id
int64
0
755k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
65
repo_stars
int64
100
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
9 values
repo_extraction_date
stringclasses
92 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
4,799
SelectionHighlight.h
rizinorg_cutter/src/common/SelectionHighlight.h
#ifndef CUTTER_SELECTIONHIGHLIGHT_H #define CUTTER_SELECTIONHIGHLIGHT_H #include <QTextEdit> class QPlainTextEdit; class QString; /** * @brief createSameWordsSelections se * @param textEdit * @param word * @return */ QList<QTextEdit::ExtraSelection> createSameWordsSelections(QPlainTextEdit *textEdit, const QString &word); /** * @brief createLineHighlight * @param cursor - a Cursor object represents the line to be highlighted * @param highlightColor - the color to be used for highlighting. The color is decided by the callee * for different usages (BP, PC, Current line, ...) * @return ExtraSelection with highlighted line */ QTextEdit::ExtraSelection createLineHighlight(const QTextCursor &cursor, QColor highlightColor); /** * @brief This function responsible to highlight the currently selected line * @param cursor - a Cursor object represents the line to be highlighted * @return ExtraSelection with highlighted line */ QTextEdit::ExtraSelection createLineHighlightSelection(const QTextCursor &cursor); /** * @brief This function responsible to highlight the program counter line * @param cursor - a Cursor object represents the line to be highlighted * @return ExtraSelection with highlighted line */ QTextEdit::ExtraSelection createLineHighlightPC(const QTextCursor &cursor); /** * @brief This function responsible to highlight a line with breakpoint * @param cursor - a Cursor object represents the line to be highlighted * @return ExtraSelection with highlighted line */ QTextEdit::ExtraSelection createLineHighlightBP(const QTextCursor &cursor); #endif // CUTTER_SELECTIONHIGHLIGHT_H
1,688
C++
.h
40
38.95
100
0.777439
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,800
BinaryTrees.h
rizinorg_cutter/src/common/BinaryTrees.h
#ifndef BINARY_TREES_H #define BINARY_TREES_H /** \file BinaryTrees.h * \brief Utilities to simplify creation of specialized augmented binary trees. */ #include <vector> #include <cstdlib> #include <climits> #include <cstdint> #include <algorithm> /** * Not really a segment tree for storing segments as referred in academic literature. Can be * considered a full, almost perfect, augmented binary tree. In the context of competitive * programming often called segment tree. * * Child classes are expected to implement updateFromChildren(NodeType&parent, NodeType& left, * NodeType& right) method which calculates inner node values from children nodes. * * \tparam NodeTypeT type of each tree element * \tparam FinalType final child class used for curiously recurring template pattern */ template<class NodeTypeT, class FinalType> class SegmentTreeBase { public: using NodePosition = size_t; using NodeType = NodeTypeT; /** * @brief Create tree with \a size leaves. * @param size number of leaves in the tree */ explicit SegmentTreeBase(size_t size) : size(size), nodeCount(2 * size), nodes(nodeCount) {} /** * @brief Create a tree with given size and initial value. * * Inner nodes are calculated from leaves. * @param size number of leaves * @param initialValue initial leave value */ SegmentTreeBase(size_t size, const NodeType &initialValue) : SegmentTreeBase(size) { init(initialValue); } protected: // Curiously recurring template pattern FinalType &This() { return static_cast<FinalType &>(*this); } // Curiously recurring template pattern const FinalType &This() const { return static_cast<const FinalType &>(*this); } size_t leavePositionToIndex(NodePosition pos) const { return pos - size; } NodePosition leaveIndexToPosition(size_t index) const { return index + size; } bool isLeave(NodePosition position) const { return position >= size; } /** * @brief Calculate inner node values from leaves. */ void buildInnerNodes() { for (size_t i = size - 1; i > 0; i--) { This().updateFromChildren(nodes[i], nodes[i << 1], nodes[(i << 1) | 1]); } } /** * @brief Initialize leaves with given value. * @param value value that will be assigned to leaves */ void init(const NodeType &value) { std::fill_n(nodes.begin() + size, size, value); buildInnerNodes(); } const size_t size; //< number of leaves and also index of left most leave const size_t nodeCount; std::vector<NodeType> nodes; }; /** * \brief Tree for point modification and range queries. */ template<class NodeType, class FinalType> class PointSetSegmentTree : public SegmentTreeBase<NodeType, FinalType> { using BaseType = SegmentTreeBase<NodeType, FinalType>; public: using BaseType::BaseType; /** * @brief Set leave \a index to \a value. * @param index Leave index, should be in the range [0,size) * @param value */ void set(size_t index, const NodeType &value) { auto pos = this->leaveIndexToPosition(index); this->nodes[pos] = value; while (pos > 1) { auto parrent = pos >> 1; this->This().updateFromChildren(this->nodes[parrent], this->nodes[pos], this->nodes[pos ^ 1]); pos = parrent; } } const NodeType &valueAtPoint(size_t index) const { return this->nodes[this->leaveIndexToPosition(index)]; } // Implement range query when necessary }; class PointSetMinTree : public PointSetSegmentTree<int, PointSetMinTree> { using BaseType = PointSetSegmentTree<int, PointSetMinTree>; public: using NodeType = int; using BaseType::BaseType; void updateFromChildren(NodeType &parent, NodeType &leftChild, NodeType &rightChild) { parent = std::min(leftChild, rightChild); } /** * @brief Find right most position with value than less than given in range [0; position]. * @param position inclusive right side of query range * @param value search for position less than this * @return returns the position with searched property or -1 if there is no such position. */ int rightMostLessThan(size_t position, int value) { auto isGood = [&](size_t pos) { return nodes[pos] < value; }; // right side exclusive range [l;r) size_t goodSubtree = 0; for (size_t l = leaveIndexToPosition(0), r = leaveIndexToPosition(position + 1); l < r; l >>= 1, r >>= 1) { if (l & 1) { if (isGood(l)) { // mark subtree as good but don't stop yet, there might be something good // further to the right goodSubtree = l; } ++l; } if (r & 1) { --r; if (isGood(r)) { goodSubtree = r; break; } } } if (!goodSubtree) { return -1; } // find rightmost good leave while (goodSubtree < size) { goodSubtree = (goodSubtree << 1) + 1; if (!isGood(goodSubtree)) { goodSubtree ^= 1; } } return leavePositionToIndex(goodSubtree); } /** * @brief Find left most position with value less than \a value in range [position; size). * @param position inclusive left side of query range * @param value search for position less than this * @return returns the position with searched property or -1 if there is no such position. */ int leftMostLessThan(size_t position, int value) { auto isGood = [&](size_t pos) { return nodes[pos] < value; }; // right side exclusive range [l;r) size_t goodSubtree = 0; for (size_t l = leaveIndexToPosition(position), r = leaveIndexToPosition(size); l < r; l >>= 1, r >>= 1) { if (l & 1) { if (isGood(l)) { goodSubtree = l; break; } ++l; } if (r & 1) { --r; if (isGood(r)) { goodSubtree = r; // mark subtree as good but don't stop yet, there might be something good // further to the left } } } if (!goodSubtree) { return -1; } // find leftmost good leave while (goodSubtree < size) { goodSubtree = (goodSubtree << 1); if (!isGood(goodSubtree)) { goodSubtree ^= 1; } } return leavePositionToIndex(goodSubtree); } }; /** * \brief Tree that supports lazily applying an operation to range. * * Each inner node has a promise value describing an operation that needs to be applied to * corresponding subtree. * * Child classes are expected to implement to pushDown(size_t nodePosition) method. Which applies * the applies the operation stored in \a promise for nodePosition to the direct children nodes. * * \tparam NodeType type of tree nodes * \tparam PromiseType type describing operation that needs to be applied to subtree * \tparam FinalType child class type for CRTP. See SegmentTreeBase */ template<class NodeType, class PromiseType, class FinalType> class LazySegmentTreeBase : public SegmentTreeBase<NodeType, FinalType> { using BaseType = SegmentTreeBase<NodeType, FinalType>; public: /** * @param size Number of tree leaves. * @param neutralPromise Promise value that doesn't modify tree nodes. */ LazySegmentTreeBase(size_t size, const PromiseType &neutralPromise) : BaseType(size), neutralPromiseElement(neutralPromise), promise(size, neutralPromise) { h = 0; size_t v = size; while (v) { v >>= 1; h++; } } LazySegmentTreeBase(size_t size, NodeType value, PromiseType neutralPromise) : LazySegmentTreeBase(size, neutralPromise) { this->init(value); } /** * @brief Calculate the tree operation over the range [\a l, \a r) * @param l inclusive range left side * @param r exclusive range right side * @param initialValue Initial value for aggregate operation. * @return Tree operation calculated over the range. */ NodeType rangeOperation(size_t l, size_t r, NodeType initialValue) { NodeType result = initialValue; l = this->leaveIndexToPosition(l); r = this->leaveIndexToPosition(r); pushDownFromRoot(l); pushDownFromRoot(r - 1); for (; l < r; l >>= 1, r >>= 1) { if (l & 1) { This().updateFromChildren(result, result, this->nodes[l++]); } if (r & 1) { This().updateFromChildren(result, result, this->nodes[--r]); } } return result; } protected: /** * @brief Ensure that all the parents of node \a p have the operation applied. * @param p Node position */ void pushDownFromRoot(typename BaseType::NodePosition p) { for (size_t i = h; i > 0; i--) { This().pushDown(p >> i); } } /** * @brief Update all the inner nodes in path from \a p to root. * @param p node position */ void updateUntilRoot(typename BaseType::NodePosition p) { while (p > 1) { auto parent = p >> 1; if (promise[parent] == neutralPromiseElement) { This().updateFromChildren(this->nodes[parent], this->nodes[p & ~size_t(1)], this->nodes[p | 1]); } p = parent; } } using BaseType::This; int h; //< Tree height const PromiseType neutralPromiseElement; std::vector<PromiseType> promise; }; /** * @brief Structure supporting range assignment and range maximum operations. */ class RangeAssignMaxTree : public LazySegmentTreeBase<int, uint8_t, RangeAssignMaxTree> { using BaseType = LazySegmentTreeBase<int, uint8_t, RangeAssignMaxTree>; public: using ValueType = int; RangeAssignMaxTree(size_t size, ValueType initialValue) : BaseType(size, initialValue, 0) {} void updateFromChildren(NodeType &parent, const NodeType &left, const NodeType &right) { parent = std::max(left, right); } void pushDown(size_t parent) { if (promise[parent]) { size_t left = (parent << 1); size_t right = (parent << 1) | 1; nodes[left] = nodes[right] = nodes[parent]; if (left < size) { promise[left] = promise[parent]; } if (right < size) { promise[right] = promise[parent]; } promise[parent] = neutralPromiseElement; } } /** * @brief Change all the elements in range [\a left, \a right) to \a value. * @param left inclusive range left side * @param right exclusive right side of range * @param value value to be assigned */ void setRange(size_t left, size_t right, NodeType value) { left = leaveIndexToPosition(left); right = leaveIndexToPosition(right); pushDownFromRoot(left); pushDownFromRoot(right - 1); for (size_t l = left, r = right; l < r; l >>= 1, r >>= 1) { if (l & 1) { nodes[l] = value; if (!isLeave(l)) { promise[l] = 1; } l += 1; } if (r & 1) { r -= 1; nodes[r] = value; if (!isLeave(r)) { promise[r] = 1; } } } updateUntilRoot(left); updateUntilRoot(right - 1); } /** * @brief Calculate biggest value in the range [l, r) * @param l inclusive left side of range * @param r exclusive right side of range * @return biggest value in given range */ int rangeMaximum(size_t l, size_t r) { return rangeOperation(l, r, std::numeric_limits<ValueType>::min()); } }; /** * @brief Structure for keeping track of minimum and maximum value set at each position. * * Supports range update and range query. * * Example: * @code{.cpp} * MinMaxAccumulateTree t(30); // operate within range [0; 30) * t.updateRange(1, 5, 10); * rangeMinMax(0, 20);// -> {10, 10} * t.updateRange(4, 6, 15); * t.updateRange(3, 10, 20); * t.rangeMinMax(0, 20); // -> {10, 20} * t.rangeMinMax(1, 3); // -> {10, 10} * t.rangeMinMax(5, 8); // -> {15, 20} * @endcode */ template<class IntegerType> class MinMaxAccumulateTree : public LazySegmentTreeBase<std::pair<IntegerType, IntegerType>, std::pair<IntegerType, IntegerType>, MinMaxAccumulateTree<IntegerType>> { // Could work with other types but that would require changing LIMITS static_assert(std::is_integral<IntegerType>::value, "Template argument IntegerType must be integer"); using MinMax = std::pair<IntegerType, IntegerType>; using ValueType = MinMax; using ThisType = MinMaxAccumulateTree<IntegerType>; using BaseType = LazySegmentTreeBase<ValueType, MinMax, ThisType>; using NodeType = typename BaseType::NodeType; using NodePosition = typename BaseType::NodePosition; static constexpr MinMax LIMITS() { return { std::numeric_limits<IntegerType>::max(), std::numeric_limits<IntegerType>::min() }; } static MinMax Combine(const MinMax &a, const MinMax &b) { return { std::min(a.first, b.first), std::max(a.second, b.second) }; } void UpdateNode(NodePosition nodePos, ValueType value) { this->nodes[nodePos] = Combine(this->nodes[nodePos], value); if (!this->isLeave(nodePos)) { this->promise[nodePos] = Combine(this->promise[nodePos], value); } } public: MinMaxAccumulateTree(size_t size, ValueType initialValue = LIMITS()) : BaseType(size, initialValue, LIMITS()) { } void updateFromChildren(NodeType &parent, const NodeType &left, const NodeType &right) { parent = Combine(left, right); } void pushDown(NodePosition parent) { size_t left = (parent << 1); size_t right = (parent << 1) | 1; this->UpdateNode(left, this->promise[parent]); this->UpdateNode(right, this->promise[parent]); this->promise[parent] = this->neutralPromiseElement; } /** * @brief Update min and max values in the range [\a left, \a right) with number \a value. * @param left inclusive range left side * @param right exclusive right side of range * @param value number to be used for updating minimum and maximum */ void updateRange(size_t left, size_t right, IntegerType value) { left = this->leaveIndexToPosition(left); right = this->leaveIndexToPosition(right); this->pushDownFromRoot(left); this->pushDownFromRoot(right - 1); MinMax pairValue { value, value }; for (size_t l = left, r = right; l < r; l >>= 1, r >>= 1) { if (l & 1) { UpdateNode(l, pairValue); l += 1; } if (r & 1) { r -= 1; UpdateNode(r, pairValue); } } this->updateUntilRoot(left); this->updateUntilRoot(right - 1); } /** * @brief Calculate minimum and maximum value in the range [l, r) * @param l inclusive left side of range * @param r exclusive right side of range * @return std::pair {min, max} */ MinMax rangeMinMax(size_t l, size_t r) { return this->rangeOperation(l, r, this->neutralPromiseElement); } }; #endif // BINARY_TREES_H
16,266
C++
.h
460
27.515217
100
0.598299
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,802
AddressableItemModel.h
rizinorg_cutter/src/common/AddressableItemModel.h
#ifndef ADDRESSABLEITEMMODEL_H #define ADDRESSABLEITEMMODEL_H #include <QAbstractItemModel> #include <QSortFilterProxyModel> #include <QAbstractItemModel> #include "core/CutterCommon.h" class CUTTER_EXPORT AddressableItemModelI { public: virtual RVA address(const QModelIndex &index) const = 0; /** * @brief Get name for item, optional. * @param index item intex * @return Item name or empty QString if item doesn't have short descriptive name. */ virtual QString name(const QModelIndex &index) const { Q_UNUSED(index) return QString(); } virtual QAbstractItemModel *asItemModel() = 0; }; template<class ParentModel = QAbstractItemModel> class CUTTER_EXPORT AddressableItemModel : public ParentModel, public AddressableItemModelI { static_assert(std::is_base_of<QAbstractItemModel, ParentModel>::value, "ParentModel needs to inherit from QAbstractItemModel"); public: explicit AddressableItemModel(QObject *parent = nullptr) : ParentModel(parent) {} virtual ~AddressableItemModel() {} QAbstractItemModel *asItemModel() { return this; } }; class CUTTER_EXPORT AddressableFilterProxyModel : public AddressableItemModel<QSortFilterProxyModel> { using ParentClass = AddressableItemModel<QSortFilterProxyModel>; public: AddressableFilterProxyModel(AddressableItemModelI *sourceModel, QObject *parent); RVA address(const QModelIndex &index) const override; QString name(const QModelIndex &) const override; void setSourceModel(AddressableItemModelI *sourceModel); private: void setSourceModel(QAbstractItemModel *sourceModel) override; // Don't use this directly AddressableItemModelI *addressableSourceModel; }; #endif // ADDRESSABLEITEMMODEL_H
1,773
C++
.h
45
35.444444
100
0.776937
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,803
ProgressIndicator.h
rizinorg_cutter/src/common/ProgressIndicator.h
#ifndef PROGRESSINDICATOR_H #define PROGRESSINDICATOR_H #include <QWidget> class ProgressIndicator : public QWidget { public: ProgressIndicator(QWidget *parent = nullptr); virtual ~ProgressIndicator(); QSize minimumSizeHint() const override; QSize sizeHint() const override; bool getProgressIndicatorVisible() const { return progressIndicatorVisible; } void setProgressIndicatorVisible(bool visible); bool getAnimating() const { return animating; } void setAnimating(bool animating); protected: void timerEvent(QTimerEvent *event) override; void paintEvent(QPaintEvent *event) override; private: bool animating = true; bool progressIndicatorVisible = true; int animationTimerId = 0; int animationState = 0; void updateAnimationTimer(); }; #endif // PROGRESSINDICATOR_H
840
C++
.h
25
29.76
81
0.773632
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,804
CommandTask.h
rizinorg_cutter/src/common/CommandTask.h
#ifndef COMMANDTASK_H #define COMMANDTASK_H #include "common/AsyncTask.h" #include "core/Cutter.h" class CUTTER_EXPORT CommandTask : public AsyncTask { Q_OBJECT public: enum ColorMode { DISABLED = COLOR_MODE_DISABLED, MODE_16 = COLOR_MODE_16, MODE_256 = COLOR_MODE_256, MODE_16M = COLOR_MODE_16M }; CommandTask(const QString &cmd, ColorMode colorMode = ColorMode::DISABLED); QString getTitle() override { return tr("Running Command"); } signals: void finished(const QString &result); protected: void runTask() override; private: QString cmd; ColorMode colorMode; }; #endif // COMMANDTASK_H
668
C++
.h
25
22.6
79
0.709321
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,805
TempConfig.h
rizinorg_cutter/src/common/TempConfig.h
#ifndef TEMPCONFIG_H #define TEMPCONFIG_H #include "core/CutterCommon.h" #include <QString> #include <QVariant> /** * @brief Class for temporary modifying Rizin `e` configuration. * * Modified values will be restored at the end of scope. This is useful when using a Rizin command * that can only be configured using `e` configuration and doesn't accept arguments. TempConfig::set * calls can be chained. If a command or Rizin method accepts arguments directly it is preferred to * use those instead of temporary modifying global configuration. * * \code * { * TempConfig tempConfig; * tempConfig.set("asm.arch", "x86").set("asm.comments", false); * // config automatically restored at the end of scope * } * \endcode */ class CUTTER_EXPORT TempConfig { public: TempConfig() = default; ~TempConfig(); TempConfig &set(const QString &key, const QString &value); TempConfig &set(const QString &key, const char *value); TempConfig &set(const QString &key, int value); TempConfig &set(const QString &key, bool value); private: TempConfig(const TempConfig &) = delete; TempConfig &operator=(const TempConfig &) = delete; QMap<QString, QVariant> resetValues; }; #endif // TEMPCONFIG_H
1,247
C++
.h
36
32.027778
100
0.734219
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,806
SvgIconEngine.h
rizinorg_cutter/src/common/SvgIconEngine.h
#ifndef SVGICONENGINE_H #define SVGICONENGINE_H #include <QIconEngine> #include <QPalette> class SvgIconEngine : public QIconEngine { private: QByteArray svgData; public: explicit SvgIconEngine(const QString &filename); SvgIconEngine(const QString &filename, const QColor &tintColor); SvgIconEngine(const QString &filename, QPalette::ColorRole colorRole); void paint(QPainter *painter, const QRect &rect, QIcon::Mode mode, QIcon::State state) override; QIconEngine *clone() const override; QPixmap pixmap(const QSize &size, QIcon::Mode mode, QIcon::State state) override; }; #endif // SVGICONENGINE_H
636
C++
.h
17
34.352941
100
0.777778
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,807
Json.h
rizinorg_cutter/src/common/Json.h
#ifndef CUTTER_JSON_H #define CUTTER_JSON_H #include "core/Cutter.h" #include <QJsonValue> static inline RVA JsonValueGetRVA(const QJsonValue &value, RVA defaultValue = RVA_INVALID) { bool ok; RVA ret = value.toVariant().toULongLong(&ok); if (!ok) { return defaultValue; } return ret; } #endif // CUTTER_JSON_H
344
C++
.h
14
21.214286
90
0.707692
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,808
PythonAPI.h
rizinorg_cutter/src/common/PythonAPI.h
#ifndef PYTHONAPI_H #define PYTHONAPI_H #define Py_LIMITED_API 0x03050000 #include <Python.h> PyObject *PyInit_api(); #endif // PYTHONAPI_H
143
C++
.h
6
22.333333
33
0.791045
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,809
StringsTask.h
rizinorg_cutter/src/common/StringsTask.h
#ifndef STRINGSASYNCTASK_H #define STRINGSASYNCTASK_H #include "common/AsyncTask.h" #include "core/Cutter.h" class StringsTask : public AsyncTask { Q_OBJECT public: QString getTitle() override { return tr("Searching for Strings"); } signals: void stringSearchFinished(const QList<StringDescription> &strings); protected: void runTask() override { auto strings = Core()->getAllStrings(); emit stringSearchFinished(strings); } }; #endif // STRINGSASYNCTASK_H
504
C++
.h
19
23.052632
71
0.742678
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,810
DirectionalComboBox.h
rizinorg_cutter/src/common/DirectionalComboBox.h
#pragma once #include <QComboBox> /** * @brief Custom QComboBox created to prevent the menu popup from opening up at different * offsets for different items, which may result in list items being rendered outside * of the screen/containing widget. */ class DirectionalComboBox : public QComboBox { Q_OBJECT public: explicit DirectionalComboBox(QWidget *parent = nullptr, bool upwards = true); void setPopupDirection(bool upwards); private: bool popupUpwards; void showPopup(); };
522
C++
.h
17
28
92
0.752
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,811
IOModesController.h
rizinorg_cutter/src/common/IOModesController.h
#ifndef IOMODESCONTROLLER_H #define IOMODESCONTROLLER_H #include "core/Cutter.h" class IOModesController : public QObject { Q_OBJECT public: enum class Mode { READ_ONLY, CACHE, WRITE }; bool prepareForWriting(); bool canWrite(); bool allChangesComitted(); Mode getIOMode(); void setIOMode(Mode mode); public slots: bool askCommitUnsavedChanges(); }; #endif // IOMODESCONTROLLER_H
417
C++
.h
17
21.352941
48
0.746835
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,812
AnalysisTask.h
rizinorg_cutter/src/common/AnalysisTask.h
#ifndef ANALTHREAD_H #define ANALTHREAD_H #include "common/AsyncTask.h" #include "core/Cutter.h" #include "common/InitialOptions.h" class CutterCore; class MainWindow; class InitialOptionsDialog; class AnalysisTask : public AsyncTask { Q_OBJECT public: explicit AnalysisTask(); ~AnalysisTask(); QString getTitle() override; void setOptions(const InitialOptions &options) { this->options = options; } void interrupt() override; bool getOpenFileFailed() { return openFailed; } protected: void runTask() override; signals: void openFileFailed(); private: InitialOptions options; bool openFailed = false; }; #endif // ANALTHREAD_H
684
C++
.h
27
22.222222
79
0.76087
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,813
SettingsUpgrade.h
rizinorg_cutter/src/common/SettingsUpgrade.h
#ifndef COMMON_SETTINGS_UPGRADE_H #define COMMON_SETTINGS_UPGRADE_H #include <QSettings> #include <core/Cutter.h> namespace Cutter { void initializeSettings(); /** * @brief Check if Cutter should offer importing settings from version that can't be directly * updated. * @return True if this is first time running Cutter and r2 based Cutter <= 1.12 settings exist. */ bool shouldOfferSettingImport(); /** * @brief Ask user if Cutter should import settings from pre-rizin Cutter. * * This function assume that QApplication isn't running yet. */ void showSettingImportDialog(int &argc, char **argv); void migrateThemes(); } #endif // COMMON_SETTINGS_UPGRADE_H
668
C++
.h
21
30.285714
96
0.77795
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,814
bindings.h
rizinorg_cutter/src/bindings/bindings.h
#ifndef CUTTER_BINDINGS_H #define CUTTER_BINDINGS_H #define QT_ANNOTATE_ACCESS_SPECIFIER(a) __attribute__((annotate(#a))) #include "../core/Cutter.h" #include "../common/Configuration.h" #include "../core/MainWindow.h" #include "../widgets/CutterDockWidget.h" #include "../plugins/CutterPlugin.h" #include "../menus/AddressableItemContextMenu.h" #endif // CUTTER_BINDINGS_H
378
C++
.h
10
36.4
69
0.758242
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,815
tapsite.cpp
TranslucentTB_TranslucentTB/ExplorerTAP/tapsite.cpp
#include "tapsite.hpp" #include "constants.hpp" winrt::weak_ref<VisualTreeWatcher> TAPSite::s_VisualTreeWatcher; wil::unique_event_nothrow TAPSite::GetReadyEvent() { wil::unique_event_nothrow readyEvent; winrt::check_hresult(readyEvent.create(wil::EventOptions::None, TAP_READY_EVENT.c_str())); return readyEvent; } HRESULT TAPSite::SetSite(IUnknown *pUnkSite) try { // only ever 1 VTW at once if (s_VisualTreeWatcher.get()) { throw winrt::hresult_illegal_method_call(); } site.copy_from(pUnkSite); if (site) { s_VisualTreeWatcher = winrt::make_self<VisualTreeWatcher>(site); wil::unique_event_nothrow readyEvent; if (readyEvent.try_open(TAP_READY_EVENT.c_str(), EVENT_MODIFY_STATE)) { readyEvent.SetEvent(); } } return S_OK; } catch (...) { return winrt::to_hresult(); } HRESULT TAPSite::GetSite(REFIID riid, void **ppvSite) noexcept { return site.as(riid, ppvSite); }
907
C++
.cpp
36
23.166667
91
0.750869
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,816
taskbarappearanceservice.cpp
TranslucentTB_TranslucentTB/ExplorerTAP/taskbarappearanceservice.cpp
#include "taskbarappearanceservice.hpp" #include <RpcProxy.h> #include <shellapi.h> #include <wil/cppwinrt_helpers.h> #include "constants.hpp" #include "util/color.hpp" extern "C" { _Check_return_ HRESULT STDAPICALLTYPE DLLGETCLASSOBJECT_ENTRY(_In_ REFCLSID rclsid, _In_ REFIID riid, _Outptr_ void** ppv); } DWORD TaskbarAppearanceService::s_ProxyStubRegistrationCookie = 0; TaskbarAppearanceService::TaskbarAppearanceService() : m_RegisterCookie(0), m_XamlThreadQueue(winrt::Windows::System::DispatcherQueue::GetForCurrentThread()) { InstallProxyStub(); winrt::check_hresult(RegisterActiveObject(static_cast<ITaskbarAppearanceService*>(this), CLSID_TaskbarAppearanceService, ACTIVEOBJECT_STRONG, &m_RegisterCookie)); } HRESULT TaskbarAppearanceService::GetVersion(DWORD* apiVersion) noexcept { if (apiVersion) { *apiVersion = TAP_API_VERSION; } return S_OK; } HRESULT TaskbarAppearanceService::SetTaskbarAppearance(HWND taskbar, TaskbarBrush brush, UINT color) try { for (const auto& [handle, info] : m_Taskbars) { if (GetAncestor(info.window, GA_PARENT) == taskbar) { if (info.background.control && info.background.originalFill) { const winrt::Windows::UI::Color tint = Util::Color::FromABGR(color); wux::Media::Brush newBrush = nullptr; if (brush == Acrylic) { wux::Media::AcrylicBrush acrylicBrush; // on the taskbar, using Backdrop instead of HostBackdrop // makes the effect still show what's behind, but also not disable itself // when the window isn't active // this is because it sources what's behind the XAML, and the taskbar window // is transparent so what's behind is actually the content behind the window // (it doesn't need to poke a hole like HostBackdrop) acrylicBrush.BackgroundSource(wux::Media::AcrylicBackgroundSource::Backdrop); acrylicBrush.TintColor(tint); newBrush = std::move(acrylicBrush); } else if (brush == SolidColor) { wux::Media::SolidColorBrush solidBrush; solidBrush.Color(tint); newBrush = std::move(solidBrush); } info.background.control.Fill(newBrush); } break; } } return S_OK; } catch (...) { return winrt::to_hresult(); } HRESULT TaskbarAppearanceService::ReturnTaskbarToDefaultAppearance(HWND taskbar) try { for (const auto& [handle, info] : m_Taskbars) { if (GetAncestor(info.window, GA_PARENT) == taskbar) { RestoreDefaultControlFill(info.background); break; } } return S_OK; } catch (...) { return winrt::to_hresult(); } HRESULT TaskbarAppearanceService::SetTaskbarBorderVisibility(HWND taskbar, BOOL visible) try { for (const auto& [handle, info] : m_Taskbars) { if (GetAncestor(info.window, GA_PARENT) == taskbar) { if (visible) { RestoreDefaultControlFill(info.border); } else { if (info.border.control && info.border.originalFill) { wux::Media::SolidColorBrush brush; brush.Opacity(0); info.border.control.Fill(brush); } } break; } } return S_OK; } catch (...) { return winrt::to_hresult(); } HRESULT TaskbarAppearanceService::RestoreAllTaskbarsToDefault() try { for (const auto& [handle, info] : m_Taskbars) { RestoreDefaultControlFill(info.background); RestoreDefaultControlFill(info.border); } return S_OK; } catch (...) { return winrt::to_hresult(); } HRESULT TaskbarAppearanceService::RestoreAllTaskbarsToDefaultWhenProcessDies(DWORD pid) { if (!m_Process) { m_Process.reset(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, false, pid)); if (!m_Process) [[unlikely]] { return HRESULT_FROM_WIN32(GetLastError()); } if (!RegisterWaitForSingleObject(m_WaitHandle.put(), m_Process.get(), ProcessWaitCallback, this, INFINITE, WT_EXECUTEONLYONCE)) { m_Process.reset(); return HRESULT_FROM_WIN32(GetLastError()); } return S_OK; } else { if (GetProcessId(m_Process.get()) == pid) { return S_OK; // already watching for this process to die. } else { return E_ILLEGAL_METHOD_CALL; } } } void TaskbarAppearanceService::RegisterTaskbar(InstanceHandle frameHandle, HWND window) { m_Taskbars.insert_or_assign(frameHandle, TaskbarInfo { { }, { }, window }); } void TaskbarAppearanceService::RegisterTaskbarBackground(InstanceHandle frameHandle, wux::Shapes::Shape element) { if (const auto it = m_Taskbars.find(frameHandle); it != m_Taskbars.end()) { it->second.background.control = element; it->second.background.originalFill = element.Fill(); } } void TaskbarAppearanceService::RegisterTaskbarBorder(InstanceHandle frameHandle, wux::Shapes::Shape element) { if (const auto it = m_Taskbars.find(frameHandle); it != m_Taskbars.end()) { it->second.border.control = element; it->second.border.originalFill = element.Fill(); } } void TaskbarAppearanceService::UnregisterTaskbar(InstanceHandle frameHandle) { m_Taskbars.erase(frameHandle); } TaskbarAppearanceService::~TaskbarAppearanceService() { // wait for all callbacks to be done, as they have a raw pointer to the instance. winrt::check_bool(UnregisterWaitEx(m_WaitHandle.get(), INVALID_HANDLE_VALUE)); m_WaitHandle.release(); m_Process.reset(); winrt::check_hresult(RestoreAllTaskbarsToDefault()); winrt::check_hresult(RevokeActiveObject(m_RegisterCookie, nullptr)); } void TaskbarAppearanceService::InstallProxyStub() { if (!s_ProxyStubRegistrationCookie) { winrt::com_ptr<IUnknown> proxyStub; winrt::check_hresult(DLLGETCLASSOBJECT_ENTRY(PROXY_CLSID_IS, winrt::guid_of<decltype(proxyStub)::type>(), proxyStub.put_void())); winrt::check_hresult(CoRegisterClassObject(PROXY_CLSID_IS, proxyStub.get(), CLSCTX_INPROC_SERVER, REGCLS_MULTIPLEUSE, &s_ProxyStubRegistrationCookie)); winrt::check_hresult(CoRegisterPSClsid(IID_ITaskbarAppearanceService, PROXY_CLSID_IS)); winrt::check_hresult(CoRegisterPSClsid(IID_IVersionedApi, PROXY_CLSID_IS)); } } void TaskbarAppearanceService::UninstallProxyStub() { if (s_ProxyStubRegistrationCookie) { winrt::check_hresult(CoRevokeClassObject(s_ProxyStubRegistrationCookie)); } } winrt::fire_and_forget TaskbarAppearanceService::OnProcessDied() { m_WaitHandle.reset(); m_Process.reset(); const auto self_weak = get_weak(); co_await wil::resume_foreground(m_XamlThreadQueue); if (const auto self = self_weak.get()) { self->RestoreAllTaskbarsToDefault(); } } void TaskbarAppearanceService::RestoreDefaultControlFill(const ControlInfo<wux::Shapes::Shape> &info) { if (info.control && info.originalFill) { info.control.Fill(info.originalFill); } } void TaskbarAppearanceService::ProcessWaitCallback(void* parameter, BOOLEAN) { reinterpret_cast<TaskbarAppearanceService *>(parameter)->OnProcessDied(); }
6,704
C++
.cpp
224
27.299107
163
0.757877
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,817
visualtreewatcher.cpp
TranslucentTB_TranslucentTB/ExplorerTAP/visualtreewatcher.cpp
#include "visualtreewatcher.hpp" #include <windows.ui.xaml.hosting.desktopwindowxamlsource.h> #include "undefgetcurrenttime.h" #include <winrt/Windows.UI.Xaml.Hosting.h> #include "redefgetcurrenttime.h" VisualTreeWatcher::VisualTreeWatcher(winrt::com_ptr<IUnknown> site) : m_XamlDiagnostics(site.as<IXamlDiagnostics>()), m_AppearanceService(winrt::make_self<TaskbarAppearanceService>()) { winrt::check_hresult(m_XamlDiagnostics.as<IVisualTreeService3>()->AdviseVisualTreeChange(this)); } HRESULT VisualTreeWatcher::OnVisualTreeChange(ParentChildRelation relation, VisualElement element, VisualMutationType mutationType) try { switch (mutationType) { case Add: { const std::wstring_view type { element.Type, SysStringLen(element.Type) }; if (type == winrt::name_of<wuxh::DesktopWindowXamlSource>()) { // we cannot check if the source contains a taskbar here, // because when a new taskbar gets added the source gets created // without containing anything initially. save the source to a set // of handles so we can later match it against the added TaskbarFrame. m_NonMatchingXamlSources.insert(element.Handle); } else if (type == L"Taskbar.TaskbarFrame") { // assume it goes DesktopWindowXamlSource -> RootGrid -> TaskbarFrame. // we need RootGrid's pointer to find the right source based on its contents. const auto rootGrid = FromHandle<wux::UIElement>(relation.Parent); for (auto it = m_NonMatchingXamlSources.begin(); it != m_NonMatchingXamlSources.end(); ++it) { const auto xamlSource = FromHandle<wuxh::DesktopWindowXamlSource>(*it); wux::UIElement content = nullptr; try { content = xamlSource.Content(); } catch (const winrt::hresult_wrong_thread&) { continue; } if (content == rootGrid) { const auto nativeSource = xamlSource.as<IDesktopWindowXamlSourceNative>(); HWND hwnd = nullptr; winrt::check_hresult(nativeSource->get_WindowHandle(&hwnd)); m_AppearanceService->RegisterTaskbar(element.Handle, hwnd); m_NonMatchingXamlSources.erase(it); break; } } } else if (type == winrt::name_of<wux::Shapes::Rectangle>()) { const std::wstring_view name { element.Name, SysStringLen(element.Name) }; const auto backgroundFill = name == L"BackgroundFill"; const auto backgroundStroke = name == L"BackgroundStroke"; if (backgroundFill || backgroundStroke) { if (const auto frame = FindParent(L"TaskbarFrame", FromHandle<wux::FrameworkElement>(relation.Parent))) { InstanceHandle handle = 0; winrt::check_hresult(m_XamlDiagnostics->GetHandleFromIInspectable(reinterpret_cast<::IInspectable*>(winrt::get_abi(frame)), &handle)); const auto shape = FromHandle<wux::Shapes::Rectangle>(element.Handle); if (backgroundFill) { m_AppearanceService->RegisterTaskbarBackground(handle, shape); } else if (backgroundStroke) { m_AppearanceService->RegisterTaskbarBorder(handle, shape); } } } } break; } case Remove: // only element.Handle is valid m_AppearanceService->UnregisterTaskbar(element.Handle); m_NonMatchingXamlSources.erase(element.Handle); break; } return S_OK; } catch (...) { return winrt::to_hresult(); } HRESULT VisualTreeWatcher::OnElementStateChanged(InstanceHandle, VisualElementState, LPCWSTR) noexcept { return S_OK; } wux::FrameworkElement VisualTreeWatcher::FindParent(std::wstring_view name, wux::FrameworkElement element) { const auto parent = wux::Media::VisualTreeHelper::GetParent(element).try_as<wux::FrameworkElement>(); if (parent) { if (parent.Name() == name) { return parent; } else { return FindParent(name, parent); } } else { return nullptr; } }
3,750
C++
.cpp
113
29.663717
139
0.738411
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,818
api.cpp
TranslucentTB_TranslucentTB/ExplorerTAP/api.cpp
#include "api.hpp" #include <libloaderapi.h> #include <wil/resource.h> #include "constants.hpp" #include "tapsite.hpp" #include "win32.hpp" #include "taskbarappearanceservice.hpp" #include "util/string_macros.hpp" using PFN_INITIALIZE_XAML_DIAGNOSTICS_EX = decltype(&InitializeXamlDiagnosticsEx); HRESULT InjectExplorerTAP(DWORD pid, REFIID riid, LPVOID* ppv) try { TaskbarAppearanceService::InstallProxyStub(); winrt::com_ptr<IUnknown> service; HRESULT hr = GetActiveObject(CLSID_TaskbarAppearanceService, nullptr, service.put()); if (hr == MK_E_UNAVAILABLE) { const auto event = TAPSite::GetReadyEvent(); const auto [location, hr2] = win32::GetDllLocation(wil::GetModuleInstanceHandle()); if (FAILED(hr2)) [[unlikely]] { return hr2; } const wil::unique_hmodule wux(LoadLibraryEx(L"Windows.UI.Xaml.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)); if (!wux) [[unlikely]] { return HRESULT_FROM_WIN32(GetLastError()); } const auto ixde = reinterpret_cast<PFN_INITIALIZE_XAML_DIAGNOSTICS_EX>(GetProcAddress(wux.get(), UTIL_STRINGIFY_UTF8(InitializeXamlDiagnosticsEx))); if (!ixde) [[unlikely]] { return HRESULT_FROM_WIN32(GetLastError()); } uint8_t attempts = 0; do { // We need this to exist because XAML Diagnostics can only be initialized once per thread // future calls simply return S_OK without doing anything. // But we need to be able to initialize it again if Explorer restarts. So we create a thread // that is discardable to do the initialization from. std::thread([&hr, ixde, pid, &location] { hr = ixde(L"VisualDiagConnection1", pid, nullptr, location.c_str(), CLSID_TAPSite, nullptr); }).join(); if (SUCCEEDED(hr)) { break; } else { ++attempts; Sleep(500); } } while (FAILED(hr) && attempts < 60); // 60 * 500ms = 30s if (FAILED(hr)) [[unlikely]] { return hr; } static constexpr DWORD TIMEOUT = #ifdef _DEBUG // do not timeout on debug builds, to allow debugging the DLL while it's loading in explorer INFINITE; #else 5000; #endif if (!event.wait(TIMEOUT)) [[unlikely]] { return HRESULT_FROM_WIN32(WAIT_TIMEOUT); } hr = GetActiveObject(CLSID_TaskbarAppearanceService, nullptr, service.put()); } if (FAILED(hr)) [[unlikely]] { return hr; } DWORD version = 0; hr = service.as<IVersionedApi>()->GetVersion(&version); if (SUCCEEDED(hr)) { if (version != TAP_API_VERSION) { return HRESULT_FROM_WIN32(ERROR_PRODUCT_VERSION); } } else { return hr; } return service.as(riid, ppv); } catch (...) { return winrt::to_hresult(); }
2,608
C++
.cpp
94
24.829787
150
0.713656
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,819
dllmain.cpp
TranslucentTB_TranslucentTB/ExplorerTAP/dllmain.cpp
#include "arch.h" #include <libloaderapi.h> #include <windef.h> #include "taskbarappearanceservice.hpp" BOOL WINAPI DllMain(HINSTANCE, DWORD fdwReason, LPVOID) noexcept { switch (fdwReason) { case DLL_PROCESS_DETACH: TaskbarAppearanceService::UninstallProxyStub(); break; } return true; }
301
C++
.cpp
14
19.642857
64
0.795775
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,820
module.cpp
TranslucentTB_TranslucentTB/ExplorerTAP/module.cpp
#include <combaseapi.h> #include "winrt.hpp" #include "tapsite.hpp" #include "simplefactory.hpp" _Use_decl_annotations_ STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv) try { if (rclsid == CLSID_TAPSite) { *ppv = nullptr; return winrt::make<SimpleFactory<TAPSite>>().as(riid, ppv); } else { return CLASS_E_CLASSNOTAVAILABLE; } } catch (...) { return winrt::to_hresult(); }
407
C++
.cpp
20
18.6
94
0.732468
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,821
log.cpp
TranslucentTB_TranslucentTB/ProgramLog/log.cpp
#include "log.hpp" #include <chrono> #include <debugapi.h> #include <spdlog/spdlog.h> #include <spdlog/sinks/msvc_sink.h> #include <spdlog/logger.h> #include "winrt.hpp" #include "appinfo.hpp" #include "config/config.hpp" #include "error/error.hpp" #include "error/winrt.hpp" #include "error/std.hpp" std::atomic<Log::InitStatus> Log::s_LogInitStatus = Log::InitStatus::NotInitialized; std::weak_ptr<lazy_file_sink_mt> Log::s_LogSink; std::time_t Log::GetProcessCreationTime() noexcept { FILETIME creationTime, exitTime, kernelTime, userTime; if (GetProcessTimes(GetCurrentProcess(), &creationTime, &exitTime, &kernelTime, &userTime)) { using winrt::clock; return clock::to_time_t(clock::from_file_time(creationTime)); } else { // Fallback to current time using std::chrono::system_clock; return system_clock::to_time_t(system_clock::now()); } } std::filesystem::path Log::GetPath(const std::optional<std::filesystem::path> &storageFolder) { std::filesystem::path path; if (storageFolder) { path = *storageFolder / L"TempState"; } else { std::error_code code; path = std::filesystem::temp_directory_path(code); if (!code) { path /= APP_NAME; } else { StdErrorCodeHandle(code, spdlog::level::err, L"Failed to get log file path. Logs won't be available during this session"); return { }; } } path /= std::format(L"{}.log", GetProcessCreationTime()); return path; } void Log::LogErrorHandler(const std::string &message) { if (IsDebuggerPresent()) { static std::atomic_size_t counter = 0; OutputDebugStringA(std::format("[*** LOG ERROR {:04} ***] {}\n", counter++, message).c_str()); } } bool Log::IsInitialized() noexcept { return s_LogInitStatus == InitStatus::Initialized; } std::shared_ptr<lazy_file_sink_mt> Log::GetSink() noexcept { if (IsInitialized()) { return s_LogSink.lock(); } else { return nullptr; } } void Log::Initialize(const std::optional<std::filesystem::path> &storageFolder) { auto expected = InitStatus::NotInitialized; if (s_LogInitStatus.compare_exchange_strong(expected, InitStatus::Initializing)) { auto defaultLogger = std::make_shared<spdlog::logger>("", std::make_shared<spdlog::sinks::windebug_sink_st>()); if (auto path = GetPath(storageFolder); !path.empty()) { auto fileLog = std::make_shared<lazy_file_sink_mt>(std::move(path)); fileLog->set_level(Config::DEFAULT_LOG_VERBOSITY); s_LogSink = fileLog; defaultLogger->sinks().push_back(std::move(fileLog)); } spdlog::set_formatter(std::make_unique<spdlog::pattern_formatter>(spdlog::pattern_time_type::utc)); spdlog::set_level(spdlog::level::trace); spdlog::flush_on(spdlog::level::off); spdlog::set_error_handler(LogErrorHandler); spdlog::initialize_logger(defaultLogger); spdlog::set_default_logger(std::move(defaultLogger)); s_LogInitStatus = InitStatus::Initialized; } else { throw std::logic_error("Log::Initialize should only be called once"); } }
2,960
C++
.cpp
102
26.764706
125
0.728903
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,822
lazyfilesink.cpp
TranslucentTB_TranslucentTB/ProgramLog/lazyfilesink.cpp
#include "lazyfilesink.hpp" #include <fileapi.h> #include <utility> #include <wil/safecast.h> #include "winrt.hpp" #include "appinfo.hpp" #include "constants.hpp" #include "error/error.hpp" #include "error/std.hpp" #include "error/win32.hpp" #include "error/winrt.hpp" template<typename Mutex> lazy_sink_state lazy_file_sink<Mutex>::state() { std::scoped_lock guard(this->mutex_); if (m_Tried) { return m_Handle ? lazy_sink_state::opened : lazy_sink_state::failed; } else { return lazy_sink_state::nothing_logged; } } template<typename Mutex> void lazy_file_sink<Mutex>::sink_it_(const spdlog::details::log_msg &msg) { open(); if (m_Handle) { spdlog::memory_buf_t formatted; this->formatter_->format(msg, formatted); write(formatted); } } template<typename Mutex> void lazy_file_sink<Mutex>::flush_() { if (m_Handle) { if (!FlushFileBuffers(m_Handle.get())) { LastErrorHandle(spdlog::level::trace, L"Failed to flush log file."); } } } template<typename Mutex> void lazy_file_sink<Mutex>::open() { if (!std::exchange(m_Tried, true)) { std::error_code err; std::filesystem::create_directories(m_File.parent_path(), err); if (!err) { m_Handle.reset(CreateFile(m_File.c_str(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, nullptr)); if (m_Handle) { write(UTF8_BOM); } else { LastErrorHandle(spdlog::level::err, L"Failed to create log file. Logs won't be available during this session."); } } else { StdErrorCodeHandle(err, spdlog::level::err, L"Failed to create log directory. Logs won't be available during this session."); } } } template<typename Mutex> template<typename T> void lazy_file_sink<Mutex>::write(const T &thing) { DWORD bytesWritten; if (WriteFile(m_Handle.get(), thing.data(), wil::safe_cast<DWORD>(thing.size()), &bytesWritten, nullptr)) { if (bytesWritten != thing.size()) [[unlikely]] { MessagePrint(spdlog::level::trace, L"Wrote less characters than there is in log entry?"); } } else { LastErrorHandle(spdlog::level::trace, L"Failed to write log entry to file."); } } // We don't actually use the singlethreaded sink. template class lazy_file_sink<std::mutex>;
2,258
C++
.cpp
92
22.26087
162
0.716605
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,824
error.cpp
TranslucentTB_TranslucentTB/ProgramLog/error/error.cpp
#include "error.hpp" #include <debugapi.h> #include <intrin.h> #include <spdlog/spdlog.h> #include <string> #ifdef _DEBUG #include <processthreadsapi.h> #endif #include <wil/resource.h> #include <winnt.h> #include "../log.hpp" #include "std.hpp" #include "util/string_macros.hpp" #include "win32.hpp" bool Error::impl::ShouldLogInternal(spdlog::level::level_enum level) { // implicitly checks if logging is initialized. if (const auto sink = Log::GetSink()) { return sink->should_log(level) || IsDebuggerPresent(); } return false; } void Error::impl::Log(std::wstring_view msg, spdlog::level::level_enum level, std::source_location location) { spdlog::log({ location.file_name(), static_cast<int>(location.line()), location.function_name() }, level, msg); } std::wstring Error::impl::GetLogMessage(std::wstring_view message, std::wstring_view error_message) { if (!error_message.empty()) { std::wstring logMessage; logMessage.reserve(message.length() + 2 + error_message.length() + 1); logMessage += message; logMessage += L" ("; logMessage += error_message; logMessage += L")"; return logMessage; } else { return std::wstring(message); } } template<> void Error::impl::Handle<spdlog::level::err>(std::wstring_view message, std::wstring_view error_message, std::source_location location) { auto dialogBoxThread = HandleCommon(spdlog::level::err, message, error_message, location, UTIL_WIDEN(UTF8_ERROR_TITLE), APP_NAME L" has encountered an error.", MB_ICONWARNING); if (dialogBoxThread.joinable()) { dialogBoxThread.detach(); } else { DebugBreak(); } } template<> void Error::impl::Handle<spdlog::level::critical>(std::wstring_view message, std::wstring_view error_message, std::source_location location) { HandleCriticalCommon(message, error_message, location); __fastfail(FAST_FAIL_FATAL_APP_EXIT); } std::thread Error::impl::HandleCommon(spdlog::level::level_enum level, std::wstring_view message, std::wstring_view error_message, std::source_location location, Util::null_terminated_wstring_view title, std::wstring_view description, unsigned int type) { // allow calls to err handling without needing to initialize logging if (Log::IsInitialized()) { Log(GetLogMessage(message, error_message), level, location); } if (!IsDebuggerPresent()) { std::size_t messageLength = description.length() + 2 + message.length(); const bool hasErrorMessage = !error_message.empty(); if (hasErrorMessage) { messageLength += 2; messageLength += error_message.length(); } std::wstring dialogMessage; dialogMessage.reserve(messageLength); dialogMessage += description; dialogMessage += L"\n\n"; dialogMessage += message; if (hasErrorMessage) { dialogMessage += L"\n\n"; dialogMessage += error_message; } return std::thread([title, type, body = std::move(dialogMessage)]() noexcept { MessageBoxEx(nullptr, body.c_str(), title.c_str(), type | MB_OK | MB_SETFOREGROUND, MAKELANGID(LANG_ENGLISH, SUBLANG_NEUTRAL)); }); } else { return {}; } } void Error::impl::HandleCriticalCommon(std::wstring_view message, std::wstring_view error_message, std::source_location location) { auto dialogBoxThread = HandleCommon(spdlog::level::critical, message, error_message, location, UTIL_WIDEN(UTF8_ERROR_TITLE), APP_NAME L" has encountered a fatal error and cannot continue executing.", MB_ICONERROR | MB_TOPMOST); if (dialogBoxThread.joinable()) { dialogBoxThread.join(); } }
3,472
C++
.cpp
107
30.28972
253
0.740674
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,825
winrt.cpp
TranslucentTB_TranslucentTB/ProgramLog/error/winrt.cpp
#include "winrt.hpp" #include <intrin.h> #include <roerrorapi.h> #include <wil/resource.h> #include <winnt.h> #include "util/strings.hpp" #include "win32.hpp" std::wstring Error::impl::FormatIRestrictedErrorInfo(HRESULT result, BSTR description) { return FormatHRESULT(result, Util::Trim({ description, SysStringLen(description) })); } void Error::impl::HandleCriticalWithErrorInfo(std::wstring_view message, std::wstring_view error_message, std::source_location location, HRESULT err, IRestrictedErrorInfo* errInfo) { HandleCriticalCommon(message, error_message, location); if (errInfo) { if (const HRESULT hr = SetRestrictedErrorInfo(errInfo); SUCCEEDED(hr)) { // This gives much better error reporting if the error came from a WinRT module: // the stack trace in the dump, debugger and telemetry is unaffected by our error handling, // giving us better insight into what went wrong. RoFailFastWithErrorContext(err); } } __fastfail(FAST_FAIL_FATAL_APP_EXIT); } std::wstring Error::MessageFromIRestrictedErrorInfo(IRestrictedErrorInfo *info, HRESULT errCode) { if (info) { wil::unique_bstr description, restrictedDescription, capabilitySid; if (SUCCEEDED(info->GetErrorDetails(description.put(), &errCode, restrictedDescription.put(), capabilitySid.put()))) { if (restrictedDescription) { return impl::FormatIRestrictedErrorInfo(errCode, restrictedDescription.get()); } else if (description) { return impl::FormatIRestrictedErrorInfo(errCode, description.get()); } // fall down to the return below, to call MessageFromHRESULT with the error code extracted from the error info. } } return MessageFromHRESULT(errCode); } std::wstring Error::MessageFromHresultError(const winrt::hresult_error &error) { return MessageFromIRestrictedErrorInfo(error.try_as<IRestrictedErrorInfo>().get(), error.code()); }
1,876
C++
.cpp
50
35.02
180
0.777655
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,826
errno.cpp
TranslucentTB_TranslucentTB/ProgramLog/error/errno.cpp
#include "errno.hpp" #include "util/strings.hpp" std::wstring Error::MessageFromErrno(errno_t err) { std::wstring str; // fairly reasonable size so that most error messages fit within it. str.resize_and_overwrite(256, [err](wchar_t* data, std::size_t count) -> std::size_t { if (const errno_t strErr = _wcserror_s(data, count + 1, err); strErr == 0) { return wcslen(data); } else { return 0; } }); if (!str.empty()) { Util::TrimInplace(str); } else { str = L"[failed to get message for errno_t]"; } return std::format(L"{}: {}", err, str); }
580
C++
.cpp
27
19.074074
85
0.657559
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,827
std.cpp
TranslucentTB_TranslucentTB/ProgramLog/error/std.cpp
#include "std.hpp" #include "errno.hpp" #include "win32.hpp" std::wstring Error::MessageFromStdErrorCode(const std::error_code &err) { if (err.category() == std::system_category()) { return MessageFromHRESULT(HRESULT_FROM_WIN32(err.value())); } else if (err.category() == std::generic_category()) { return MessageFromErrno(err.value()); } else { return L"Unknown error"; } }
392
C++
.cpp
18
19.833333
71
0.717742
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,828
win32.cpp
TranslucentTB_TranslucentTB/ProgramLog/error/win32.cpp
#include "win32.hpp" #include <type_traits> #include <WinBase.h> #include <winnt.h> #include "util/strings.hpp" std::wstring Error::impl::FormatHRESULT(HRESULT result, std::wstring_view description) { return std::format( L"0x{:08X}: {}", static_cast<std::make_unsigned_t<HRESULT>>(result), // needs this otherwise we get some error codes in the negatives description ); } wil::unique_hlocal_string Error::impl::FormatMessageForLanguage(HRESULT result, DWORD langId, DWORD &count) { wil::unique_hlocal_string error; count = FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, result, langId, reinterpret_cast<wchar_t*>(error.put()), 0, nullptr ); return error; } std::wstring Error::MessageFromHRESULT(HRESULT result) { DWORD count = 0; auto error = impl::FormatMessageForLanguage(result, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), count); DWORD lastErr = GetLastError(); if (!count && (lastErr == ERROR_MUI_FILE_NOT_FOUND || lastErr == ERROR_RESOURCE_LANG_NOT_FOUND)) { // US language not installed, try again with default language lookup. error = impl::FormatMessageForLanguage(result, 0, count); lastErr = GetLastError(); } std::wstring errBuf; std::wstring_view description; if (count) { description = Util::Trim({ error.get(), count }); } else { errBuf = std::format(L"[failed to get message] 0x{:08X}", static_cast<std::make_unsigned_t<HRESULT>>(HRESULT_FROM_WIN32(lastErr))); description = errBuf; } return impl::FormatHRESULT(result, description); }
1,585
C++
.cpp
51
28.901961
133
0.743287
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,829
common.cpp
TranslucentTB_TranslucentTB/ExplorerHooks/common.cpp
#include "common.hpp" #include <handleapi.h> #include <wil/result.h> void CloseHandleFailFast(HANDLE handle) noexcept { FAIL_FAST_IF_WIN32_BOOL_FALSE(CloseHandle(handle)); }
176
C++
.cpp
7
23.857143
52
0.797619
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,830
swcadetour.cpp
TranslucentTB_TranslucentTB/ExplorerHooks/swcadetour.cpp
#include "swcadetour.hpp" #include <libloaderapi.h> #include <WinUser.h> #include <wil/result.h> #include "constants.hpp" #include "detourtransaction.hpp" #include "util/string_macros.hpp" SWCADetour::unique_module_failfast SWCADetour::s_User32; PFN_SET_WINDOW_COMPOSITION_ATTRIBUTE SWCADetour::SetWindowCompositionAttribute; UINT SWCADetour::s_RequestAttribute; bool SWCADetour::s_DetourInstalled; void SWCADetour::FreeLibraryFailFast(HMODULE hModule) noexcept { FAIL_FAST_IF_WIN32_BOOL_FALSE(FreeLibrary(hModule)); } BOOL WINAPI SWCADetour::FunctionDetour(HWND hWnd, const WINDOWCOMPOSITIONATTRIBDATA *data) noexcept { if (data && data->Attrib == WCA_ACCENT_POLICY) { if (const auto worker = FindWindow(TTB_WORKERWINDOW.c_str(), TTB_WORKERWINDOW.c_str())) { // avoid freezing Explorer if our main process is frozen DWORD_PTR result = 0; if (SendMessageTimeout(worker, s_RequestAttribute, 0, reinterpret_cast<LPARAM>(hWnd), SMTO_ABORTIFHUNG | SMTO_BLOCK | SMTO_ERRORONEXIT, 100, &result) && result) { return true; } } } return SetWindowCompositionAttribute(hWnd, data); } void SWCADetour::Install() noexcept { if (!s_User32) { s_User32.reset(LoadLibraryEx(L"user32.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)); FAIL_FAST_LAST_ERROR_IF_NULL(s_User32); } if (!SetWindowCompositionAttribute) { SetWindowCompositionAttribute = reinterpret_cast<PFN_SET_WINDOW_COMPOSITION_ATTRIBUTE>(GetProcAddress(s_User32.get(), UTIL_STRINGIFY_UTF8(SetWindowCompositionAttribute))); FAIL_FAST_LAST_ERROR_IF(!SetWindowCompositionAttribute); } if (!s_RequestAttribute) { s_RequestAttribute = RegisterWindowMessage(WM_TTBHOOKREQUESTREFRESH.c_str()); FAIL_FAST_LAST_ERROR_IF(!s_RequestAttribute); } if (!s_DetourInstalled) { DetourTransaction transaction; transaction.update_all_threads(); transaction.attach(SetWindowCompositionAttribute, FunctionDetour); transaction.commit(); s_DetourInstalled = true; } } void SWCADetour::Uninstall() noexcept { if (s_DetourInstalled) { DetourTransaction transaction; transaction.update_all_threads(); transaction.detach(SetWindowCompositionAttribute, FunctionDetour); transaction.commit(); s_DetourInstalled = false; } }
2,226
C++
.cpp
68
30.426471
173
0.787512
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,831
api.cpp
TranslucentTB_TranslucentTB/ExplorerHooks/api.cpp
#include "api.hpp" #include <cstdint> #include <WinBase.h> #include <detours/detours.h> #include <processthreadsapi.h> #include <wil/resource.h> #include <wil/win32_helpers.h> #include <WinUser.h> #include "constants.hpp" LRESULT CALLBACK CallWndProc(int nCode, WPARAM wParam, LPARAM lParam) noexcept { // Placeholder return CallNextHookEx(nullptr, nCode, wParam, lParam); } HHOOK InjectExplorerHook(HWND window) noexcept { DWORD pid = 0; const DWORD tid = GetWindowThreadProcessId(window, &pid); wil::unique_process_handle proc(OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pid)); if (!proc) [[unlikely]] { return nullptr; } if (!DetourFindRemotePayload(proc.get(), EXPLORER_PAYLOAD, nullptr)) { proc.reset(OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_WRITE, false, pid)); if (!proc) [[unlikely]] { return nullptr; } static constexpr uint32_t content = 0xDEADBEEF; if (!DetourCopyPayloadToProcess(proc.get(), EXPLORER_PAYLOAD, &content, sizeof(content))) [[unlikely]] { return nullptr; } } return SetWindowsHookEx(WH_CALLWNDPROC, CallWndProc, wil::GetModuleInstanceHandle(), tid); }
1,146
C++
.cpp
38
28.026316
104
0.75931
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,832
taskviewvisibilitymonitor.cpp
TranslucentTB_TranslucentTB/ExplorerHooks/taskviewvisibilitymonitor.cpp
#include "taskviewvisibilitymonitor.hpp" #include <combaseapi.h> #include <processthreadsapi.h> #include <synchapi.h> #include <wil/result.h> #include <wil/win32_helpers.h> #include <WinUser.h> #include "appinfo.hpp" #include "constants.hpp" #include "multitaskingviewvisibilitysink.hpp" #include "undoc/explorer.hpp" std::atomic<bool> TaskViewVisibilityMonitor::s_ThreadRunning = false; unique_handle_failfast TaskViewVisibilityMonitor::s_ThreadCleanupEvent; UINT TaskViewVisibilityMonitor::s_TaskViewVisibilityChangeMessage; UINT TaskViewVisibilityMonitor::s_IsTaskViewOpenedMessage; TaskViewVisibilityMonitor::unique_class_atom_failfast TaskViewVisibilityMonitor::s_WindowClassAtom; unique_handle_failfast TaskViewVisibilityMonitor::s_hThread; wil::com_ptr_failfast<IMultitaskingViewVisibilityService> TaskViewVisibilityMonitor::s_ViewService; void TaskViewVisibilityMonitor::UnregisterClassFailFast(ATOM atom) noexcept { FAIL_FAST_IF_WIN32_BOOL_FALSE(UnregisterClass(reinterpret_cast<LPCWSTR>(atom), wil::GetModuleInstanceHandle())); } void TaskViewVisibilityMonitor::DestroyWindowFailFast(HWND hwnd) noexcept { FAIL_FAST_IF_WIN32_BOOL_FALSE(DestroyWindow(hwnd)); } void TaskViewVisibilityMonitor::UnregisterSink(IMultitaskingViewVisibilityService *source, DWORD cookie) noexcept { FAIL_FAST_IF_FAILED(source->Unregister(cookie)); } void TaskViewVisibilityMonitor::ResetViewService() noexcept { s_ViewService.reset(); } TaskViewVisibilityMonitor::unique_view_service TaskViewVisibilityMonitor::LoadViewService() noexcept { // if we get injected at process creation, it's possible the immersive shell isn't ready yet. // try until it is ready. if after 10 seconds the class is still not registered, it's most likely // an issue other than process init not being done. wil::com_ptr_failfast<IServiceProvider> servProv; uint8_t attempts = 0; HRESULT hr = S_OK; do { hr = CoCreateInstance(CLSID_ImmersiveShell, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(servProv.put())); if (SUCCEEDED(hr)) { break; } else { ++attempts; Sleep(500); } } while (hr == REGDB_E_CLASSNOTREG && attempts < 20); FAIL_FAST_IF_FAILED(hr); // on Windows 11, we frequently get not implemented if this is done too early, so apply the same treatment for the QueryService call. attempts = 0; hr = S_OK; do { hr = servProv->QueryService(SID_MultitaskingViewVisibilityService, s_ViewService.put()); if (SUCCEEDED(hr)) { return unique_view_service(); } else { ++attempts; Sleep(500); } } while (hr == E_NOTIMPL && attempts < 20); FAIL_FAST_HR(hr); } TaskViewVisibilityMonitor::unique_multitasking_view_visibility_token TaskViewVisibilityMonitor::RegisterSink() noexcept { const auto sink = Microsoft::WRL::Make<MultitaskingViewVisibilitySink>(s_TaskViewVisibilityChangeMessage); FAIL_FAST_IF_NULL_ALLOC(sink); DWORD cookie = 0; FAIL_FAST_IF_FAILED(s_ViewService->Register(sink.Get(), &cookie)); return { s_ViewService.get(), cookie }; } void TaskViewVisibilityMonitor::ThreadMain() noexcept { s_ThreadRunning = true; const auto guard = wil::scope_exit([]() noexcept { s_ThreadRunning = false; FAIL_FAST_IF_WIN32_BOOL_FALSE(SetEvent(s_ThreadCleanupEvent.get())); }); const auto coInitialize = wil::CoInitializeEx_failfast(COINIT_APARTMENTTHREADED); const auto viewService = LoadViewService(); const auto token = RegisterSink(); unique_window_failfast window(CreateWindowEx(WS_EX_NOREDIRECTIONBITMAP, reinterpret_cast<LPCWSTR>(s_WindowClassAtom.get()), TTBHOOK_TASKVIEWMONITOR.c_str(), 0, 0, 0, 0, 0, HWND_MESSAGE, nullptr, wil::GetModuleInstanceHandle(), nullptr)); FAIL_FAST_LAST_ERROR_IF_NULL(window); BOOL ret; MSG msg; while ((ret = GetMessage(&msg, nullptr, 0, 0)) != 0) { FAIL_FAST_LAST_ERROR_IF(ret == -1); TranslateMessage(&msg); DispatchMessage(&msg); } } DWORD WINAPI TaskViewVisibilityMonitor::ThreadProc(LPVOID) noexcept { ThreadMain(); // suspend this thread forever. // if we just return, the code in Uninstall might terminate the thread while the CRT is // cleaning up thread-local structures in a lock, resulting in an abandonned lock. // so once the CRT is unloaded, it deadlocks the GUI thread. Sleep(INFINITE); // if the thread somehow gets resumed, something is very wrong. __fastfail(FAST_FAIL_FATAL_APP_EXIT); return static_cast<DWORD>(-1); // make the compiler happy } LRESULT CALLBACK TaskViewVisibilityMonitor::WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) noexcept { if (uMsg == s_IsTaskViewOpenedMessage) { MULTITASKING_VIEW_TYPES flags = MVT_NONE; const HRESULT hr = s_ViewService->IsViewVisible(MVT_ALL_UP_VIEW, &flags); if (SUCCEEDED(hr)) { return flags & MVT_ALL_UP_VIEW; } else { return false; } } else { return DefWindowProc(hwnd, uMsg, wParam, lParam); } } void TaskViewVisibilityMonitor::EndWatcherThread() noexcept { // check if the thread is still alive const DWORD waitResult = WaitForSingleObject(s_hThread.get(), 0); if (waitResult == WAIT_TIMEOUT) { // if the DLL gets unloaded before the thread began // executing, we still need to terminate it. if (s_ThreadRunning) { const DWORD tid = GetThreadId(s_hThread.get()); FAIL_FAST_LAST_ERROR_IF(!tid); FAIL_FAST_IF_WIN32_BOOL_FALSE(PostThreadMessage(tid, WM_QUIT, 0, 0)); const DWORD shutdownWaitResult = WaitForSingleObject(s_ThreadCleanupEvent.get(), INFINITE); FAIL_FAST_LAST_ERROR_IF(shutdownWaitResult != WAIT_OBJECT_0); } // terminate it FAIL_FAST_IF_WIN32_BOOL_FALSE(TerminateThread(s_hThread.get(), 0)); } else { FAIL_FAST_LAST_ERROR_IF(waitResult != WAIT_OBJECT_0); } } void TaskViewVisibilityMonitor::Install() noexcept { if (!s_TaskViewVisibilityChangeMessage) { s_TaskViewVisibilityChangeMessage = RegisterWindowMessage(WM_TTBHOOKTASKVIEWVISIBILITYCHANGE.c_str()); FAIL_FAST_LAST_ERROR_IF(!s_TaskViewVisibilityChangeMessage); } if (!s_IsTaskViewOpenedMessage) { s_IsTaskViewOpenedMessage = RegisterWindowMessage(WM_TTBHOOKISTASKVIEWOPENED.c_str()); FAIL_FAST_LAST_ERROR_IF(!s_IsTaskViewOpenedMessage); } if (!s_WindowClassAtom) { const WNDCLASSEX wndClass = { .cbSize = sizeof(wndClass), .lpfnWndProc = WindowProc, .hInstance = wil::GetModuleInstanceHandle(), .lpszClassName = TTBHOOK_TASKVIEWMONITOR.c_str() }; s_WindowClassAtom.reset(RegisterClassEx(&wndClass)); FAIL_FAST_LAST_ERROR_IF_NULL(s_WindowClassAtom); } if (!s_ThreadCleanupEvent) { s_ThreadCleanupEvent.reset(CreateEvent(nullptr, true, false, nullptr)); FAIL_FAST_LAST_ERROR_IF_NULL(s_WindowClassAtom); } if (!s_hThread) { s_hThread.reset(CreateThread(nullptr, 0, ThreadProc, wil::GetModuleInstanceHandle(), 0, nullptr)); FAIL_FAST_LAST_ERROR_IF_NULL(s_hThread); #ifdef _DEBUG FAIL_FAST_IF_FAILED(SetThreadDescription(s_hThread.get(), APP_NAME L" Task View Visibility Monitor Thread")); #endif } } void TaskViewVisibilityMonitor::Uninstall() noexcept { if (s_hThread) { EndWatcherThread(); s_hThread.reset(); } }
7,029
C++
.cpp
207
31.657005
238
0.772721
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,833
dllmain.cpp
TranslucentTB_TranslucentTB/ExplorerHooks/dllmain.cpp
#include "arch.h" #include <libloaderapi.h> #include <windef.h> #include <processthreadsapi.h> #include <detours/detours.h> #include "constants.hpp" #include "swcadetour.hpp" #include "taskviewvisibilitymonitor.hpp" void *payload = nullptr; BOOL WINAPI DllMain(HINSTANCE, DWORD fdwReason, LPVOID) noexcept { switch (fdwReason) { case DLL_PROCESS_ATTACH: // Are we in Explorer? payload = DetourFindPayloadEx(EXPLORER_PAYLOAD, nullptr); if (payload) { // Install the things SWCADetour::Install(); TaskViewVisibilityMonitor::Install(); } break; case DLL_PROCESS_DETACH: if (payload) { TaskViewVisibilityMonitor::Uninstall(); SWCADetour::Uninstall(); } break; } return true; }
719
C++
.cpp
33
19.393939
64
0.753304
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,834
detourtransaction.cpp
TranslucentTB_TranslucentTB/ExplorerHooks/detourtransaction.cpp
#include "detourtransaction.hpp" #include "arch.h" #include <windef.h> #include <winbase.h> #include <handleapi.h> #include <detours/detours.h> #include <new> #include <processthreadsapi.h> #include <utility> #include <wil/result.h> DetourTransaction::unique_hheap_failfast DetourTransaction::s_Heap; const PSS_ALLOCATOR DetourTransaction::s_PssAllocator = { .AllocRoutine = PssAllocRoutineFailFast, .FreeRoutine = PssFreeRoutineFailFast }; void DetourTransaction::HeapDestroyFailFast(HANDLE hHeap) noexcept { FAIL_FAST_IF_WIN32_BOOL_FALSE(HeapDestroy(hHeap)); } void DetourTransaction::PssFreeSnapshotFailFast(HPSS snapshot) noexcept { FAIL_FAST_IF_WIN32_ERROR(PssFreeSnapshot(GetCurrentProcess(), snapshot)); } void DetourTransaction::PssWalkMarkerFreeFailFast(HPSSWALK marker) noexcept { FAIL_FAST_IF_WIN32_ERROR(PssWalkMarkerFree(marker)); } void* DetourTransaction::PssAllocRoutineFailFast(void*, DWORD size) noexcept { const auto mem = HeapAlloc(s_Heap.get(), 0, size); FAIL_FAST_LAST_ERROR_IF_NULL(mem); return mem; } void DetourTransaction::PssFreeRoutineFailFast(void*, void* address) noexcept { FAIL_FAST_IF_WIN32_BOOL_FALSE(HeapFree(s_Heap.get(), 0, address)); } void DetourTransaction::node_deleter::operator()(node *ptr) const noexcept { ptr->~node(); FAIL_FAST_IF_WIN32_BOOL_FALSE(HeapFree(s_Heap.get(), 0, ptr)); } void DetourTransaction::attach_internal(void **function, void *detour) noexcept { FAIL_FAST_IF_WIN32_ERROR(DetourAttach(function, detour)); } void DetourTransaction::detach_internal(void **function, void *detour) noexcept { FAIL_FAST_IF_WIN32_ERROR(DetourDetach(function, detour)); } void DetourTransaction::update_thread(unique_handle_failfast hThread) noexcept { FAIL_FAST_IF_WIN32_ERROR(DetourUpdateThread(hThread.get())); const auto mem = HeapAlloc(s_Heap.get(), 0, sizeof(node)); FAIL_FAST_LAST_ERROR_IF_NULL(mem); m_Head.reset(new (mem) node { .thread = std::move(hThread), .next = std::move(m_Head) }); } DetourTransaction::DetourTransaction() noexcept { if (!s_Heap) { s_Heap.reset(HeapCreate(HEAP_NO_SERIALIZE, 0, 0)); FAIL_FAST_LAST_ERROR_IF_NULL(s_Heap); } FAIL_FAST_IF_WIN32_ERROR(DetourTransactionBegin()); } void DetourTransaction::update_all_threads() noexcept { unique_hpss_failfast snapshot; FAIL_FAST_IF_WIN32_ERROR(PssCaptureSnapshot(GetCurrentProcess(), PSS_CAPTURE_THREADS, 0, snapshot.put())); unique_hpsswalk_failfast walker; FAIL_FAST_IF_WIN32_ERROR(PssWalkMarkerCreate(&s_PssAllocator, walker.put())); const auto pid = GetCurrentProcessId(); const auto tid = GetCurrentThreadId(); while (true) { PSS_THREAD_ENTRY thread; const DWORD error = PssWalkSnapshot(snapshot.get(), PSS_WALK_THREADS, walker.get(), &thread, sizeof(thread)); if (error == ERROR_SUCCESS) { if (thread.ProcessId == pid && thread.ThreadId != tid && (thread.Flags & PSS_THREAD_FLAGS_TERMINATED) != PSS_THREAD_FLAGS_TERMINATED) { unique_handle_failfast threadHandle(OpenThread(THREAD_QUERY_INFORMATION | THREAD_GET_CONTEXT | THREAD_SET_CONTEXT | THREAD_SUSPEND_RESUME, false, thread.ThreadId)); FAIL_FAST_LAST_ERROR_IF_NULL(threadHandle); update_thread(std::move(threadHandle)); } } else if (error == ERROR_NO_MORE_ITEMS) { break; } else { FAIL_FAST_WIN32(error); } } } void DetourTransaction::commit() noexcept { FAIL_FAST_IF_WIN32_ERROR(DetourTransactionCommit()); m_IsTransacting = false; } DetourTransaction::~DetourTransaction() noexcept { if (m_IsTransacting) { FAIL_FAST_IF_WIN32_ERROR(DetourTransactionAbort()); } }
3,563
C++
.cpp
113
29.495575
168
0.769029
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,835
localization.cpp
TranslucentTB_TranslucentTB/TranslucentTB/localization.cpp
#include "localization.hpp" #include <libloaderapi.h> #include <WinBase.h> #include <WinUser.h> #include "winrt.hpp" #include <winrt/Windows.ApplicationModel.Resources.Core.h> #include "../ProgramLog/error/win32.hpp" #include "../ProgramLog/error/winrt.hpp" bool Localization::SetProcessLangOverride(std::wstring_view langOverride) { // make double null terminated std::wstring language(langOverride); language.push_back(L'\0'); // set for process if (!SetProcessPreferredUILanguages(MUI_LANGUAGE_NAME, language.c_str(), nullptr)) { LastErrorHandle(spdlog::level::err, L"Failed to set process UI language. Is the language set in the configuration file a BCP-47 language name?"); // don't try setting thread & XAML language, it'll probably fail too return false; } // SetProcessPreferredUILanguages does not affect the lookup behavior of resource functions like FindResourceEx, // only SetThreadPreferredUILanguages does. // WHY WINDOWS // WHAT IS THE POINT OF SETPROCESSPREFERREDUILANGUAGES THEN if (!SetThreadPreferredUILanguages(MUI_LANGUAGE_NAME, language.c_str(), nullptr)) { LastErrorHandle(spdlog::level::err, L"Failed to set thread UI language. Is the language set in the configuration file a BCP-47 language name?"); // remove the existing override to not fail in a partially localized to previous value state SetProcessPreferredUILanguages(MUI_LANGUAGE_NAME, nullptr, nullptr); // don't try setting XAML language, it'll probably fail too return false; } // set for WinRT resources try { winrt::Windows::ApplicationModel::Resources::Core::ResourceContext::SetGlobalQualifierValue(L"Language", langOverride); } catch (const winrt::hresult_error& err) { HresultErrorHandle(err, spdlog::level::err, L"Failed to set resource language override. Is the language set in the configuration file a BCP-47 language name?"); // remove the existing overrides to not fail in a partially localized to previous value state SetThreadPreferredUILanguages(MUI_LANGUAGE_NAME, nullptr, nullptr); SetProcessPreferredUILanguages(MUI_LANGUAGE_NAME, nullptr, nullptr); return false; } return true; } Util::null_terminated_wstring_view Localization::LoadLocalizedResourceString(uint16_t resource, HINSTANCE hInst, WORD lang) { const auto fail = [resource, hInst, lang]() -> Util::null_terminated_wstring_view { if (lang != MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US)) { // try again in English return LoadLocalizedResourceString(resource, hInst, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US)); } else { return L"[error occurred while loading localized string]"; } }; const HRSRC src = FindResourceEx(hInst, RT_STRING, MAKEINTRESOURCE((resource >> 4) + 1), lang); if (!src) { LastErrorHandle(spdlog::level::warn, L"Failed to find string resource."); return fail(); } const HGLOBAL res = LoadResource(hInst, src); if (!res) { LastErrorHandle(spdlog::level::warn, L"Failed to load string resource."); return fail(); } auto str = static_cast<const wchar_t *>(LockResource(res)); if (!str) { LastErrorHandle(spdlog::level::warn, L"Failed to lock string resource."); return fail(); } for (int i = 0; i < (resource & 0xF); i++) { str += 1 + static_cast<uint16_t>(*str); } std::wstring_view resStr { str + 1, static_cast<uint16_t>(*str) }; if (!resStr.empty() && resStr.back() == L'\0') { return Util::null_terminated_wstring_view::make_unsafe(resStr.data(), resStr.length() - 1); } else { return fail(); } } std::thread Localization::ShowLocalizedMessageBox(uint16_t resource, UINT type, HINSTANCE hInst, WORD lang) { const auto msg = LoadLocalizedResourceString(resource, hInst, lang); return std::thread([msg, type, lang]() noexcept { MessageBoxEx(Window::NullWindow, msg.c_str(), APP_NAME, type, lang); }); }
3,826
C++
.cpp
101
35.50495
162
0.752563
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,836
loadabledll.cpp
TranslucentTB_TranslucentTB/TranslucentTB/loadabledll.cpp
#include "loadabledll.hpp" #include <format> #include <wil/win32_helpers.h> #include "resources/ids.h" #include "localization.hpp" #include "win32.hpp" #include "windows/window.hpp" #include "../ProgramLog/error/std.hpp" std::filesystem::path LoadableDll::GetDllPath(const std::optional<std::filesystem::path> &storageFolder, std::wstring_view dll) { std::error_code err; const auto [loc, hr] = win32::GetExeLocation(); HresultVerify(hr, spdlog::level::critical, L"Failed to determine executable location!"); std::filesystem::path dllPath = loc.parent_path() / dll; // copy the file over to a place Explorer can read. It can't be injected from WindowsApps. // when running portable, copy it to the temp folder anyways, to allow ejecting the device TTB is running from. std::filesystem::path tempFolder; if (storageFolder) { tempFolder = *storageFolder / L"TempState"; } else { tempFolder = std::filesystem::temp_directory_path(err); if (!err) { tempFolder /= APP_NAME; } else { StdErrorCodeHandle(err, spdlog::level::critical, L"Failed to get temp folder path."); } } std::filesystem::create_directories(tempFolder, err); if (err) [[unlikely]] { StdErrorCodeHandle(err, spdlog::level::critical, L"Failed to create " APP_NAME " temp folder."); } auto tempDllPath = tempFolder / dll; std::filesystem::copy_file(dllPath, tempDllPath, std::filesystem::copy_options::update_existing, err); if (err) [[unlikely]] { if (err.category() == std::system_category() && err.value() == ERROR_SHARING_VIOLATION) { Localization::ShowLocalizedMessageBox(IDS_RESTART_REQUIRED, MB_OK | MB_ICONWARNING | MB_SETFOREGROUND).join(); ExitProcess(1); } else { StdErrorCodeHandle(err, spdlog::level::critical, std::format(L"Failed to copy {}", dll)); } } return tempDllPath; } wil::unique_hmodule LoadableDll::LoadDll(const std::filesystem::path &location) { wil::unique_hmodule hmod(LoadLibraryEx(location.c_str(), nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)); if (!hmod) { LastErrorHandle(spdlog::level::critical, std::format(L"Failed to load {}", location.filename().native())); } return hmod; } LoadableDll::LoadableDll(const std::optional<std::filesystem::path> &storagePath, std::wstring_view dll) : m_hMod(LoadDll(GetDllPath(storagePath, dll))) { }
2,312
C++
.cpp
67
32.208955
127
0.735452
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,837
application.cpp
TranslucentTB_TranslucentTB/TranslucentTB/application.cpp
#include "application.hpp" #include <WinBase.h> #include <WinUser.h> #include "winrt.hpp" #include <winrt/Windows.System.h> #include <winrt/TranslucentTB.Xaml.Pages.h> #include <wil/cppwinrt_helpers.h> #include "../ProgramLog/error/std.hpp" #include "../ProgramLog/error/win32.hpp" #include "uwp/uwp.hpp" void Application::ConfigurationChanged(void *context) { const auto that = static_cast<Application *>(context); that->m_Worker.ConfigurationChanged(); that->m_AppWindow.ConfigurationChanged(); } winrt::TranslucentTB::Xaml::App Application::CreateXamlApp() try { return { }; } HresultErrorCatch(spdlog::level::critical, L"Failed to create Xaml app"); void Application::CreateWelcomePage() { using winrt::TranslucentTB::Xaml::Pages::WelcomePage; CreateXamlWindow<WelcomePage>( xaml_startup_position::center, [this](const WelcomePage &content, BaseXamlPageHost *host) { DispatchToMainThread([this, hwnd = host->handle()] { m_WelcomePage = hwnd; }); auto closeRevoker = content.Closed(winrt::auto_revoke, [this] { DispatchToMainThread([this] { Shutdown(); }); }); content.LiberapayOpenRequested(OpenDonationPage); content.DiscordJoinRequested(OpenDiscordServer); content.ConfigEditRequested([this] { DispatchToMainThread([this] { m_Config.EditConfigFile(); }); }); content.LicenseApproved([this, revoker = std::move(closeRevoker)]() mutable { // remove the close handler because returning from the lambda will make the close event fire. revoker.revoke(); DispatchToMainThread([this] { m_WelcomePage = nullptr; m_Config.SaveConfig(); // create the config file, if not already present m_AppWindow.RemoveHideTrayIconOverride(); m_AppWindow.SendNotification(IDS_WELCOME_NOTIFICATION); }); }); }); } Application::Application(HINSTANCE hInst, std::optional<std::filesystem::path> storageFolder, bool fileExists) : m_Config(storageFolder, fileExists, ConfigurationChanged, this), m_DispatcherController(UWP::CreateDispatcherController()), m_Worker(m_Config.GetConfig(), hInst, m_Loader, storageFolder), m_UwpCRTDep( hInst, L"Microsoft.VCLibs.140.00_8wekyb3d8bbwe", PACKAGE_VERSION { // 14.0.30704.0 but the order is reversed because that's how the struct is. .Revision = 0, .Build = 30704, .Minor = 0, .Major = 14 }, storageFolder.has_value() ), m_WinUIDep( hInst, L"Microsoft.UI.Xaml.2.8_8wekyb3d8bbwe", PACKAGE_VERSION { // 8.2310.30001.0 but the order is reversed because that's how the struct is. .Revision = 0, .Build = 30001, .Minor = 2310, .Major = 8 }, storageFolder.has_value() ), m_XamlApp(CreateXamlApp()), m_XamlManager(UWP::CreateXamlManager()), m_AppWindow(*this, !fileExists, storageFolder.has_value(), hInst, m_Loader), m_Xaml(hInst), m_ShuttingDown(false) { if (const auto spam = m_Loader.SetPreferredAppMode()) { spam(PreferredAppMode::AllowDark); } if (storageFolder) { m_Startup.AcquireTask(); } if (!fileExists) { CreateWelcomePage(); } } void Application::OpenDonationPage() { UWP::OpenUri(wf::Uri(L"https://liberapay.com/TranslucentTB")); } void Application::OpenTipsPage() { UWP::OpenUri(wf::Uri(L"https://TranslucentTB.github.io/tips")); } void Application::OpenDiscordServer() { UWP::OpenUri(wf::Uri(L"https://discord.gg/TranslucentTB")); } int Application::Run() { while (true) { switch (MsgWaitForMultipleObjectsEx(0, nullptr, INFINITE, QS_ALLINPUT, MWMO_ALERTABLE | MWMO_INPUTAVAILABLE)) { case WAIT_OBJECT_0: for (MSG msg; PeekMessage(&msg, 0, 0, 0, PM_REMOVE);) { if (msg.message != WM_QUIT) { if (!m_AppWindow.PreTranslateMessage(msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } else { return static_cast<int>(msg.wParam); } } [[fallthrough]]; case WAIT_IO_COMPLETION: continue; case WAIT_FAILED: LastErrorHandle(spdlog::level::critical, L"Failed to enter alertable wait state!"); default: MessagePrint(spdlog::level::critical, L"MsgWaitForMultipleObjectsEx returned an unexpected value!"); } } } winrt::fire_and_forget Application::Shutdown() { // several calls to Shutdown crash the app because DispatcherController::ShutdownQueueAsync // can only be called once. but it can happen that Shutdown is called several times // e.g. the user uninstalls the app while the welcome page is opened, which causes Shutdown // to close the welcome page, which tries to shutdown the app. if (!m_ShuttingDown) { m_ShuttingDown = true; const bool hasWelcomePage = m_WelcomePage != nullptr; bool canExit = true; for (const auto &thread : m_Xaml.GetThreads()) { const auto guard = thread->Lock(); if (const auto &window = thread->GetCurrentWindow(); window && window->page()) { // Checking if the window can be closed requires to be on the same thread, so // switch to that thread. co_await wil::resume_foreground(thread->GetDispatcher()); if (!window->TryClose()) { canExit = false; // bring attention to the window that couldn't be closed. SetForegroundWindow(window->handle()); } } } if (canExit) { // go back to the main thread for exiting co_await wil::resume_foreground(m_DispatcherController.DispatcherQueue()); co_await m_DispatcherController.ShutdownQueueAsync(); // delete the config file if the user hasn't went through the welcome page // to make them go through it again next startup. if (hasWelcomePage) { m_Config.DeleteConfigFile(); } // exit PostQuitMessage(hasWelcomePage ? 1 : 0); } } } bool Application::BringWelcomeToFront() noexcept { if (m_WelcomePage) { SetForegroundWindow(m_WelcomePage); return true; } else { return false; } }
5,830
C++
.cpp
208
24.836538
112
0.7198
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,838
main.cpp
TranslucentTB_TranslucentTB/TranslucentTB/main.cpp
#include "arch.h" #include <errhandlingapi.h> #include <heapapi.h> #include <processthreadsapi.h> #include <synchapi.h> #include <wil/resource.h> #include "winrt.hpp" #include <winrt/Windows.ApplicationModel.Activation.h> #include "application.hpp" #include "constants.hpp" #include "mainappwindow.hpp" #include "../ProgramLog/error/win32.hpp" #include "../ProgramLog/error/winrt.hpp" #include "../ProgramLog/log.hpp" #include "uwp/uwp.hpp" void HardenProcess() { // Higher logging levels might end up loading more DLLs while we're trying // to enable mitigations for DLL loading. // OK for debug builds because it makes it readable from the log file // but in release we'd rather not. // This entire thing happens before config is loaded, so trace will never log. static constexpr spdlog::level::level_enum level = #ifdef _DEBUG spdlog::level::warn; #else spdlog::level::trace; #endif if (!SetSearchPathMode(BASE_SEARCH_PATH_ENABLE_SAFE_SEARCHMODE | BASE_SEARCH_PATH_PERMANENT)) { LastErrorHandle(level, L"Couldn't enable safe DLL search mode."); } if (!HeapSetInformation(nullptr, HeapEnableTerminationOnCorruption, nullptr, 0)) { LastErrorHandle(level, L"Couldn't enable termination on heap corruption."); } PROCESS_MITIGATION_STRICT_HANDLE_CHECK_POLICY handle_policy{}; handle_policy.RaiseExceptionOnInvalidHandleReference = true; handle_policy.HandleExceptionsPermanentlyEnabled = true; if (!SetProcessMitigationPolicy(ProcessStrictHandleCheckPolicy, &handle_policy, sizeof(handle_policy))) { LastErrorHandle(level, L"Couldn't enable strict handle checks."); } PROCESS_MITIGATION_ASLR_POLICY aslr_policy; if (GetProcessMitigationPolicy(GetCurrentProcess(), ProcessASLRPolicy, &aslr_policy, sizeof(aslr_policy))) { aslr_policy.EnableForceRelocateImages = true; aslr_policy.DisallowStrippedImages = true; if (!SetProcessMitigationPolicy(ProcessASLRPolicy, &aslr_policy, sizeof(aslr_policy))) { LastErrorHandle(level, L"Couldn't enable image force relocation."); } } else { LastErrorHandle(level, L"Couldn't get current ASLR policy."); } PROCESS_MITIGATION_EXTENSION_POINT_DISABLE_POLICY extension_policy{}; extension_policy.DisableExtensionPoints = true; if (!SetProcessMitigationPolicy(ProcessExtensionPointDisablePolicy, &extension_policy, sizeof(extension_policy))) { LastErrorHandle(level, L"Couldn't disable extension point DLLs."); } PROCESS_MITIGATION_BINARY_SIGNATURE_POLICY signature_policy{}; signature_policy.MitigationOptIn = true; if (!SetProcessMitigationPolicy(ProcessSignaturePolicy, &signature_policy, sizeof(signature_policy))) { LastErrorHandle(level, L"Couldn't enable image signature enforcement."); } PROCESS_MITIGATION_IMAGE_LOAD_POLICY load_policy{}; load_policy.PreferSystem32Images = true; if (!SetProcessMitigationPolicy(ProcessImageLoadPolicy, &load_policy, sizeof(load_policy))) { LastErrorHandle(level, L"Couldn't set image load policy."); } BOOL suppressExceptions = false; if (!SetUserObjectInformation(GetCurrentProcess(), UOI_TIMERPROC_EXCEPTION_SUPPRESSION, &suppressExceptions, sizeof(suppressExceptions))) { LastErrorHandle(level, L"Couldn't disable timer exception suppression."); } } _Use_decl_annotations_ int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, wchar_t *, int) { #ifdef _DEBUG SetThreadDescription(GetCurrentThread(), APP_NAME L" Main Thread"); #endif auto storageFolder = UWP::GetAppStorageFolder(); Log::Initialize(storageFolder); HardenProcess(); wil::unique_mutex instanceMutex; bool instanceAlreadyExists = false; try { instanceMutex.create(MUTEX_GUID.c_str(), 0, MAXIMUM_ALLOWED, nullptr, &instanceAlreadyExists); } ResultExceptionCatch(spdlog::level::critical, L"Failed to create or open single-instance mutex."); if (instanceAlreadyExists) { bool suppressNotification = false; if (storageFolder) { const auto eventArgs = wam::AppInstance::GetActivatedEventArgs(); if (eventArgs) { // if an instance got started even earlier, for example by EarlyStart, suppress the notification. suppressNotification = eventArgs.Kind() == wam::Activation::ActivationKind::StartupTask; } } // If there already is another instance running, tell it. if (!suppressNotification) { MainAppWindow::PostNewInstanceNotification(); } return 0; } try { winrt::init_apartment(winrt::apartment_type::single_threaded); } HresultErrorCatch(spdlog::level::critical, L"Initialization of Windows Runtime failed."); // Run the main program loop. When this method exits, TranslucentTB itself is about to exit. const auto ret = Application(hInstance, std::move(storageFolder)).Run(); // why are we brutally terminating you might ask? // Windows.UI.Xaml.dll likes to read null pointers if you exit the app too quickly after // closing a XAML window. While this is not a big deal for the user since we // are about to exit and saved everything, it pollutes telemetry and system crash data. // It's not easily doable to catch SEH exceptions in post-Main DLL unload, so instead just // brutally terminating will work. // Caused specifically by ColorPicker, go figure: https://github.com/microsoft/microsoft-ui-xaml/issues/3541 TerminateProcess(GetCurrentProcess(), ret); // just in case return ret; }
5,294
C++
.cpp
133
37.518797
138
0.784478
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,839
folderwatcher.cpp
TranslucentTB_TranslucentTB/TranslucentTB/folderwatcher.cpp
#include "folderwatcher.hpp" #include <wil/filesystem.h> #include "../ProgramLog/error/win32.hpp" void FolderWatcher::OverlappedCallback(DWORD error, DWORD, OVERLAPPED *overlapped) { // getting parent pointer by casting first child pointer needs standard layout. static_assert(std::is_standard_layout_v<FolderWatcher> && offsetof(FolderWatcher, m_Overlapped) == 0); const auto that = reinterpret_cast<FolderWatcher *>(overlapped); switch (error) { case ERROR_SUCCESS: for (const auto &fileEntry : wil::create_next_entry_offset_iterator(reinterpret_cast<FILE_NOTIFY_INFORMATION *>(that->m_Buffer.get()))) { that->m_Callback(overlapped->hEvent, fileEntry.Action, { fileEntry.FileName, fileEntry.FileNameLength / 2 }); } that->rearm(); break; case ERROR_NOTIFY_ENUM_DIR: that->m_Callback(overlapped->hEvent, 0, { }); that->rearm(); break; case ERROR_OPERATION_ABORTED: break; default: that->m_FolderHandle.reset(); that->m_Buffer.reset(); LastErrorHandle(spdlog::level::warn, L"Error occured while watching directory"); break; } } void FolderWatcher::rearm() { if (!ReadDirectoryChangesW(m_FolderHandle.get(), m_Buffer.get(), m_BufferSize, m_Recursive, m_Filter, nullptr, &m_Overlapped, OverlappedCallback)) { m_FolderHandle.reset(); m_Buffer.reset(); LastErrorHandle(spdlog::level::warn, L"Failed to arm directory watcher"); } } FolderWatcher::FolderWatcher(const std::filesystem::path &path, bool recursive, DWORD filter, callback_t callback, void *context) : m_Overlapped { .hEvent = context // not used for ReadDirectoryChanges so we can stash the user context pointer in it. }, m_Recursive(recursive), m_Filter(filter), m_Callback(callback), m_BufferSize() { m_FolderHandle.reset(CreateFile( path.c_str(), FILE_LIST_DIRECTORY, FILE_SHARE_READ | FILE_SHARE_DELETE | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, nullptr )); if (m_FolderHandle) { SYSTEM_INFO info; GetSystemInfo(&info); m_BufferSize = std::max(info.dwPageSize, info.dwAllocationGranularity); m_Buffer.reset(static_cast<char *>(VirtualAlloc(nullptr, m_BufferSize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE))); if (m_Buffer) { rearm(); } else { m_FolderHandle.reset(); LastErrorHandle(spdlog::level::warn, L"Failed to allocate overlapped IO buffer"); } } else { LastErrorHandle(spdlog::level::warn, L"Failed to open folder handle"); } } FolderWatcher::~FolderWatcher() { if (m_FolderHandle && m_Buffer) { if (!CancelIo(m_FolderHandle.get())) { LastErrorHandle(spdlog::level::warn, L"Failed to cancel asynchronous IO"); } } }
2,661
C++
.cpp
84
29.190476
147
0.74191
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,840
mainappwindow.cpp
TranslucentTB_TranslucentTB/TranslucentTB/mainappwindow.cpp
#include "mainappwindow.hpp" #include <member_thunk/member_thunk.hpp> #include "application.hpp" #include "constants.hpp" #include "localization.hpp" #include "resources/ids.h" #include "../ProgramLog/log.hpp" #include "../ProgramLog/error/win32.hpp" LRESULT MainAppWindow::MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_CLOSE: Exit(); return 1; case WM_QUERYENDSESSION: if (lParam & ENDSESSION_CLOSEAPP) { // The app is being queried if it can close for an update. RegisterApplicationRestart(nullptr, 0); } return 1; case WM_ENDSESSION: if (wParam) { // The app can be killed after processing this message, but we'll try doing it gracefully Exit(); } return 0; default: if (uMsg == m_NewInstanceMessage) { if (!m_App.BringWelcomeToFront()) { SendNotification(IDS_ALREADY_RUNNING); m_App.GetWorker().ResetState(true); } return 0; } else { return TrayContextMenu::MessageHandler(uMsg, wParam, lParam); } } } void MainAppWindow::RefreshMenu() { const auto &trayPage = page(); const auto &settings = m_App.GetConfigManager().GetConfig(); trayPage.SetTaskbarSettings(txmp::TaskbarState::Desktop, settings.DesktopAppearance); trayPage.SetTaskbarSettings(txmp::TaskbarState::VisibleWindow, txmp::OptionalTaskbarAppearance(settings.VisibleWindowAppearance)); trayPage.SetTaskbarSettings(txmp::TaskbarState::MaximisedWindow, txmp::OptionalTaskbarAppearance(settings.MaximisedWindowAppearance)); trayPage.SetTaskbarSettings(txmp::TaskbarState::StartOpened, txmp::OptionalTaskbarAppearance(settings.StartOpenedAppearance)); trayPage.SetTaskbarSettings(txmp::TaskbarState::SearchOpened, txmp::OptionalTaskbarAppearance(settings.SearchOpenedAppearance)); trayPage.SetTaskbarSettings(txmp::TaskbarState::TaskViewOpened, txmp::OptionalTaskbarAppearance(settings.TaskViewOpenedAppearance)); trayPage.SetTaskbarSettings(txmp::TaskbarState::BatterySaver, txmp::OptionalTaskbarAppearance(settings.BatterySaverAppearance)); if (const auto sink = Log::GetSink()) { trayPage.SetLogLevel(static_cast<txmp::LogLevel>(sink->level())); trayPage.SinkState(static_cast<txmp::LogSinkState>(sink->state())); } else { trayPage.SinkState(txmp::LogSinkState::Failed); } trayPage.SetDisableSavingSettings(settings.DisableSaving); trayPage.SetStartupState(m_App.GetStartupManager().GetState()); } void MainAppWindow::RegisterMenuHandlers() { const auto &menu = page(); m_TaskbarSettingsChangedRevoker = menu.TaskbarSettingsChanged(winrt::auto_revoke, { this, &MainAppWindow::TaskbarSettingsChanged }); m_ColorRequestedRevoker = menu.ColorRequested(winrt::auto_revoke, { this, &MainAppWindow::ColorRequested }); m_OpenLogFileRequestedRevoker = menu.OpenLogFileRequested(winrt::auto_revoke, { this, &MainAppWindow::OpenLogFileRequested }); m_LogLevelChangedRevoker = menu.LogLevelChanged(winrt::auto_revoke, { this, &MainAppWindow::LogLevelChanged }); m_DumpDynamicStateRequestedRevoker = menu.DumpDynamicStateRequested(winrt::auto_revoke, { this, &MainAppWindow::DumpDynamicStateRequested }); m_EditSettingsRequestedRevoker = menu.EditSettingsRequested(winrt::auto_revoke, { this, &MainAppWindow::EditSettingsRequested }); m_ResetSettingsRequestedRevoker = menu.ResetSettingsRequested(winrt::auto_revoke, { this, &MainAppWindow::ResetSettingsRequested }); m_ResetDynamicStateRequestedRevoker = menu.ResetDynamicStateRequested(winrt::auto_revoke, { this, &MainAppWindow::ResetDynamicStateRequested }); m_DisableSavingSettingsChangedRevoker = menu.DisableSavingSettingsChanged(winrt::auto_revoke, { this, &MainAppWindow::DisableSavingSettingsChanged }); m_HideTrayRequestedRevoker = menu.HideTrayRequested(winrt::auto_revoke, { this, &MainAppWindow::HideTrayRequested }); m_ResetDynamicStateRequestedRevoker = menu.ResetDynamicStateRequested(winrt::auto_revoke, { this, &MainAppWindow::ResetDynamicStateRequested }); m_CompactThunkHeapRequestedRevoker = menu.CompactThunkHeapRequested(winrt::auto_revoke, MainAppWindow::CompactThunkHeapRequested); m_StartupStateChangedRevoker = menu.StartupStateChanged(winrt::auto_revoke, { this, &MainAppWindow::StartupStateChanged }); m_TipsAndTricksRequestedRevoker = menu.TipsAndTricksRequested(winrt::auto_revoke, MainAppWindow::TipsAndTricksRequested); m_AboutRequestedRevoker = menu.AboutRequested(winrt::auto_revoke, { this, &MainAppWindow::AboutRequested }); m_ExitRequestedRevoker = menu.ExitRequested(winrt::auto_revoke, { this, &MainAppWindow::Exit }); } void MainAppWindow::TaskbarSettingsChanged(const txmp::TaskbarState &state, const txmp::TaskbarAppearance &appearance) { auto &config = GetConfigForState(state); // restore color because the context menu doesn't transmit that info appearance.Color(config.Color); if (const auto optAppearance = appearance.try_as<txmp::OptionalTaskbarAppearance>()) { if (state == txmp::TaskbarState::Desktop) [[unlikely]] { throw std::invalid_argument("Desktop appearance is not optional"); } static_cast<OptionalTaskbarAppearance &>(config) = optAppearance; } else { config = appearance; } m_App.GetWorker().ConfigurationChanged(); } void MainAppWindow::ColorRequested(const txmp::TaskbarState &state) { std::unique_lock lock(m_PickerMutex); auto &pickerHost = m_ColorPickers.at(static_cast<std::size_t>(state)); if (!pickerHost) { auto &appearance = GetConfigForState(state); using winrt::TranslucentTB::Xaml::Pages::ColorPickerPage; m_App.CreateXamlWindow<ColorPickerPage>(xaml_startup_position::mouse, [this, &appearance, &pickerHost, state, inner_lock = std::move(lock)](const ColorPickerPage &picker, BaseXamlPageHost *host) mutable { pickerHost = host; inner_lock.unlock(); auto closeRevoker = picker.Closed(winrt::auto_revoke, [this, state, &pickerHost] { m_App.DispatchToMainThread([this, state, &pickerHost]() mutable { m_App.GetWorker().RemoveColorPreview(state); std::scoped_lock guard(m_PickerMutex); pickerHost = nullptr; }); }); picker.ChangesCommitted([this, state, &appearance, &pickerHost, revoker = std::move(closeRevoker)](const winrt::Windows::UI::Color &color) mutable { revoker.revoke(); // we're already doing this. m_App.DispatchToMainThread([this, state, color, &appearance, &pickerHost]() mutable { appearance.Color = color; m_App.GetWorker().RemoveColorPreview(state); // remove color preview implicitly refreshes config std::scoped_lock guard(m_PickerMutex); pickerHost = nullptr; }); }); picker.ColorChanged([this, state](const winrt::Windows::UI::Color &color) { m_App.DispatchToMainThread([this, state, color] { m_App.GetWorker().ApplyColorPreview(state, color); }); }); }, state, appearance.Color); } else { SetForegroundWindow(pickerHost->handle()); } } void MainAppWindow::OpenLogFileRequested() { if (const auto sink = Log::GetSink()) { HresultVerify(win32::EditFile(sink->file()), spdlog::level::err, L"Failed to open log file."); } } void MainAppWindow::LogLevelChanged(const txmp::LogLevel &level) { const auto spdlogLevel = static_cast<spdlog::level::level_enum>(level); auto &configManager = m_App.GetConfigManager(); configManager.GetConfig().LogVerbosity = spdlogLevel; configManager.UpdateVerbosity(); } void MainAppWindow::DumpDynamicStateRequested() { m_App.GetWorker().DumpState(); } void MainAppWindow::EditSettingsRequested() { m_App.GetConfigManager().EditConfigFile(); } void MainAppWindow::ResetSettingsRequested() { auto &manager = m_App.GetConfigManager(); manager.GetConfig() = { }; manager.UpdateVerbosity(); m_App.GetWorker().ConfigurationChanged(); ConfigurationChanged(); } void MainAppWindow::DisableSavingSettingsChanged(bool disabled) noexcept { m_App.GetConfigManager().GetConfig().DisableSaving = disabled; } void MainAppWindow::HideTrayRequested() { Localization::ShowLocalizedMessageBoxWithCallback(IDS_HIDE_TRAY, MB_OK | MB_ICONINFORMATION | MB_SETFOREGROUND, hinstance(), [this](int) { m_App.DispatchToMainThread([this] { m_HideIconOverride = true; Hide(); }); }).detach(); } void MainAppWindow::ResetDynamicStateRequested() { m_App.GetWorker().ResetState(true); } void MainAppWindow::CompactThunkHeapRequested() { member_thunk::compact(); } winrt::fire_and_forget MainAppWindow::StartupStateChanged() { auto &manager = m_App.GetStartupManager(); if (const auto state = manager.GetState()) { switch (*state) { using enum winrt::Windows::ApplicationModel::StartupTaskState; case Disabled: co_await manager.Enable(); break; case Enabled: manager.Disable(); break; case DisabledByUser: StartupManager::OpenSettingsPage(); break; default: MessagePrint(spdlog::level::err, L"Cannot change startup state because it is locked by external factors (for example Group Policy)."); break; } } } void MainAppWindow::TipsAndTricksRequested() { Application::OpenTipsPage(); } void MainAppWindow::AboutRequested() { //m_App.CreateXamlWindow<winrt::TranslucentTB::Xaml::Pages::AboutPage>(xaml_startup_position::center, [](const auto &) { }); } void MainAppWindow::Exit() { m_App.GetConfigManager().SaveConfig(); m_App.Shutdown(); } TaskbarAppearance &MainAppWindow::GetConfigForState(const txmp::TaskbarState &state) { auto &config = m_App.GetConfigManager().GetConfig(); switch (state) { using enum txmp::TaskbarState; case Desktop: return config.DesktopAppearance; case VisibleWindow: return config.VisibleWindowAppearance; case MaximisedWindow: return config.MaximisedWindowAppearance; case StartOpened: return config.StartOpenedAppearance; case SearchOpened: return config.SearchOpenedAppearance; case TaskViewOpened: return config.TaskViewOpenedAppearance; case BatterySaver: return config.BatterySaverAppearance; default: throw std::invalid_argument("Unknown taskbar state"); } } void MainAppWindow::UpdateTrayVisibility(bool visible) { if (!m_HideIconOverride && visible) { Show(); } else { Hide(); } } MainAppWindow::MainAppWindow(Application &app, bool hideIconOverride, bool hasPackageIdentity, HINSTANCE hInstance, DynamicLoader &loader) : // make the window topmost so that the context menu shows correctly MessageWindow(TRAY_WINDOW, APP_NAME, hInstance, WS_POPUP, WS_EX_TOPMOST | WS_EX_NOREDIRECTIONBITMAP), TrayContextMenu(TRAY_GUID, MAKEINTRESOURCE(IDI_TRAYWHITEICON), MAKEINTRESOURCE(IDI_TRAYBLACKICON), loader, hasPackageIdentity), m_App(app), m_HideIconOverride(hideIconOverride), m_NewInstanceMessage(Window::RegisterMessage(WM_TTBNEWINSTANCESTARTED)) { RegisterMenuHandlers(); ConfigurationChanged(); } void MainAppWindow::ConfigurationChanged() { const Config &config = m_App.GetConfigManager().GetConfig(); UpdateTrayVisibility(!config.HideTray); SetXamlContextMenuOverride(config.UseXamlContextMenu); } void MainAppWindow::RemoveHideTrayIconOverride() { m_HideIconOverride = false; UpdateTrayVisibility(!m_App.GetConfigManager().GetConfig().HideTray); } void MainAppWindow::PostNewInstanceNotification() { if (const auto msg = Window::RegisterMessage(WM_TTBNEWINSTANCESTARTED)) { if (const auto runningInstance = Window::Find(TRAY_WINDOW, APP_NAME)) { AllowSetForegroundWindow(runningInstance.process_id()); runningInstance.post_message(*msg); } } }
11,408
C++
.cpp
305
34.760656
151
0.780755
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,841
trayicon.cpp
TranslucentTB_TranslucentTB/TranslucentTB/tray/trayicon.cpp
#include "trayicon.hpp" #include <cguid.h> #include <shellapi.h> #include "appinfo.hpp" #include "constants.hpp" #include "../localization.hpp" #include "../../ProgramLog/error/errno.hpp" #include "../../ProgramLog/error/std.hpp" #include "../../ProgramLog/error/win32.hpp" #include "util/color.hpp" const wchar_t *TrayIcon::GetThemedIcon() const { HIGHCONTRAST info = { .cbSize = sizeof(info) }; if (SystemParametersInfo(SPI_GETHIGHCONTRAST, 0, &info, 0)) { if (info.dwFlags & HCF_HIGHCONTRASTON) { return Util::Color::FromABGR(GetSysColor(COLOR_WINDOWTEXT)).IsDarkColor() ? m_darkIconResource : m_whiteIconResource; } } else { LastErrorHandle(spdlog::level::info, L"Failed to check if high contrast mode is enabled"); } return m_Ssudm && !m_Ssudm() ? m_darkIconResource : m_whiteIconResource; } void TrayIcon::LoadThemedIcon() { if (const HRESULT hr = LoadIconMetric(hinstance(), GetThemedIcon(), LIM_SMALL, m_Icon.put()); SUCCEEDED(hr)) { m_IconData.uFlags |= NIF_ICON; m_IconData.hIcon = m_Icon.get(); } else { m_IconData.uFlags &= ~NIF_ICON; m_Icon.reset(); HresultHandle(hr, spdlog::level::warn, L"Failed to load tray icon."); } } bool TrayIcon::Notify(DWORD message, NOTIFYICONDATA *data) { if (Shell_NotifyIcon(message, data ? data : &m_IconData)) { return true; } else { MessagePrint(spdlog::level::info, L"Failed to notify shell."); return false; } } LRESULT TrayIcon::MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_DPICHANGED: case WM_SETTINGCHANGE: case WM_THEMECHANGED: case WM_DISPLAYCHANGE: LoadThemedIcon(); if (m_CurrentlyShowing) { Notify(NIM_MODIFY); } break; default: if (uMsg == m_TaskbarCreatedMessage) { LoadThemedIcon(); // https://github.com/TranslucentTB/TranslucentTB/issues/417 // we also get this message when DPI changes. Check if explorer truly // restarted by seeing if a normal NIM_MODIFY worked m_CurrentlyShowing = Shell_NotifyIcon(NIM_MODIFY, &m_IconData); if (m_ShowPreference) { Show(); } return 0; } } return MessageWindow::MessageHandler(uMsg, wParam, lParam); } std::optional<RECT> TrayIcon::GetTrayRect() { NOTIFYICONIDENTIFIER id = { sizeof(id) }; #ifdef SIGNED_BUILD id.guidItem = m_IconData.guidItem; #else id.hWnd = m_IconData.hWnd; id.uID = m_IconData.uID; id.guidItem = GUID_NULL; #endif RECT rect{}; const HRESULT hr = Shell_NotifyIconGetRect(&id, &rect); if (SUCCEEDED(hr)) { return rect; } else { HresultHandle(hr, spdlog::level::warn, L"Failed to get tray rect"); return std::nullopt; } } TrayIcon::TrayIcon(const GUID &iconId, const wchar_t *whiteIconResource, const wchar_t *darkIconResource, PFN_SHOULD_SYSTEM_USE_DARK_MODE ssudm) : m_IconData { .cbSize = sizeof(m_IconData), .hWnd = m_WindowHandle, .uFlags = NIF_MESSAGE | NIF_TIP, .uCallbackMessage = TRAY_CALLBACK, .szTip = APP_NAME, .uVersion = NOTIFYICON_VERSION_4 }, m_whiteIconResource(whiteIconResource), m_darkIconResource(darkIconResource), m_ShowPreference(false), m_CurrentlyShowing(false), m_TaskbarCreatedMessage(Window::RegisterMessage(WM_TASKBARCREATED)), m_Ssudm(ssudm) { #ifdef SIGNED_BUILD m_IconData.uFlags |= NIF_GUID; m_IconData.guidItem = iconId; #else // good enough method to get an unique id m_IconData.uID = iconId.Data1; #endif LoadThemedIcon(); #ifdef SIGNED_BUILD // Clear icon from a previous instance that didn't cleanly exit. // Errors if instance cleanly exited, so avoid logging it. // Only works when using GUIDs. Shell_NotifyIcon(NIM_DELETE, &m_IconData); #endif } void TrayIcon::Show() { m_ShowPreference = true; if (!m_CurrentlyShowing && Notify(NIM_ADD)) { Notify(NIM_SETVERSION); m_CurrentlyShowing = true; } } void TrayIcon::Hide() { m_ShowPreference = false; if (m_CurrentlyShowing && Notify(NIM_DELETE)) { m_CurrentlyShowing = false; } } void TrayIcon::SendNotification(uint16_t textResource, DWORD infoFlags) { if (m_CurrentlyShowing) { // copy the data because if explorer restarts or the theme/settings change we don't want to re-send the notification auto data = m_IconData; data.uFlags |= NIF_INFO; data.dwInfoFlags = infoFlags; // don't set szInfoTitle, the OS will show the app name already. Localization::LoadLocalizedResourceString(textResource, hinstance()).copy(data.szInfo, std::size(data.szInfo)); Notify(NIM_MODIFY, &data); } } TrayIcon::~TrayIcon() noexcept(false) { Hide(); }
4,490
C++
.cpp
172
23.860465
118
0.737602
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,842
basecontextmenu.cpp
TranslucentTB_TranslucentTB/TranslucentTB/tray/basecontextmenu.cpp
#include "basecontextmenu.hpp" #include <windows.ui.xaml.hosting.desktopwindowxamlsource.h> #include <winrt/Microsoft.UI.Xaml.Controls.h> #include <winrt/Windows.Foundation.h> #include <winrt/Windows.UI.Xaml.Automation.Peers.h> #include <winrt/Windows.UI.Xaml.Automation.Provider.h> #include "win32.hpp" #include "../ProgramLog/error/win32.hpp" UINT BaseContextMenu::GetNextClickableId() noexcept { // skip over 0 because TrackPopupMenu returning 0 means the menu was dismissed // or an error occured. We don't want to trigger an entry when the menu is dismissed, // and we can't distinguish menu dismisses from proper clicks. if (m_ContextMenuClickableId == 0) { m_ContextMenuClickableId = 1; } return m_ContextMenuClickableId++; } wil::unique_hmenu BaseContextMenu::BuildContextMenuInner(const wfc::IVector<wuxc::MenuFlyoutItemBase> &items) { wil::unique_hmenu menu(CreatePopupMenu()); if (menu) { UINT position = 0; for (const wuxc::MenuFlyoutItemBase item : items) { if (item.Visibility() != wux::Visibility::Visible) { continue; } wil::unique_hmenu subMenu; winrt::hstring menuText; MENUITEMINFO itemInfo = { .cbSize = sizeof(itemInfo) }; if (const auto menuItem = item.try_as<wuxc::MenuFlyoutItem>()) { // keep a reference alive for dwItemData m_Items.insert(menuItem); menuText = menuItem.Text(); itemInfo.fMask = MIIM_DATA | MIIM_ID | MIIM_STATE | MIIM_STRING; itemInfo.fState = menuItem.IsEnabled() ? MFS_ENABLED : MFS_DISABLED; itemInfo.wID = GetNextClickableId(); itemInfo.dwTypeData = const_cast<wchar_t *>(menuText.c_str()); itemInfo.dwItemData = reinterpret_cast<ULONG_PTR>(winrt::get_abi(menuItem)); if (const auto radioItem = menuItem.try_as<muxc::RadioMenuFlyoutItem>()) { itemInfo.fState |= radioItem.IsChecked() ? MFS_CHECKED : MFS_UNCHECKED; itemInfo.fMask |= MIIM_FTYPE; itemInfo.fType = MFT_RADIOCHECK; } else if (const auto toggleItem = menuItem.try_as<wuxc::ToggleMenuFlyoutItem>()) { itemInfo.fState |= toggleItem.IsChecked() ? MFS_CHECKED : MFS_UNCHECKED; } } else if (const auto subItem = item.try_as<wuxc::MenuFlyoutSubItem>()) { subMenu = BuildContextMenuInner(subItem.Items()); menuText = subItem.Text(); itemInfo.fMask = MIIM_STATE | MIIM_STRING | MIIM_SUBMENU; itemInfo.fState = subItem.IsEnabled() ? MFS_ENABLED : MFS_DISABLED; itemInfo.hSubMenu = subMenu.get(); itemInfo.dwTypeData = const_cast<wchar_t *>(menuText.c_str()); } else if (const auto separator = item.try_as<wuxc::MenuFlyoutSeparator>()) { itemInfo.fMask = MIIM_FTYPE; itemInfo.fType = MFT_SEPARATOR; } else { MessagePrint(spdlog::level::warn, L"Unknown flyout item type"); continue; } if (InsertMenuItem(menu.get(), position, true, &itemInfo)) { subMenu.release(); // ownership transferred to system ++position; } else { LastErrorHandle(spdlog::level::warn, L"Failed to insert menu item"); } } } else { LastErrorHandle(spdlog::level::warn, L"Failed to create popup menu"); } return menu; } HMENU BaseContextMenu::BuildClassicContextMenu(const wuxc::MenuFlyout &flyout) { m_ContextMenu = BuildContextMenuInner(flyout.Items()); return m_ContextMenu.get(); } void BaseContextMenu::TriggerClassicContextMenuItem(UINT item) { MENUITEMINFO itemInfo = { .cbSize = sizeof(itemInfo), .fMask = MIIM_DATA }; if (GetMenuItemInfo(m_ContextMenu.get(), item, false, &itemInfo)) { wuxc::MenuFlyoutItem menuItem(nullptr); winrt::copy_from_abi(menuItem, reinterpret_cast<void *>(itemInfo.dwItemData)); if (menuItem) { // muxc::RadioMenuFlyoutItem secretely inherits from wuxc::ToggleMenuFlyoutItem, // so try_as succeeds and the automation peer works still. if (const auto toggleItem = menuItem.try_as<wuxc::ToggleMenuFlyoutItem>()) { wux::Automation::Peers::ToggleMenuFlyoutItemAutomationPeer(toggleItem).Toggle(); } else { wux::Automation::Peers::MenuFlyoutItemAutomationPeer(menuItem).Invoke(); } } } else { LastErrorHandle(spdlog::level::warn, L"Failed to get menu item info"); } } void BaseContextMenu::CleanupClassicContextMenu() { m_ContextMenu.reset(); m_Items.clear(); } bool BaseContextMenu::ShouldUseXamlMenu() { if (!m_UseXamlMenu) { static const bool xamlMenuWorks = [] { if (win32::IsAtLeastBuild(19045)) { // Windows 10 22H2 and up (including Windows 11) - always works return true; } else if (win32::IsAtLeastBuild(19041)) { // Windows 10 21H2, 21H1, 20H2, 2004 - requires KB5007253 (which is revision number 1387 on all of those) if (const auto [version, hr] = win32::GetWindowsBuild(); SUCCEEDED(hr)) { return version.Revision >= 1387; } else { return false; } } else { // older than 2004 - always broken return false; } }(); return xamlMenuWorks; } else { return *m_UseXamlMenu; } } void BaseContextMenu::ShowClassicContextMenu(const wuxc::MenuFlyout &flyout, POINT pt) { const auto guard = wil::scope_exit([this] { CleanupClassicContextMenu(); }); if (const auto menu = BuildClassicContextMenu(flyout)) { SetLastError(NO_ERROR); const unsigned int item = TrackPopupMenu(menu, TPM_RETURNCMD | TPM_LEFTALIGN, pt.x, pt.y, 0, m_WindowHandle, nullptr); if (item) { TriggerClassicContextMenuItem(item); } else if (const DWORD lastErr = GetLastError(); lastErr != NO_ERROR) // can return 0 if the menu is dismissed { HresultHandle(HRESULT_FROM_WIN32(lastErr), spdlog::level::warn, L"Failed to open context menu."); } } } void BaseContextMenu::MoveHiddenWindow(RECT &rect) { HMONITOR mon = MonitorFromRect(&rect, MONITOR_DEFAULTTONULL); MONITORINFO info = { sizeof(info) }; if (mon && GetMonitorInfo(mon, &info)) { // if it's in the taskbar (completely outside work area), oversize the window // to allow the MenuFlyout to put itself in the work area if (!win32::RectFitsInRect(info.rcWork, rect)) { ExtendIntoArea(rect, info.rcWork); } const int width = rect.right - rect.left; const int height = rect.bottom - rect.top; if (!SetWindowPos(m_WindowHandle, nullptr, rect.left, rect.top, width, height, SWP_NOZORDER | SWP_NOACTIVATE)) { LastErrorHandle(spdlog::level::warn, L"Failed to move window"); } if (!SetWindowPos(m_InteropWnd, nullptr, 0, 0, width, height, SWP_NOZORDER | SWP_NOACTIVATE)) { LastErrorHandle(spdlog::level::warn, L"Failed to resize interop window"); } } } BaseContextMenu::BaseContextMenu() { const auto nativeSource = m_Source.as<IDesktopWindowXamlSourceNative2>(); HresultVerify(nativeSource->AttachToWindow(m_WindowHandle), spdlog::level::critical, L"Failed to attach DesktopWindowXamlSource"); HresultVerify(nativeSource->get_WindowHandle(m_InteropWnd.put()), spdlog::level::critical, L"Failed to get interop window handle"); // This *needs* to use SetWindowPos, don't ask me why if (!SetWindowPos(m_InteropWnd, nullptr, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE)) { LastErrorHandle(spdlog::level::critical, L"Failed to show interop window"); } } BaseContextMenu::~BaseContextMenu() { m_Source.Close(); m_Source = nullptr; } void BaseContextMenu::SetXamlContextMenuOverride(const std::optional<bool> &menuOverride) { m_UseXamlMenu = menuOverride; } bool BaseContextMenu::PreTranslateMessage(const MSG &msg) { if (const auto nativeSource = m_Source.try_as<IDesktopWindowXamlSourceNative2>()) { BOOL result; const HRESULT hr = nativeSource->PreTranslateMessage(&msg, &result); if (SUCCEEDED(hr)) { return result; } else { HresultHandle(hr, spdlog::level::warn, L"Failed to pre-translate message"); } } return false; }
7,808
C++
.cpp
249
28.220884
132
0.725764
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,843
xamlthreadpool.cpp
TranslucentTB_TranslucentTB/TranslucentTB/uwp/xamlthreadpool.cpp
#include "xamlthreadpool.hpp" #include <wil/safecast.h> XamlThread &XamlThreadPool::GetAvailableThread(std::unique_lock<Util::thread_independent_mutex> &lock) { for (auto it = m_Threads.begin(); it != m_Threads.end(); ++it) { XamlThread &thread = **it; lock = thread.Lock(); if (thread.IsAvailable()) { return thread; } else { lock.unlock(); } } auto &thread = m_Threads.emplace_back(std::make_unique<XamlThread>()); lock = thread->Lock(); return *thread; } XamlThreadPool::~XamlThreadPool() { if (const auto size = m_Threads.size(); size != 0) { std::vector<wil::unique_handle> threads; threads.reserve(size); for (auto &xamlThread : m_Threads) { threads.push_back(xamlThread->Delete()); static_cast<void>(xamlThread.release()); } if (WaitForMultipleObjects(wil::safe_cast<DWORD>(size), threads.data()->addressof(), true, INFINITE) == WAIT_FAILED) { LastErrorHandle(spdlog::level::warn, L"Failed to wait for thread termination"); } } }
998
C++
.cpp
38
23.657895
118
0.696335
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,844
xamlthread.cpp
TranslucentTB_TranslucentTB/TranslucentTB/uwp/xamlthread.cpp
#include "xamlthread.hpp" #include <wil/resource.h> #include "../windows/window.hpp" #include "uwp.hpp" #include "../../ProgramLog/error/win32.hpp" DWORD WINAPI XamlThread::ThreadProc(LPVOID param) { const auto that = static_cast<XamlThread *>(param); that->ThreadInit(); that->m_Ready.SetEvent(); BOOL ret; MSG msg; while ((ret = GetMessage(&msg, Window::NullWindow, 0, 0)) != 0) { if (ret != -1) { if (!that->PreTranslateMessage(msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } else { LastErrorHandle(spdlog::level::critical, L"Failed to get message"); } } delete that; winrt::uninit_apartment(); return static_cast<DWORD>(msg.wParam); } void XamlThread::DeletedCallback(void *data) { const auto that = static_cast<XamlThread *>(data); { std::scoped_lock guard(that->m_CurrentWindowLock); that->m_CurrentWindow.reset(); } that->m_Source = nullptr; } void XamlThread::ThreadInit() { try { winrt::init_apartment(winrt::apartment_type::single_threaded); } HresultErrorCatch(spdlog::level::critical, L"Failed to initialize thread apartment"); m_Dispatcher = UWP::CreateDispatcherController(); m_Manager = UWP::CreateXamlManager(); } bool XamlThread::PreTranslateMessage(const MSG &msg) { // prevent XAML islands from capturing ALT-{F4,SPACE} because of // https://github.com/microsoft/microsoft-ui-xaml/issues/2408 if (msg.message == WM_SYSKEYDOWN && (msg.wParam == VK_F4 || msg.wParam == VK_SPACE)) [[unlikely]] { Window(msg.hwnd).ancestor(GA_ROOT).send_message(msg.message, msg.wParam, msg.lParam); return true; } if (m_Source) { BOOL result; const HRESULT hr = m_Source->PreTranslateMessage(&msg, &result); if (SUCCEEDED(hr)) { if (result) { return result; } } else { HresultHandle(hr, spdlog::level::warn, L"Failed to pre-translate message"); } } return false; } winrt::fire_and_forget XamlThread::ThreadDeinit() { co_await wil::resume_foreground(GetDispatcher(), winrt::Windows::System::DispatcherQueuePriority::Low); // only called during destruction of thread pool, so no locking needed. m_CurrentWindow.reset(); m_Source = nullptr; m_Manager.Close(); m_Manager = nullptr; co_await m_Dispatcher.ShutdownQueueAsync(); PostQuitMessage(0); } XamlThread::XamlThread() : m_Dispatcher(nullptr), m_Manager(nullptr) { m_Thread.reset(CreateThread(nullptr, 0, XamlThread::ThreadProc, this, 0, nullptr)); if (!m_Thread) { LastErrorHandle(spdlog::level::critical, L"Failed to create XAML thread"); } #ifdef _DEBUG HresultVerify(SetThreadDescription(m_Thread.get(), APP_NAME L" XAML Island Thread"), spdlog::level::info, L"Failed to set thread description"); #endif m_Ready.wait(); } wil::unique_handle XamlThread::Delete() { ThreadDeinit(); return std::move(m_Thread); }
2,818
C++
.cpp
107
23.990654
144
0.727239
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,845
xamldragregion.cpp
TranslucentTB_TranslucentTB/TranslucentTB/uwp/xamldragregion.cpp
#include "xamldragregion.hpp" #include <windowsx.h> #include <wil/resource.h> #include "../ProgramLog/error/win32.hpp" void XamlDragRegion::HandleClick(UINT msg, LPARAM lParam) noexcept { POINT pt = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) }; if (ClientToScreen(m_WindowHandle, &pt)) { ancestor(GA_PARENT).send_message(msg, HTCAPTION, MAKELPARAM(pt.x, pt.y)); } } LRESULT XamlDragRegion::MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_LBUTTONDOWN: HandleClick(WM_NCLBUTTONDOWN, lParam); return 0; case WM_LBUTTONDBLCLK: HandleClick(WM_NCLBUTTONDBLCLK, lParam); return 0; case WM_LBUTTONUP: HandleClick(WM_NCLBUTTONUP, lParam); return 0; case WM_RBUTTONDOWN: HandleClick(WM_NCRBUTTONDOWN, lParam); return 0; case WM_RBUTTONDBLCLK: HandleClick(WM_NCRBUTTONDBLCLK, lParam); return 0; case WM_RBUTTONUP: HandleClick(WM_NCRBUTTONUP, lParam); return 0; case WM_MOUSEMOVE: if (!m_Tracking) { TRACKMOUSEEVENT tme = { .cbSize = sizeof(tme), .dwFlags = TME_HOVER | TME_LEAVE, .hwndTrack = m_WindowHandle, .dwHoverTime = HOVER_DEFAULT }; if (TrackMouseEvent(&tme)) { m_Tracking = true; } else { LastErrorHandle(spdlog::level::info, L"Failed to track mouse events"); } } return 0; case WM_MOUSEHOVER: ancestor(GA_PARENT).send_message(uMsg, wParam, lParam); return 0; case WM_MOUSELEAVE: ancestor(GA_PARENT).send_message(uMsg, wParam, lParam); m_Tracking = false; return 0; default: return MessageWindow::MessageHandler(uMsg, wParam, lParam); } } void XamlDragRegion::SetRegion(int width, int height, wf::Rect buttonsRegion) { if (buttonsRegion != m_ButtonsRegion) { if (buttonsRegion == wf::Rect { 0, 0, 0, 0 }) { if (!SetWindowRgn(m_WindowHandle, nullptr, false)) [[unlikely]] { MessagePrint(spdlog::level::warn, L"Failed to clear window region"); return; } } else { wil::unique_hrgn windowRgn(CreateRectRgn(0, 0, width, height)); if (!windowRgn) [[unlikely]] { MessagePrint(spdlog::level::warn, L"Failed to create window region"); return; } wil::unique_hrgn buttonsRgn(CreateRectRgn( static_cast<int>(buttonsRegion.X), static_cast<int>(buttonsRegion.Y), static_cast<int>(buttonsRegion.X + buttonsRegion.Width), static_cast<int>(buttonsRegion.Y + buttonsRegion.Height) )); if (!buttonsRgn) [[unlikely]] { MessagePrint(spdlog::level::warn, L"Failed to create buttons region"); return; } CombineRgn(windowRgn.get(), windowRgn.get(), buttonsRgn.get(), RGN_DIFF); if (SetWindowRgn(m_WindowHandle, windowRgn.get(), false)) { windowRgn.release(); // the system owns the region now } else { MessagePrint(spdlog::level::warn, L"Failed to set window region"); return; } } m_ButtonsRegion = buttonsRegion; } } XamlDragRegion::XamlDragRegion(WindowClass &classRef, Window parent) : MessageWindow(classRef, { }, WS_CHILD, WS_EX_LAYERED | WS_EX_NOREDIRECTIONBITMAP, parent) { } void XamlDragRegion::Position(const RECT &parentRect, wf::Rect position, wf::Rect buttonsRegion, UINT flags) { const auto newX = static_cast<int>(position.X); const auto newY = static_cast<int>(position.Y); const auto newHeight = static_cast<int>(position.Height); const auto newWidth = static_cast<int>(position.Width); if (const auto dragRegionRect = rect()) { const auto x = dragRegionRect->left - parentRect.left; const auto y = dragRegionRect->top - parentRect.top; const auto width = dragRegionRect->right - dragRegionRect->left; const auto height = dragRegionRect->bottom - dragRegionRect->top; if (x != newX || y != newY || height != newHeight || width != newWidth) [[unlikely]] { if (!SetWindowPos(m_WindowHandle, HWND_TOP, newX, newY, newWidth, newHeight, flags | SWP_NOACTIVATE)) [[unlikely]] { LastErrorHandle(spdlog::level::warn, L"Failed to set drag region window position"); } if (!SetLayeredWindowAttributes(m_WindowHandle, 0, 255, LWA_ALPHA)) [[unlikely]] { LastErrorHandle(spdlog::level::warn, L"Failed to set drag region window attributes"); } } } SetRegion(newWidth, newHeight, buttonsRegion); }
4,219
C++
.cpp
139
27.122302
117
0.716716
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,846
basexamlpagehost.cpp
TranslucentTB_TranslucentTB/TranslucentTB/uwp/basexamlpagehost.cpp
#include "basexamlpagehost.hpp" #include <ShellScalingApi.h> #include <windows.ui.xaml.hosting.desktopwindowxamlsource.h> #include "win32.hpp" #include "../ProgramLog/error/win32.hpp" #include "../uwp/uwp.hpp" void BaseXamlPageHost::UpdateFrame() { // Magic that gives us shadows // we use the top side because any other side would cause a single line of white pixels to // suddenly flash when resizing the color picker. // can't use 0, that does nothing // or -1: turns it full white. const MARGINS margins = { 0, 0, 1, 0 }; HresultVerify(DwmExtendFrameIntoClientArea(m_WindowHandle, &margins), spdlog::level::info, L"Failed to extend frame into client area"); } wf::Rect BaseXamlPageHost::ScaleRect(wf::Rect rect, float scale) { return { rect.X * scale, rect.Y * scale, rect.Width * scale, rect.Height * scale }; } HMONITOR BaseXamlPageHost::GetInitialMonitor(POINT &cursor, xaml_startup_position position) { if (position == xaml_startup_position::mouse) { if (!GetCursorPos(&cursor)) { LastErrorHandle(spdlog::level::info, L"Failed to get cursor position"); } } return MonitorFromPoint(cursor, MONITOR_DEFAULTTOPRIMARY); } float BaseXamlPageHost::GetDpiScale(HMONITOR mon) { UINT dpiX, dpiY; if (const HRESULT hr = GetDpiForMonitor(mon, MDT_EFFECTIVE_DPI, &dpiX, &dpiY); SUCCEEDED(hr)) { return static_cast<float>(dpiX) / USER_DEFAULT_SCREEN_DPI; } else { HresultHandle(hr, spdlog::level::info, L"Failed to get monitor DPI"); return 1.0f; } } void BaseXamlPageHost::CalculateInitialPosition(int &x, int &y, int width, int height, POINT cursor, const RECT &workArea, xaml_startup_position position) noexcept { if (position == xaml_startup_position::mouse) { // Center on the mouse x = cursor.x - (width / 2); y = cursor.y - (height / 2); AdjustWindowPosition(x, y, width, height, workArea); } else { x = ((workArea.right - workArea.left - width) / 2) + workArea.left; y = ((workArea.bottom - workArea.top - height) / 2) + workArea.top; } } bool BaseXamlPageHost::AdjustWindowPosition(int &x, int &y, int width, int height, const RECT &workArea) noexcept { RECT coords = { x, y, x + width, y + height }; if (win32::RectFitsInRect(workArea, coords)) { // It fits, nothing to do. return false; } const bool rightDoesntFits = coords.right > workArea.right; const bool leftDoesntFits = coords.left < workArea.left; const bool bottomDoesntFits = coords.bottom > workArea.bottom; const bool topDoesntFits = coords.top < workArea.top; if ((rightDoesntFits && leftDoesntFits) || (bottomDoesntFits && topDoesntFits)) { // Doesn't fits in the monitor work area :( return true; } // Offset the rect so that it is completely in the work area int x_offset = 0; if (rightDoesntFits) { x_offset = workArea.right - coords.right; // Negative offset } else if (leftDoesntFits) { x_offset = workArea.left - coords.left; } int y_offset = 0; if (bottomDoesntFits) { y_offset = workArea.bottom - coords.bottom; // Negative offset } else if (topDoesntFits) { y_offset = workArea.top - coords.top; } win32::OffsetRect(coords, x_offset, y_offset); x = coords.left; y = coords.top; return true; } LRESULT BaseXamlPageHost::MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_QUERYENDSESSION: if (!TryClose()) { return 0; } else { return 1; } case WM_SETTINGCHANGE: case WM_THEMECHANGED: case WM_SIZE: if (const auto coreWin = UWP::GetCoreWindow()) { // forward theme changes to the fake core window // so that they propagate to our islands // do the same for size: https://github.com/microsoft/microsoft-ui-xaml/issues/3577#issuecomment-1399250405 coreWin.send_message(uMsg, wParam, lParam); } break; case WM_NCCALCSIZE: return 0; case WM_DWMCOMPOSITIONCHANGED: UpdateFrame(); return 0; case WM_SETFOCUS: if (!SetFocus(m_interopWnd)) { LastErrorHandle(spdlog::level::info, L"Failed to set focus to Island host"); } return 0; case WM_DPICHANGED: { const auto newRect = reinterpret_cast<RECT *>(lParam); ResizeWindow(newRect->left, newRect->top, newRect->right - newRect->left, newRect->bottom - newRect->top, true); return 0; } } return MessageWindow::MessageHandler(uMsg, wParam, lParam); } void BaseXamlPageHost::ResizeWindow(int x, int y, int width, int height, bool move, UINT flags) { flags |= SWP_NOACTIVATE | SWP_NOZORDER; if (!SetWindowPos(m_interopWnd, nullptr, 0, 0, width, height, flags)) [[unlikely]] { LastErrorHandle(spdlog::level::info, L"Failed to set interop window position"); } if (!SetWindowPos(m_WindowHandle, nullptr, x, y, width, height, flags | (move ? 0 : SWP_NOMOVE))) [[unlikely]] { LastErrorHandle(spdlog::level::info, L"Failed to set host window position"); } } void BaseXamlPageHost::PositionDragRegion(wf::Rect position, wf::Rect buttonsRegion, UINT flags) { if (const auto wndRect = rect()) { m_DragRegion.Position(*wndRect, position, buttonsRegion, flags); } } bool BaseXamlPageHost::PaintBackground(HDC dc, const RECT &target, winrt::Windows::UI::Color col) { if (!m_BackgroundBrush || m_BackgroundColor != col) [[unlikely]] { m_BackgroundBrush.reset(CreateSolidBrush(RGB(col.R, col.G, col.B))); if (m_BackgroundBrush) { m_BackgroundColor = col; } else { MessagePrint(spdlog::level::info, L"Failed to create background brush"); return false; } } if (FillRect(dc, &target, m_BackgroundBrush.get())) { return true; } else { LastErrorHandle(spdlog::level::info, L"Failed to fill rectangle."); return false; } } BaseXamlPageHost::BaseXamlPageHost(WindowClass &classRef, WindowClass &dragRegionClass) : MessageWindow(classRef, { }), m_DragRegion(dragRegionClass, m_WindowHandle) { UpdateFrame(); auto nativeSource = m_source.as<IDesktopWindowXamlSourceNative2>(); HresultVerify(nativeSource->AttachToWindow(m_WindowHandle), spdlog::level::critical, L"Failed to attach DesktopWindowXamlSource"); HresultVerify(nativeSource->get_WindowHandle(m_interopWnd.put()), spdlog::level::critical, L"Failed to get interop window handle"); m_focusToken = m_source.TakeFocusRequested([](const wuxh::DesktopWindowXamlSource &sender, const wuxh::DesktopWindowXamlSourceTakeFocusRequestedEventArgs &args) { const auto request = args.Request(); const auto reason = request.Reason(); if (reason == wuxh::XamlSourceFocusNavigationReason::First || reason == wuxh::XamlSourceFocusNavigationReason::Last) { // just cycle back to beginning sender.NavigateFocus(request); } }); }
6,581
C++
.cpp
212
28.660377
163
0.737257
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,847
dynamicdependency.cpp
TranslucentTB_TranslucentTB/TranslucentTB/uwp/dynamicdependency.cpp
#include "dynamicdependency.hpp" #include <wil/win32_helpers.h> #include "../ProgramLog/error/win32.hpp" #include "../resources/ids.h" #include "../localization.hpp" #include "version.hpp" #include "../windows/window.hpp" DynamicDependency::DynamicDependency(HMODULE hModule, Util::null_terminated_wstring_view packageFamilyName, const PACKAGE_VERSION &minVersion, bool hasPackageIdentity) : m_Context(nullptr) { if (!hasPackageIdentity) { if (!IsApiSetImplemented("api-ms-win-appmodel-runtime-l1-1-5")) { Localization::ShowLocalizedMessageBox(IDS_PORTABLE_UNSUPPORTED, MB_OK | MB_ICONWARNING | MB_SETFOREGROUND, hModule).join(); ExitProcess(1); } static constexpr PackageDependencyProcessorArchitectures arch = #if defined(_M_AMD64) PackageDependencyProcessorArchitectures_X64; #elif defined(_M_ARM64) PackageDependencyProcessorArchitectures_Arm64; #endif // we are using process dependency lifetime because we want the app to be portable, so we cannot be sure if a dependency ID created by a // previous instance is valid anymore - the app might have been launched on another computer. Plus I'm too lazy to implement proper storage. HRESULT hr = TryCreatePackageDependency(nullptr, packageFamilyName.c_str(), minVersion, arch, PackageDependencyLifetimeKind_Process, nullptr, CreatePackageDependencyOptions_None, m_dependencyId.put()); if (FAILED(hr)) [[unlikely]] { if (hr == STATEREPOSITORY_E_DEPENDENCY_NOT_RESOLVED) { Localization::ShowLocalizedMessageBoxWithFormat(IDS_MISSING_DEPENDENCIES, MB_OK | MB_ICONWARNING | MB_SETFOREGROUND, hModule, packageFamilyName, Version::FromPackageVersion(minVersion)).join(); ExitProcess(1); } else { HresultHandle(hr, spdlog::level::critical, L"Failed to create a dynamic dependency"); } } wil::unique_process_heap_string packageFullName; hr = AddPackageDependency(m_dependencyId.get(), 0, AddPackageDependencyOptions_None, &m_Context, packageFullName.put()); HresultVerify(hr, spdlog::level::critical, L"Failed to add a runtime dependency"); } } DynamicDependency::~DynamicDependency() noexcept(false) { if (m_Context) { HRESULT hr = RemovePackageDependency(m_Context); if (SUCCEEDED(hr)) { m_Context = nullptr; } else { // we get random invalid parameter errors despite the parameter being correct. HresultHandle(hr, spdlog::level::info, L"Failed to remove a runtime dependency"); } hr = DeletePackageDependency(m_dependencyId.get()); HresultVerify(hr, spdlog::level::warn, L"Failed to delete a dynamic dependency"); } }
2,574
C++
.cpp
61
39.409836
203
0.772546
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,848
uwp.cpp
TranslucentTB_TranslucentTB/TranslucentTB/uwp/uwp.cpp
#include "uwp.hpp" #include <Windows.h> #include <appmodel.h> #include <CoreWindow.h> #include <DispatcherQueue.h> #include <ShlObj_core.h> #include <wil/resource.h> #include <winrt/Windows.Foundation.h> #include <winrt/Windows.UI.Core.h> #include "../ProgramLog/error/win32.hpp" #include "../ProgramLog/error/winrt.hpp" std::optional<std::wstring> UWP::GetPackageFamilyName() { static constexpr std::wstring_view FAILED_TO_GET = L"Failed to get package family name"; UINT32 length = 0; LONG result = GetCurrentPackageFamilyName(&length, nullptr); if (result != ERROR_INSUFFICIENT_BUFFER) [[unlikely]] { if (result == APPMODEL_ERROR_NO_PACKAGE) { return std::nullopt; } else { HresultHandle(HRESULT_FROM_WIN32(result), spdlog::level::critical, FAILED_TO_GET); } } std::wstring familyName; familyName.resize_and_overwrite(length - 1, [](wchar_t* data, std::size_t count) { UINT32 length = static_cast<UINT32>(count) + 1; const LONG result = GetCurrentPackageFamilyName(&length, data); if (result != ERROR_SUCCESS) [[unlikely]] { HresultHandle(HRESULT_FROM_WIN32(result), spdlog::level::critical, FAILED_TO_GET); } return length - 1; }); return familyName; } std::optional<std::filesystem::path> UWP::GetAppStorageFolder() { if (const auto familyName = UWP::GetPackageFamilyName()) { wil::unique_cotaskmem_string appdata; HresultVerify( SHGetKnownFolderPath(FOLDERID_LocalAppData, KF_FLAG_NO_PACKAGE_REDIRECTION, nullptr, appdata.put()), spdlog::level::critical, L"Failed to get local app data folder" ); std::filesystem::path storage = appdata.get(); storage /= L"Packages"; storage /= *familyName; return std::move(storage); } else { return std::nullopt; } } winrt::fire_and_forget UWP::OpenUri(const wf::Uri &uri) { bool opened; try { opened = co_await winrt::Windows::System::Launcher::LaunchUriAsync(uri); } catch (const winrt::hresult_error &err) { HresultErrorHandle(err, spdlog::level::err, L"Failed to launch uri."); co_return; } if (!opened) { MessagePrint(spdlog::level::err, L"Uri was not launched."); } } winrt::Windows::System::DispatcherQueueController UWP::CreateDispatcherController() { const DispatcherQueueOptions options = { .dwSize = sizeof(options), .threadType = DQTYPE_THREAD_CURRENT, .apartmentType = DQTAT_COM_STA }; winrt::com_ptr<ABI::Windows::System::IDispatcherQueueController> controller; HresultVerify(CreateDispatcherQueueController(options, controller.put()), spdlog::level::critical, L"Failed to create dispatcher!"); return { controller.detach(), winrt::take_ownership_from_abi }; } Window UWP::GetCoreWindow() { Window coreWin; try { const auto coreInterop = winrt::Windows::UI::Core::CoreWindow::GetForCurrentThread().as<ICoreWindowInterop>(); winrt::check_hresult(coreInterop->get_WindowHandle(coreWin.put())); } HresultErrorCatch(spdlog::level::warn, L"Failed to get core window handle"); return coreWin; } void UWP::HideCoreWindow() { if (auto coreWin = GetCoreWindow()) { coreWin.show(SW_HIDE); } } wuxh::WindowsXamlManager UWP::CreateXamlManager() try { const auto manager = wuxh::WindowsXamlManager::InitializeForCurrentThread(); HideCoreWindow(); return manager; } HresultErrorCatch(spdlog::level::critical, L"Failed to create Xaml manager");
3,324
C++
.cpp
113
27.19469
133
0.748983
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,849
configmanager.cpp
TranslucentTB_TranslucentTB/TranslucentTB/managers/configmanager.cpp
#include "configmanager.hpp" #include <cerrno> #include <cstdio> #include <rapidjson/encodedstream.h> #include <rapidjson/error/error.h> #include <rapidjson/filereadstream.h> #include <rapidjson/filewritestream.h> #include <rapidjson/prettywriter.h> #include <share.h> #include <Shlwapi.h> #include <wil/resource.h> #include "winrt.hpp" #include <winrt/Windows.ApplicationModel.Resources.Core.h> #include "constants.hpp" #include "../../ProgramLog/error/errno.hpp" #include "../../ProgramLog/error/rapidjson.hpp" #include "../../ProgramLog/error/std.hpp" #include "../../ProgramLog/error/win32.hpp" #include "../../ProgramLog/error/winrt.hpp" #include "../../ProgramLog/log.hpp" #include "config/rapidjsonhelper.hpp" #include "win32.hpp" #include "../localization.hpp" #include "../resources/ids.h" std::filesystem::path ConfigManager::DetermineConfigPath(const std::optional<std::filesystem::path> &storageFolder) { std::filesystem::path path; if (storageFolder) { path = *storageFolder / L"RoamingState"; } else { const auto [loc, hr] = win32::GetExeLocation(); HresultVerify(hr, spdlog::level::critical, L"Failed to determine executable location!"); path = loc.parent_path(); } path /= CONFIG_FILE; return path; } void ConfigManager::WatcherCallback(void *context, DWORD, std::wstring_view fileName) { if (fileName.empty() || win32::IsSameFilename(fileName, CONFIG_FILE)) { const auto that = static_cast<ConfigManager *>(context); if (!that->ScheduleReload()) { that->Reload(); } } } void ConfigManager::TimerCallback(void *context, DWORD, DWORD) { static_cast<ConfigManager *>(context)->Reload(); } bool ConfigManager::TryOpenConfigAsJson() noexcept { wil::unique_hkey key; const HRESULT hr = AssocQueryKey(ASSOCF_VERIFY | ASSOCF_INIT_IGNOREUNKNOWN, ASSOCKEY_SHELLEXECCLASS, L".json", L"open", key.put()); if (SUCCEEDED(hr)) { SHELLEXECUTEINFO info = { .cbSize = sizeof(info), .fMask = SEE_MASK_CLASSKEY | SEE_MASK_FLAG_NO_UI, .lpVerb = L"open", .lpFile = m_ConfigPath.c_str(), .nShow = SW_SHOW, .hkeyClass = key.get() }; const bool success = ShellExecuteEx(&info); if (!success) { LastErrorHandle(spdlog::level::warn, L"Failed to launch JSON file editor"); } return success; } else { if (hr != HRESULT_FROM_WIN32(ERROR_NO_ASSOCIATION)) { HresultHandle(hr, spdlog::level::warn, L"Failed to query for .json file association"); } return false; } } void ConfigManager::SaveToFile(FILE *f) const { static constexpr std::string_view COMMENT = "// See https://TranslucentTB.github.io/config for more information\n"; static constexpr std::wstring_view SCHEMA = L"https://TranslucentTB.github.io/settings.schema.json"; char buffer[1024]; rj::FileWriteStream filestream(f, buffer, std::size(buffer)); using OutputStream = rj::EncodedOutputStream<rj::UTF8<>, rj::FileWriteStream>; OutputStream out(filestream, true); for (const char c : COMMENT) { out.Put(c); } rj::PrettyWriter<OutputStream, rj::UTF16LE<>> writer(out); writer.SetIndent(' ', 2); writer.StartObject(); rjh::Serialize(writer, SCHEMA, SCHEMA_KEY); m_Config.Serialize(writer); writer.EndObject(); writer.Flush(); } bool ConfigManager::LoadFromFile(FILE *f) { static constexpr std::wstring_view DESERIALIZE_FAILED = L"Failed to deserialize JSON document"; char buffer[1024]; rj::FileReadStream filestream(f, buffer, std::size(buffer)); rj::AutoUTFInputStream<uint32_t, rj::FileReadStream> in(filestream); rj::GenericDocument<rj::UTF16LE<>> doc; if (const rj::ParseResult result = doc.ParseStream<rj::kParseCommentsFlag | rj::kParseTrailingCommasFlag, rj::AutoUTF<uint32_t>>(in)) { // remove the schema key to avoid a false unknown key warning doc.RemoveMember(rjh::StringViewToValue(SCHEMA_KEY)); try { // load the defaults before deserializing to not reuse previous settings // in case some keys are missing from the file m_Config = { }; m_Config.Deserialize(doc, [](std::wstring_view unknownKey) { if (Error::ShouldLog<spdlog::level::info>()) { MessagePrint(spdlog::level::info, std::format(L"Unknown key found in JSON: {}", unknownKey)); } }); // everything went fine, we can return! return true; } HelperDeserializationErrorCatch(spdlog::level::err, DESERIALIZE_FAILED) StdSystemErrorCatch(spdlog::level::err, DESERIALIZE_FAILED); } else if (result.Code() != rj::kParseErrorDocumentEmpty) { ParseErrorCodeHandle(result.Code(), spdlog::level::err, DESERIALIZE_FAILED); } // parsing failed, use defaults m_Config = { }; return false; } bool ConfigManager::Load(bool firstLoad) { if (const wil::unique_file file { _wfsopen(m_ConfigPath.c_str(), L"rbS", _SH_DENYNO) }) { if (LoadFromFile(file.get())) { if (firstLoad) { if (!m_Config.Language.empty() && Localization::SetProcessLangOverride(m_Config.Language)) { m_StartupLanguage = m_Config.Language; } } else if (m_StartupLanguage != m_Config.Language && !std::exchange(m_ShownChangeWarning, true)) { // try using the new locale for that dialog box LCID newLang = LocaleNameToLCID(m_Config.Language.c_str(), LOCALE_ALLOW_NEUTRAL_NAMES); Localization::ShowLocalizedMessageBox(IDS_LANGUAGE_CHANGED, MB_OK | MB_ICONINFORMATION | MB_SETFOREGROUND, wil::GetModuleInstanceHandle(), newLang ? LANGIDFROMLCID(newLang) : MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL)).detach(); } } // note: this demarks if the file exists, even if parsing failed. return true; } else { const errno_t err = errno; const bool fileExists = err != ENOENT; if (fileExists) { // if the file failed to open, but it exists, something went wrong ErrnoTHandle(err, spdlog::level::err, L"Failed to open configuration file"); } // opening file failed, use defaults m_Config = { }; return fileExists; } } void ConfigManager::Reload() { Load(); UpdateVerbosity(); m_Callback(m_Context); } bool ConfigManager::ScheduleReload() { if (m_ReloadTimer) { LARGE_INTEGER waitTime{}; // 200 ms, relative to current time. arbitrarily chosen to get a balance // between feeling snappy and not triggering errors due to the various weird // ways editors save files. waitTime.QuadPart = -2000000; if (SetWaitableTimer(m_ReloadTimer.get(), &waitTime, 0, TimerCallback, this, false)) { return true; } else { LastErrorHandle(spdlog::level::warn, L"Failed to set waitable timer"); } } return false; } ConfigManager::ConfigManager(const std::optional<std::filesystem::path> &storageFolder, bool &fileExists, callback_t callback, void *context) : m_ConfigPath(DetermineConfigPath(storageFolder)), m_Watcher(m_ConfigPath.parent_path(), false, FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE, WatcherCallback, this), m_ReloadTimer(CreateWaitableTimer(nullptr, true, nullptr)), m_ShownChangeWarning(false), m_Callback(callback), m_Context(context) { if (!m_ReloadTimer) { LastErrorHandle(spdlog::level::warn, L"Failed to create waitable timer"); } fileExists = Load(true); UpdateVerbosity(); } ConfigManager::~ConfigManager() { if (m_ReloadTimer) { if (!CancelWaitableTimer(m_ReloadTimer.get())) { LastErrorHandle(spdlog::level::info, L"Failed to cancel reload timer"); } } } void ConfigManager::UpdateVerbosity() { if (const auto sink = Log::GetSink()) { sink->set_level(m_Config.LogVerbosity); } } void ConfigManager::EditConfigFile() { SaveConfig(); if (!TryOpenConfigAsJson()) { HresultVerify(win32::EditFile(m_ConfigPath), spdlog::level::err, L"Failed to open configuration file."); } } void ConfigManager::DeleteConfigFile() { std::error_code errc; std::filesystem::remove(m_ConfigPath, errc); StdErrorCodeVerify(errc, spdlog::level::warn, L"Failed to delete config file"); } void ConfigManager::SaveConfig() const { if (m_Config.DisableSaving) { return; } std::filesystem::path tempFile = m_ConfigPath; tempFile.replace_extension(L".tmp"); wil::unique_file file; const errno_t err = _wfopen_s(file.put(), tempFile.c_str(), L"wbS"); if (err == 0) { SaveToFile(file.get()); file.reset(); if (!ReplaceFile(m_ConfigPath.c_str(), tempFile.c_str(), nullptr, REPLACEFILE_WRITE_THROUGH | REPLACEFILE_IGNORE_MERGE_ERRORS | REPLACEFILE_IGNORE_ACL_ERRORS, nullptr, nullptr)) { // If the target file doesn't exist (e.g. brand new installation of TranslucentTB), ReplaceFile fails. if (const auto lastErr = GetLastError(); lastErr == ERROR_FILE_NOT_FOUND) { if (!MoveFileEx(tempFile.c_str(), m_ConfigPath.c_str(), MOVEFILE_WRITE_THROUGH)) { LastErrorHandle(spdlog::level::err, L"Failed to move temporary configuration file"); } } else { HresultHandle(HRESULT_FROM_WIN32(lastErr), spdlog::level::err, L"Failed to replace configuration file"); } } } else { ErrnoTHandle(err, spdlog::level::err, L"Failed to save configuration!"); } }
8,953
C++
.cpp
286
28.748252
231
0.731826
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,850
startupmanager.cpp
TranslucentTB_TranslucentTB/TranslucentTB/managers/startupmanager.cpp
#include "startupmanager.hpp" #include <winrt/Windows.Foundation.Collections.h> #include "../../ProgramLog/error/winrt.hpp" #include "../uwp/uwp.hpp" #include "../localization.hpp" #include "../resources/ids.h" winrt::fire_and_forget StartupManager::AcquireTask() try { if (!m_StartupTask) { m_StartupTask = co_await winrt::Windows::ApplicationModel::StartupTask::GetAsync(L"TranslucentTB"); } } HresultErrorCatch(spdlog::level::err, L"Failed to load startup task."); std::optional<winrt::Windows::ApplicationModel::StartupTaskState> StartupManager::GetState() const try { return m_StartupTask ? std::optional(m_StartupTask.State()) : std::nullopt; } HresultErrorCatch(spdlog::level::warn, L"Failed to get startup task status."); wf::IAsyncAction StartupManager::Enable() try { if (m_StartupTask) { const auto result = co_await m_StartupTask.RequestEnableAsync(); using enum winrt::Windows::ApplicationModel::StartupTaskState; if (result != Enabled && result != EnabledByPolicy) { Localization::ShowLocalizedMessageBox(IDS_STARTUPTASK_BROKEN, MB_OK | MB_ICONWARNING | MB_SETFOREGROUND).detach(); } } } HresultErrorCatch(spdlog::level::err, L"Failed to enable startup task."); void StartupManager::Disable() try { if (m_StartupTask) { m_StartupTask.Disable(); } } HresultErrorCatch(spdlog::level::err, L"Failed to disable startup task."); void StartupManager::OpenSettingsPage() try { UWP::OpenUri(wf::Uri(L"ms-settings:startupapps")); } HresultErrorCatch(spdlog::level::err, L"Failed to open Settings app.");
1,544
C++
.cpp
45
32.533333
117
0.764075
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,851
taskbarattributeworker.cpp
TranslucentTB_TranslucentTB/TranslucentTB/taskbar/taskbarattributeworker.cpp
#include "taskbarattributeworker.hpp" #include <functional> #include <member_thunk/member_thunk.hpp> #include "constants.hpp" #include "../localization.hpp" #include "../../ProgramLog/error/win32.hpp" #include "../../ProgramLog/error/winrt.hpp" #include "undoc/explorer.hpp" #include "undoc/user32.hpp" #include "undoc/winuser.hpp" #include "win32.hpp" #include "winrt/Windows.Foundation.h" #include "winrt/Windows.Foundation.Metadata.h" class TaskbarAttributeWorker::AttributeRefresher { private: TaskbarAttributeWorker &m_Worker; taskbar_iterator m_MainMonIt; bool m_Refresh; public: AttributeRefresher(TaskbarAttributeWorker &worker, bool refresh = true) noexcept : m_Worker(worker), m_MainMonIt(m_Worker.m_Taskbars.end()), m_Refresh(refresh) { } AttributeRefresher(const AttributeRefresher &) = delete; AttributeRefresher &operator =(const AttributeRefresher &) = delete; void refresh(taskbar_iterator it) { if (m_Refresh) { if (it->first == MonitorFromPoint({ 0, 0 }, MONITOR_DEFAULTTOPRIMARY)) { assert(m_MainMonIt == m_Worker.m_Taskbars.end()); m_MainMonIt = it; } else { m_Worker.RefreshAttribute(it); } } } void disarm() noexcept { m_MainMonIt = m_Worker.m_Taskbars.end(); } ~AttributeRefresher() noexcept(false) { if (m_Refresh && m_MainMonIt != m_Worker.m_Taskbars.end()) { m_Worker.RefreshAttribute(m_MainMonIt); } } }; template<DWORD insert, DWORD remove> void TaskbarAttributeWorker::WindowInsertRemove(DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD, DWORD) { if (const Window window(hwnd); idObject == OBJID_WINDOW && idChild == CHILDID_SELF) { if (event == insert && window.valid()) { InsertWindow(window, true); } else if (event == remove) { AttributeRefresher refresher(*this); for (auto it = m_Taskbars.begin(); it != m_Taskbars.end(); ++it) { RemoveWindow(window, it, refresher); } } } } void TaskbarAttributeWorker::OnAeroPeekEnterExit(DWORD event, HWND, LONG, LONG, DWORD, DWORD) { m_PeekActive = event == EVENT_SYSTEM_PEEKSTART; MessagePrint(spdlog::level::debug, m_PeekActive ? L"Aero Peek entered" : L"Aero Peek exited"); RefreshAllAttributes(); } void TaskbarAttributeWorker::OnWindowStateChange(DWORD, HWND hwnd, LONG idObject, LONG idChild, DWORD, DWORD) { if (const Window window(hwnd); idObject == OBJID_WINDOW && idChild == CHILDID_SELF && window.valid()) { InsertWindow(window, true); } } void TaskbarAttributeWorker::OnWindowCreateDestroy(DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD, DWORD) { if (const Window window(hwnd); idObject == OBJID_WINDOW && idChild == CHILDID_SELF) { if (event == EVENT_OBJECT_CREATE && window.valid()) { if (const auto className = window.classname(); className && (*className == TASKBAR || *className == SECONDARY_TASKBAR)) { MessagePrint(spdlog::level::debug, L"A taskbar got created, refreshing..."); ResetState(); } else { InsertWindow(window, true); } } else if (event == EVENT_OBJECT_DESTROY) { // events are asynchronous, the window might be invalid already // important to not try to query its info here, just go off the handle AttributeRefresher refresher(*this); for (auto it = m_Taskbars.begin(); it != m_Taskbars.end(); ++it) { if (it->second.Taskbar.TaskbarWindow == window) { MessagePrint(spdlog::level::debug, L"A taskbar got destroyed, refreshing..."); ResetState(); // iterators invalid refresher.disarm(); return; } RemoveWindow<LogWindowRemovalDestroyed>(window, it, refresher); } } } } void TaskbarAttributeWorker::OnForegroundWindowChange(DWORD, HWND hwnd, LONG idObject, LONG idChild, DWORD, DWORD) { if (idObject == OBJID_WINDOW && idChild == CHILDID_SELF) { const Window oldForegroundWindow = std::exchange(m_ForegroundWindow, Window(hwnd).valid() ? hwnd : Window::NullWindow); if (Error::ShouldLog<spdlog::level::debug>()) { MessagePrint(spdlog::level::debug, std::format(L"Changed foreground window to {}", DumpWindow(m_ForegroundWindow))); } AttributeRefresher refresher(*this); HMONITOR oldMonitor = nullptr; if (oldForegroundWindow) { oldMonitor = oldForegroundWindow.monitor(); if (const auto it = m_Taskbars.find(oldMonitor); it != m_Taskbars.end()) { refresher.refresh(it); } } if (m_ForegroundWindow) { if (auto newMonitor = m_ForegroundWindow.monitor(); newMonitor != oldMonitor) { if (const auto it = m_Taskbars.find(newMonitor); it != m_Taskbars.end()) { refresher.refresh(it); } } } } } void TaskbarAttributeWorker::OnWindowOrderChange(DWORD, HWND hwnd, LONG idObject, LONG idChild, DWORD, DWORD) { if (const Window window(hwnd); idObject == OBJID_WINDOW && idChild == CHILDID_SELF && window.valid()) { if (const auto iter = m_Taskbars.find(window.monitor()); iter != m_Taskbars.end()) { RefreshAttribute(iter); } } } void TaskbarAttributeWorker::OnStartVisibilityChange(bool state) { HMONITOR mon = nullptr; if (state) { mon = m_CurrentStartMonitor = GetStartMenuMonitor(); if (Error::ShouldLog<spdlog::level::debug>()) { MessagePrint(spdlog::level::debug, std::format(L"Start menu opened on monitor {}", static_cast<void *>(mon))); } } else { mon = std::exchange(m_CurrentStartMonitor, nullptr); MessagePrint(spdlog::level::debug, L"Start menu closed"); } if (const auto iter = m_Taskbars.find(mon); iter != m_Taskbars.end()) { RefreshAttribute(iter); } } void TaskbarAttributeWorker::OnTaskViewVisibilityChange(bool state) { m_TaskViewActive = state; MessagePrint(spdlog::level::debug, m_TaskViewActive ? L"Task View opened" : L"Task View closed"); RefreshAllAttributes(); } void TaskbarAttributeWorker::OnSearchVisibilityChange(bool state) { HMONITOR mon = nullptr; if (state) { mon = m_CurrentSearchMonitor = GetSearchMonitor(); if (Error::ShouldLog<spdlog::level::debug>()) { MessagePrint(spdlog::level::debug, std::format(L"Search opened on monitor {}", static_cast<void *>(mon))); } } else { mon = std::exchange(m_CurrentSearchMonitor, nullptr); MessagePrint(spdlog::level::debug, L"Search closed"); } if (const auto iter = m_Taskbars.find(mon); iter != m_Taskbars.end()) { RefreshAttribute(iter); } } void TaskbarAttributeWorker::OnForceRefreshTaskbar(Window taskbar) { if (!m_TaskbarService) { m_disableAttributeRefreshReply = true; auto guard = wil::scope_exit([this] { m_disableAttributeRefreshReply = false; }); taskbar.send_message(WM_DWMCOMPOSITIONCHANGED); guard.reset(); taskbar.send_message(WM_DWMCOMPOSITIONCHANGED); } } LRESULT TaskbarAttributeWorker::OnSystemSettingsChange(UINT uiAction) { if (uiAction == SPI_SETWORKAREA) { MessagePrint(spdlog::level::debug, L"Work area change detected, refreshing..."); ResetState(); } return 0; } LRESULT TaskbarAttributeWorker::OnPowerBroadcast(const POWERBROADCAST_SETTING *settings) { if (settings && settings->PowerSetting == GUID_POWER_SAVING_STATUS && settings->DataLength == sizeof(DWORD)) { m_PowerSaver = *reinterpret_cast<const DWORD *>(&settings->Data); RefreshAllAttributes(); } return TRUE; } LRESULT TaskbarAttributeWorker::OnRequestAttributeRefresh(LPARAM lParam) { if (!m_disableAttributeRefreshReply && !m_TaskbarService) { const Window window = reinterpret_cast<HWND>(lParam); if (const auto iter = m_Taskbars.find(window.monitor()); iter != m_Taskbars.end() && iter->second.Taskbar.TaskbarWindow == window) { if (const auto config = GetConfig(iter); config.Accent != ACCENT_NORMAL) { SetAttribute(iter, config); return 1; } } } return 0; } LRESULT TaskbarAttributeWorker::MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam) { if (uMsg == WM_SETTINGCHANGE) { if (InSendMessage()) { // post the message back to ourself to process outside of SendMessage post_message(uMsg, wParam, lParam); return 0; } else { return OnSystemSettingsChange(static_cast<UINT>(wParam)); } } else if (uMsg == WM_DISPLAYCHANGE) { MessagePrint(spdlog::level::debug, L"Monitor configuration change detected, refreshing..."); ResetState(); return 0; } else if (uMsg == WM_POWERBROADCAST && wParam == PBT_POWERSETTINGCHANGE) { return OnPowerBroadcast(reinterpret_cast<const POWERBROADCAST_SETTING *>(lParam)); } else if (uMsg == m_TaskbarCreatedMessage) { MessagePrint(spdlog::level::debug, L"Main taskbar got created, refreshing..."); ResetState(); return 0; } else if (uMsg == m_RefreshRequestedMessage) { return OnRequestAttributeRefresh(lParam); } else if (uMsg == m_TaskViewVisibilityChangeMessage) { OnTaskViewVisibilityChange(wParam); return 0; } else if (uMsg == m_StartVisibilityChangeMessage) { OnStartVisibilityChange(wParam); return 0; } else if (uMsg == m_SearchVisibilityChangeMessage) { m_highestSeenSearchSource = std::max(m_highestSeenSearchSource, lParam); if (lParam == m_highestSeenSearchSource) { OnSearchVisibilityChange(wParam); } return 0; } else if (uMsg == m_ForceRefreshTaskbar) { OnForceRefreshTaskbar(reinterpret_cast<HWND>(lParam)); return 0; } return MessageWindow::MessageHandler(uMsg, wParam, lParam); } TaskbarAppearance TaskbarAttributeWorker::GetConfig(taskbar_iterator taskbar) const { if (m_Config.BatterySaverAppearance.Enabled && m_PowerSaver) { return WithPreview(txmp::TaskbarState::BatterySaver, m_Config.BatterySaverAppearance); } if (m_Config.TaskViewOpenedAppearance.Enabled && m_TaskViewActive) { return WithPreview(txmp::TaskbarState::TaskViewOpened, m_Config.TaskViewOpenedAppearance); } // Task View is ignored by peek, so shall we if (m_PeekActive) { return WithPreview(txmp::TaskbarState::Desktop, m_Config.DesktopAppearance); } // on windows 11, search is considered open when start is, so we need to check for start first. bool startOpened; if (m_IsWindows11 && m_CurrentSearchMonitor != nullptr) { // checking the search monitor is more reliable on windows 11 (if available) // so check the start monitor to see if it's open and then use the search monitor // to check *where* it's open. startOpened = m_CurrentStartMonitor != nullptr && m_CurrentSearchMonitor == taskbar->first; } else { startOpened = m_CurrentStartMonitor == taskbar->first; } if (m_Config.StartOpenedAppearance.Enabled && startOpened) { return WithPreview(txmp::TaskbarState::StartOpened, m_Config.StartOpenedAppearance); } if (m_Config.SearchOpenedAppearance.Enabled && !startOpened && m_CurrentSearchMonitor == taskbar->first) { return WithPreview(txmp::TaskbarState::SearchOpened, m_Config.SearchOpenedAppearance); } auto &maximisedWindows = taskbar->second.MaximisedWindows; const bool hasMaximizedWindows = SetContainsValidWindows(maximisedWindows); if (m_Config.MaximisedWindowAppearance.Enabled && hasMaximizedWindows) { if (m_Config.MaximisedWindowAppearance.HasRules()) { for (const Window wnd : Window::DesktopWindow().get_ordered_childrens()) { // find the highest maximized window in the z-order. if (maximisedWindows.contains(wnd)) { if (const auto rule = m_Config.MaximisedWindowAppearance.FindRule(wnd)) { // if it has a rule, use that rule return *rule; } else { // we only consider the highest z-order maximized window for rules // so stop looking through the z-order break; } } } } // otherwise, use the normal maximized state return WithPreview(txmp::TaskbarState::MaximisedWindow, m_Config.MaximisedWindowAppearance); } if (m_Config.VisibleWindowAppearance.Enabled && (hasMaximizedWindows || SetContainsValidWindows(taskbar->second.NormalWindows))) { // if there is no maximized window, and the foreground window is on the current monitor if (m_Config.VisibleWindowAppearance.HasRules() && !hasMaximizedWindows && m_ForegroundWindow.monitor() == taskbar->first) { // find a rule for the foreground window if (const auto rule = m_Config.VisibleWindowAppearance.FindRule(m_ForegroundWindow)) { // if it has a rule, use that rule return *rule; } } // otherwise use normal visible state return WithPreview(txmp::TaskbarState::VisibleWindow, m_Config.VisibleWindowAppearance); } return WithPreview(txmp::TaskbarState::Desktop, m_Config.DesktopAppearance); } void TaskbarAttributeWorker::ShowAeroPeekButton(const TaskbarInfo &taskbar, bool show) { if (const auto style = taskbar.PeekWindow.get_long_ptr(GWL_EXSTYLE)) { const bool success = SetNewWindowExStyle(taskbar.PeekWindow, *style, show ? (*style & ~WS_EX_LAYERED) : (*style | WS_EX_LAYERED)); if (!show && success) { // Non-zero alpha makes the button still interactible, even if practically invisible. if (!SetLayeredWindowAttributes(taskbar.PeekWindow, 0, 1, LWA_ALPHA)) { LastErrorHandle(spdlog::level::warn, L"Failed to set peek button layered attributes"); } } } } void TaskbarAttributeWorker::ShowTaskbarLine(const TaskbarInfo &taskbar, bool show) { if (auto workerW = taskbar.WorkerWWindow) { workerW.show(show ? SW_SHOWNA : SW_HIDE); } else if (taskbar.InnerXamlContent) { if (show) { if (auto rect = taskbar.InnerXamlContent.client_rect()) { const float scaleFactor = static_cast<float>(GetDpiForWindow(taskbar.InnerXamlContent)) / USER_DEFAULT_SCREEN_DPI; // bottom taskbar is the only available option in Windows 11 22000. rect->top += std::lround(1.0f * scaleFactor); if (wil::unique_hrgn rgn { CreateRectRgnIndirect(&*rect) }) { if (SetWindowRgn(taskbar.InnerXamlContent, rgn.get(), true)) { rgn.release(); } else { LastErrorHandle(spdlog::level::warn, L"Failed to set region of inner XAML window"); } } } } else { if (!SetWindowRgn(taskbar.InnerXamlContent, nullptr, true)) [[unlikely]] { LastErrorHandle(spdlog::level::info, L"Failed to clear window region of inner taskbar XAML"); } } } } void TaskbarAttributeWorker::SetAttribute(taskbar_iterator taskbar, TaskbarAppearance config) { if (m_TaskbarService) { if (config.Accent == ACCENT_NORMAL) { HresultVerify(m_TaskbarService->ReturnTaskbarToDefaultAppearance(taskbar->second.Taskbar.TaskbarWindow), spdlog::level::info, L"Failed to restore taskbar to normal"); } else { auto color = config.Color; TaskbarBrush brush = SolidColor; if (config.Accent == ACCENT_ENABLE_ACRYLICBLURBEHIND) { brush = Acrylic; } else if (config.Accent == ACCENT_ENABLE_GRADIENT) { color.A = 0xFF; } HresultVerify(m_TaskbarService->SetTaskbarAppearance(taskbar->second.Taskbar.TaskbarWindow, brush, color.ToABGR()), spdlog::level::info, L"Failed to set taskbar brush"); } } else { const auto window = taskbar->second.Taskbar.TaskbarWindow; if (config.Accent != ACCENT_NORMAL) { m_NormalTaskbars.erase(window); const bool isAcrylic = config.Accent == ACCENT_ENABLE_ACRYLICBLURBEHIND; if (isAcrylic && config.Color.A == 0) { // Acrylic mode doesn't likes a completely 0 opacity config.Color.A = 1; } ACCENT_POLICY policy = { config.Accent, static_cast<UINT>(isAcrylic ? 0 : 2), config.Color.ToABGR(), 0 }; const WINDOWCOMPOSITIONATTRIBDATA data = { WCA_ACCENT_POLICY, &policy, sizeof(policy) }; if (!SetWindowCompositionAttribute(window, &data)) [[unlikely]] { LastErrorHandle(spdlog::level::info, L"Failed to set window composition attribute"); } } else if (const auto [it, inserted] = m_NormalTaskbars.insert(window); inserted) { // If this is in response to a window being moved, we send the message way too often // and Explorer doesn't like that too much. window.send_message(WM_DWMCOMPOSITIONCHANGED, 1, 0); } } } void TaskbarAttributeWorker::RefreshAttribute(taskbar_iterator taskbar) { // These functions may trigger Windows internal message loops, // do not pass any member of taskbar map by reference. // See comment in InsertWindow. const auto taskbarInfo = taskbar->second.Taskbar; const auto &cfg = GetConfig(taskbar); SetAttribute(taskbar, cfg); if (m_TaskbarService) { HresultVerify(m_TaskbarService->SetTaskbarBorderVisibility(taskbarInfo.TaskbarWindow, cfg.ShowLine), spdlog::level::info, L"Failed to set taskbar border visibility"); } else if (taskbarInfo.InnerXamlContent || taskbarInfo.WorkerWWindow) { ShowTaskbarLine(taskbarInfo, cfg.ShowLine); } else if (taskbarInfo.PeekWindow) { // Ignore changes when peek is active if (!m_PeekActive) { ShowAeroPeekButton(taskbarInfo, cfg.ShowPeek); } } } void TaskbarAttributeWorker::RefreshAllAttributes() { AttributeRefresher refresher(*this); for (auto it = m_Taskbars.begin(); it != m_Taskbars.end(); ++it) { refresher.refresh(it); } } void TaskbarAttributeWorker::LogWindowInsertion(const std::pair<std::unordered_set<Window>::iterator, bool> &result, std::wstring_view state, HMONITOR mon) { if (result.second && Error::ShouldLog<spdlog::level::debug>()) { MessagePrint(spdlog::level::debug, std::format(L"Inserting {} window {} to monitor {}", state, DumpWindow(*result.first), static_cast<void *>(mon))); } } void TaskbarAttributeWorker::LogWindowRemoval(std::wstring_view state, Window window, HMONITOR mon) { if (Error::ShouldLog<spdlog::level::debug>()) { MessagePrint(spdlog::level::debug, std::format(L"Removing {} window {} from monitor {}", state, DumpWindow(window), static_cast<void *>(mon))); } } void TaskbarAttributeWorker::LogWindowRemovalDestroyed(std::wstring_view state, Window window, HMONITOR mon) { if (Error::ShouldLog<spdlog::level::debug>()) { MessagePrint(spdlog::level::debug, std::format(L"Removing {} window {} [window destroyed] from monitor {}", state, static_cast<void *>(window.handle()), static_cast<void *>(mon))); } } void TaskbarAttributeWorker::InsertWindow(Window window, bool refresh) { if (window.classname() == CORE_WINDOW) [[unlikely]] { // Windows.UI.Core.CoreWindow is always shell UI stuff // that we either have a dynamic mode for or should ignore. // so just skip it. return; } AttributeRefresher refresher(*this, refresh); // Note: The checks are done before iterating because // some methods (most notably Window::on_current_desktop) // will trigger a Windows internal message loop, // which pumps messages to the worker. When the DPI is // changing, it means m_Taskbars is cleared while we still // have an iterator to it. Acquiring the iterator after the // call to on_current_desktop resolves this issue. const bool windowMatches = window.is_user_window() && !m_Config.IgnoredWindows.IsFiltered(window); const HMONITOR mon = window.monitor(); for (auto it = m_Taskbars.begin(); it != m_Taskbars.end(); ++it) { auto &maximised = it->second.MaximisedWindows; auto &normal = it->second.NormalWindows; if (it->first == mon) { if (windowMatches && window.maximised()) { if (normal.erase(window) > 0) { LogWindowRemoval(L"normal", window, mon); } LogWindowInsertion(maximised.insert(window), L"maximised", mon); refresher.refresh(it); continue; } else if (windowMatches && !window.minimised()) { if (maximised.erase(window) > 0) { LogWindowRemoval(L"maximised", window, mon); } LogWindowInsertion(normal.insert(window), L"normal", mon); refresher.refresh(it); continue; } // fall out the if if the window is minimized } RemoveWindow(window, it, refresher); } } template<void(*logger)(std::wstring_view, Window, HMONITOR)> void TaskbarAttributeWorker::RemoveWindow(Window window, taskbar_iterator it, AttributeRefresher& refresher) { bool erased = false; if (it->second.MaximisedWindows.erase(window) > 0) { logger(L"maximised", window, it->first); erased = true; } if (it->second.NormalWindows.erase(window) > 0) { logger(L"normal", window, it->first); erased = true; } // only refresh the taskbar once in the case the window is in both if (erased) { refresher.refresh(it); } } bool TaskbarAttributeWorker::SetNewWindowExStyle(Window wnd, LONG_PTR oldStyle, LONG_PTR newStyle) { if (oldStyle != newStyle) { return wnd.set_long_ptr(GWL_EXSTYLE, newStyle).has_value(); } else { return true; } } bool TaskbarAttributeWorker::SetContainsValidWindows(std::unordered_set<Window> &set) { std::erase_if(set, [](Window wnd) { return !wnd.valid(); }); return !set.empty(); } void TaskbarAttributeWorker::DumpWindowSet(std::wstring_view prefix, const std::unordered_set<Window> &set, bool showInfo) { if (!set.empty()) { std::wstring buf; for (const Window window : set) { buf.clear(); if (showInfo) { buf += prefix; buf += DumpWindow(window); } else { std::format_to(std::back_inserter(buf), L"{}{}", prefix, static_cast<void *>(window.handle())); } MessagePrint(spdlog::level::off, buf); } } else { MessagePrint(spdlog::level::off, std::format(L"{}[none]", prefix)); } } std::wstring TaskbarAttributeWorker::DumpWindow(Window window) { if (window) { std::wstring title, className, fileName; if (auto titleOpt = window.title()) { title = std::move(*titleOpt); if (auto classNameOpt = window.classname()) { className = std::move(*classNameOpt); if (const auto fileOpt = window.file()) { fileName = fileOpt->filename().native(); } } } return std::format(L"{} [{}] [{}] [{}]", static_cast<void *>(window.handle()), title, className, fileName); } else { return L"0x0"; } } void TaskbarAttributeWorker::CreateAppVisibility() { if (m_StartVisibilityChangeMessage) { try { m_IAV = wil::CoCreateInstance<IAppVisibility>(CLSID_AppVisibility); } catch (const wil::ResultException &err) { ResultExceptionHandle(err, spdlog::level::warn, L"Failed to create app visibility instance."); return; } const auto av_sink = winrt::make_self<LauncherVisibilitySink>(*this, *m_StartVisibilityChangeMessage); m_IAVECookie.associate(m_IAV.get()); HresultVerify(m_IAV->Advise(av_sink.get(), m_IAVECookie.put()), spdlog::level::warn, L"Failed to register app visibility sink."); } } void TaskbarAttributeWorker::CreateSearchManager() { UnregisterSearchCallbacks(); m_SearchManager = nullptr; m_SearchViewCoordinator = nullptr; m_FindInStartViewCoordinator = nullptr; if (m_SearchVisibilityChangeMessage) { if (m_IsWindows11) { try { using winrt::WindowsUdk::UI::Shell::ShellView; using winrt::WindowsUdk::UI::Shell::ShellViewCoordinator; m_SearchViewCoordinator = ShellViewCoordinator{winrt::WindowsUdk::UI::Shell::ShellView::Search}; m_SearchViewVisibilityChangedToken = m_SearchViewCoordinator.VisibilityChanged([this](const ShellViewCoordinator &coordinator, const wf::IInspectable &) { post_message(*m_SearchVisibilityChangeMessage, coordinator.Visibility() == winrt::WindowsUdk::UI::Shell::ViewVisibility::Visible, 1); }); m_FindInStartViewCoordinator = ShellViewCoordinator { winrt::WindowsUdk::UI::Shell::ShellView::FindInStart }; m_FindInStartVisibilityChangedToken = m_FindInStartViewCoordinator.VisibilityChanged([this](const ShellViewCoordinator& coordinator, const wf::IInspectable&) { post_message(*m_SearchVisibilityChangeMessage, coordinator.Visibility() == winrt::WindowsUdk::UI::Shell::ViewVisibility::Visible, 2); }); } HresultErrorCatch(spdlog::level::warn, L"Failed to create ShellViewCoordinator"); } else { try { using winrt::Windows::Internal::Shell::Experience::IShellExperienceManagerFactory; using winrt::Windows::Internal::Shell::Experience::ICortanaExperienceManager; auto serviceManager = wil::CoCreateInstance<IServiceProvider>(CLSID_ImmersiveShell, CLSCTX_LOCAL_SERVER); IShellExperienceManagerFactory factory(nullptr); winrt::check_hresult(serviceManager->QueryService(winrt::guid_of<IShellExperienceManagerFactory>(), winrt::guid_of<IShellExperienceManagerFactory>(), winrt::put_abi(factory))); m_SearchManager = factory.GetExperienceManager(win32::IsAtLeastBuild(19041) ? SEH_SearchApp : SEH_Cortana).as<ICortanaExperienceManager>(); m_SuggestionsShownToken = m_SearchManager.SuggestionsShown([this](const ICortanaExperienceManager &, const wf::IInspectable &) { post_message(*m_SearchVisibilityChangeMessage, true, 0); }); m_SuggestionsHiddenToken = m_SearchManager.SuggestionsHidden([this](const ICortanaExperienceManager &, const wf::IInspectable &) { post_message(*m_SearchVisibilityChangeMessage, false, 0); }); } ResultExceptionCatch(spdlog::level::warn, L"Failed to create immersive shell service provider") HresultErrorCatch(spdlog::level::warn, L"Failed to query for ICortanaExperienceManager"); } } } void TaskbarAttributeWorker::UnregisterSearchCallbacks() noexcept { if (m_SearchManager) { if (m_SuggestionsShownToken) { m_SearchManager.SuggestionsShown(m_SuggestionsShownToken); m_SuggestionsShownToken = { }; } if (m_SuggestionsHiddenToken) { m_SearchManager.SuggestionsHidden(m_SuggestionsHiddenToken); m_SuggestionsHiddenToken = { }; } } if (m_FindInStartViewCoordinator) { if (m_FindInStartVisibilityChangedToken) { m_FindInStartViewCoordinator.VisibilityChanged(m_FindInStartVisibilityChangedToken); m_FindInStartVisibilityChangedToken = { }; } } if (m_SearchViewCoordinator) { if (m_SearchViewVisibilityChangedToken) { m_SearchViewCoordinator.VisibilityChanged(m_SearchViewVisibilityChangedToken); m_SearchViewVisibilityChangedToken = { }; } } } WINEVENTPROC TaskbarAttributeWorker::CreateThunk(void(CALLBACK TaskbarAttributeWorker:: *proc)(DWORD, HWND, LONG, LONG, DWORD, DWORD)) { return m_ThunkPage.make_thunk<WINEVENTPROC>(this, proc); } wil::unique_hwineventhook TaskbarAttributeWorker::CreateHook(DWORD eventMin, DWORD eventMax, WINEVENTPROC proc) { if (wil::unique_hwineventhook hook { SetWinEventHook(eventMin, eventMax, nullptr, proc, 0, 0, WINEVENT_OUTOFCONTEXT) }) { return hook; } else { MessagePrint(spdlog::level::critical, L"Failed to create a Windows event hook."); } } void TaskbarAttributeWorker::ReturnToStock() { if (m_TaskbarService) { HresultVerify(m_TaskbarService->RestoreAllTaskbarsToDefault(), spdlog::level::info, L"Failed to restore taskbars"); } else { // Copy taskbars to a vector because some functions // trigger Windows internal message loop. std::vector<TaskbarInfo> taskbarInfos; for (auto it = m_Taskbars.begin(); it != m_Taskbars.end(); ++it) { SetAttribute(it, { ACCENT_NORMAL, { 0, 0, 0, 0 }, true, true }); taskbarInfos.push_back(it->second.Taskbar); } for (const auto& taskbarInfo : taskbarInfos) { if (taskbarInfo.InnerXamlContent || taskbarInfo.WorkerWWindow) { ShowTaskbarLine(taskbarInfo, true); } else if (taskbarInfo.PeekWindow) { ShowAeroPeekButton(taskbarInfo, true); } } } } bool TaskbarAttributeWorker::IsStartMenuOpened() const { if (m_IAV) { BOOL start_visible; const HRESULT hr = m_IAV->IsLauncherVisible(&start_visible); if (SUCCEEDED(hr)) { return start_visible; } else { HresultHandle(hr, spdlog::level::info, L"Failed to query launcher visibility state."); } } return false; } bool TaskbarAttributeWorker::IsSearchOpened() const try { if (m_SearchViewCoordinator) { return m_SearchViewCoordinator.Visibility() == winrt::WindowsUdk::UI::Shell::ViewVisibility::Visible; } else if (m_SearchManager) { return m_SearchManager.SuggestionsShowing(); } else { return false; } } catch (const winrt::hresult_error &err) { HresultErrorHandle(err, spdlog::level::info, L"Failed to check if search is opened"); return false; } void TaskbarAttributeWorker::InsertTaskbar(HMONITOR mon, Window window) { TaskbarInfo taskbarInfo = { .TaskbarWindow = window }; if (m_IsWindows11) { if (win32::IsAtLeastBuild(22616)) // TODO: ignore explorer patcher classic taskbar { taskbarInfo.WorkerWWindow = window.find_child(L"WorkerW"); } else { taskbarInfo.InnerXamlContent = window.find_child(L"Windows.UI.Composition.DesktopWindowContentBridge", L"DesktopWindowXamlSource"); } } else { taskbarInfo.PeekWindow = window.find_child(L"TrayNotifyWnd").find_child(L"TrayShowDesktopButtonWClass"); } m_NormalTaskbars.insert(window); m_Taskbars.insert_or_assign(mon, MonitorInfo { taskbarInfo }); if (wil::unique_hhook hook { m_InjectExplorerHook(window) }) { m_Hooks.push_back(std::move(hook)); } else { LastErrorHandle(spdlog::level::critical, L"Failed to set hook."); } } BOOL TaskbarAttributeWorker::MonitorEnumProc(HMONITOR hMonitor, HDC, LPRECT lprcMonitor, LPARAM dwData) { const auto info = reinterpret_cast<MonitorEnumInfo*>(&dwData); for (const UINT edge : { ABE_BOTTOM, ABE_TOP, ABE_LEFT, ABE_RIGHT }) { APPBARDATA data = { sizeof(data) }; data.uEdge = edge; data.rc = *lprcMonitor; HWND hwndAutoHide = reinterpret_cast<HWND>(SHAppBarMessage(ABM_GETAUTOHIDEBAREX, &data)); if (hwndAutoHide == info->window) { info->monitor = hMonitor; return false; } } return true; } HMONITOR TaskbarAttributeWorker::GetTaskbarMonitor(Window taskbar) { MonitorEnumInfo info = { taskbar }; if (EnumDisplayMonitors(nullptr, nullptr, MonitorEnumProc, reinterpret_cast<LPARAM>(&info)) && info.monitor) { return info.monitor; } else { return taskbar.monitor(); } } TaskbarAttributeWorker::TaskbarAttributeWorker(const Config &cfg, HINSTANCE hInstance, DynamicLoader &loader, const std::optional<std::filesystem::path> &storageFolder) : MessageWindow(TTB_WORKERWINDOW, TTB_WORKERWINDOW, hInstance, WS_POPUP, WS_EX_NOREDIRECTIONBITMAP), SetWindowCompositionAttribute(loader.SetWindowCompositionAttribute()), ShouldSystemUseDarkMode(loader.ShouldSystemUseDarkMode()), m_PowerSaver(false), m_TaskViewActive(false), m_PeekActive(false), m_disableAttributeRefreshReply(false), m_ResettingState(false), m_ResetStateReentered(false), m_CurrentStartMonitor(nullptr), m_CurrentSearchMonitor(nullptr), m_Config(cfg), m_ThunkPage(member_thunk::allocate_page()), m_PeekUnpeekHook(CreateHook(EVENT_SYSTEM_PEEKSTART, EVENT_SYSTEM_PEEKEND, CreateThunk(&TaskbarAttributeWorker::OnAeroPeekEnterExit))), m_CloakUncloakHook(CreateHook(EVENT_OBJECT_CLOAKED, EVENT_OBJECT_UNCLOAKED, CreateThunk(&TaskbarAttributeWorker::WindowInsertRemove<EVENT_OBJECT_UNCLOAKED, EVENT_OBJECT_CLOAKED>))), m_MinimizeRestoreHook(CreateHook(EVENT_SYSTEM_MINIMIZESTART, EVENT_SYSTEM_MINIMIZEEND, CreateThunk(&TaskbarAttributeWorker::WindowInsertRemove<EVENT_SYSTEM_MINIMIZEEND, EVENT_SYSTEM_MINIMIZESTART>))), m_ShowHideHook(CreateHook(EVENT_OBJECT_SHOW, EVENT_OBJECT_HIDE, CreateThunk(&TaskbarAttributeWorker::WindowInsertRemove<EVENT_OBJECT_SHOW, EVENT_OBJECT_HIDE>))), m_CreateDestroyHook(CreateHook(EVENT_OBJECT_CREATE, EVENT_OBJECT_DESTROY, CreateThunk(&TaskbarAttributeWorker::OnWindowCreateDestroy))), m_ForegroundChangeHook(CreateHook(EVENT_SYSTEM_FOREGROUND, CreateThunk(&TaskbarAttributeWorker::OnForegroundWindowChange))), m_OrderChangeHook(CreateHook(EVENT_OBJECT_REORDER, CreateThunk(&TaskbarAttributeWorker::OnWindowOrderChange))), m_SearchManager(nullptr), m_SearchViewCoordinator(nullptr), m_FindInStartViewCoordinator(nullptr), m_highestSeenSearchSource(0), m_TaskbarCreatedMessage(Window::RegisterMessage(WM_TASKBARCREATED)), m_RefreshRequestedMessage(Window::RegisterMessage(WM_TTBHOOKREQUESTREFRESH)), m_TaskViewVisibilityChangeMessage(Window::RegisterMessage(WM_TTBHOOKTASKVIEWVISIBILITYCHANGE)), m_IsTaskViewOpenedMessage(Window::RegisterMessage(WM_TTBHOOKISTASKVIEWOPENED)), m_StartVisibilityChangeMessage(Window::RegisterMessage(WM_TTBSTARTVISIBILITYCHANGE)), m_SearchVisibilityChangeMessage(Window::RegisterMessage(WM_TTBSEARCHVISIBILITYCHANGE)), m_ForceRefreshTaskbar(Window::RegisterMessage(WM_TTBFORCEREFRESHTASKBAR)), m_LastExplorerPid(0), m_HookDll(storageFolder, L"ExplorerHooks.dll"), m_InjectExplorerHook(m_HookDll.GetProc<PFN_INJECT_EXPLORER_HOOK>("InjectExplorerHook")), m_TAPDll(storageFolder, L"ExplorerTAP.dll"), m_InjectExplorerTAP(m_TAPDll.GetProc<PFN_INJECT_EXPLORER_TAP>("InjectExplorerTAP")), m_IsWindows11(win32::IsAtLeastBuild(22000)) { const auto stateThunk = CreateThunk(&TaskbarAttributeWorker::OnWindowStateChange); m_ResizeMoveHook = CreateHook(EVENT_OBJECT_LOCATIONCHANGE, stateThunk); m_TitleChangeHook = CreateHook(EVENT_OBJECT_NAMECHANGE, stateThunk); m_ParentChangeHook = CreateHook(EVENT_OBJECT_PARENTCHANGE, stateThunk); m_ThunkPage.mark_executable(); m_PowerSaverHook.reset(RegisterPowerSettingNotification(m_WindowHandle, &GUID_POWER_SAVING_STATUS, DEVICE_NOTIFY_WINDOW_HANDLE)); if (!m_PowerSaverHook) { LastErrorHandle(spdlog::level::warn, L"Failed to create battery saver notification handle"); } CreateAppVisibility(); // we don't want to consider the first state reset as an Explorer restart. ResetState(true); } void TaskbarAttributeWorker::DumpState() { MessagePrint(spdlog::level::off, L"===== Begin TaskbarAttributeWorker state dump ====="); std::wstring buf; for (const auto &[monitor, info] : m_Taskbars) { buf.clear(); std::format_to(std::back_inserter(buf), L"Monitor {}:", static_cast<void *>(monitor)); MessagePrint(spdlog::level::off, buf); buf.clear(); std::format_to(std::back_inserter(buf), L"\tTaskbar handle: {}", DumpWindow(info.Taskbar.TaskbarWindow)); MessagePrint(spdlog::level::off, buf); buf.clear(); std::format_to(std::back_inserter(buf), L"\tPeek button handle: {}", DumpWindow(info.Taskbar.PeekWindow)); MessagePrint(spdlog::level::off, buf); buf.clear(); std::format_to(std::back_inserter(buf), L"\tInner XAML handle: {}", DumpWindow(info.Taskbar.InnerXamlContent)); MessagePrint(spdlog::level::off, buf); buf.clear(); std::format_to(std::back_inserter(buf), L"\tWorkerW handle: {}", DumpWindow(info.Taskbar.WorkerWWindow)); MessagePrint(spdlog::level::off, buf); MessagePrint(spdlog::level::off, L"\tMaximised windows:"); DumpWindowSet(L"\t\t\t", info.MaximisedWindows); MessagePrint(spdlog::level::off, L"\tNormal windows:"); DumpWindowSet(L"\t\t\t", info.NormalWindows); } buf.clear(); std::format_to(std::back_inserter(buf), L"User is using Aero Peek: {}", m_PeekActive); MessagePrint(spdlog::level::off, buf); buf.clear(); std::format_to(std::back_inserter(buf), L"User is using Task View: {}", m_TaskViewActive); MessagePrint(spdlog::level::off, buf); if (m_CurrentStartMonitor != nullptr) { buf.clear(); std::format_to(std::back_inserter(buf), L"Start menu is opened: true [monitor {}]", static_cast<void *>(m_CurrentStartMonitor)); MessagePrint(spdlog::level::off, buf); } else { MessagePrint(spdlog::level::off, L"Start menu is opened: false"); } if (m_CurrentSearchMonitor != nullptr) { buf.clear(); std::format_to(std::back_inserter(buf), L"Search is opened: true [monitor {}]", static_cast<void *>(m_CurrentSearchMonitor)); MessagePrint(spdlog::level::off, buf); } else { MessagePrint(spdlog::level::off, L"Search is opened: false"); } buf.clear(); std::format_to(std::back_inserter(buf), L"Current foreground window: {}", DumpWindow(m_ForegroundWindow)); MessagePrint(spdlog::level::off, buf); buf.clear(); std::format_to(std::back_inserter(buf), L"Worker handles attribute refresh requests from hooks: {}", !m_disableAttributeRefreshReply); MessagePrint(spdlog::level::off, buf); buf.clear(); std::format_to(std::back_inserter(buf), L"Battery saver is active: {}", m_PowerSaver); MessagePrint(spdlog::level::off, buf); MessagePrint(spdlog::level::off, L"Taskbars currently using normal appearance:"); DumpWindowSet(L"\t\t", m_NormalTaskbars, false); MessagePrint(spdlog::level::off, L"===== End TaskbarAttributeWorker state dump ====="); } void TaskbarAttributeWorker::ResetState(bool manual) { if (!m_ResettingState) { MessagePrint(spdlog::level::debug, L"Resetting worker state"); m_ResettingState = true; m_ResetStateReentered = false; auto guard = wil::scope_exit([this] { m_ResettingState = false; m_ResetStateReentered = false; }); // Clear state m_PowerSaver = false; m_PeekActive = false; m_TaskViewActive = false; m_CurrentStartMonitor = nullptr; m_CurrentSearchMonitor = nullptr; m_ForegroundWindow = Window::NullWindow; m_Taskbars.clear(); m_NormalTaskbars.clear(); m_TaskbarService = nullptr; // Keep old hooks alive while we rehook to avoid DLL unload. auto oldHooks = std::move(m_Hooks); m_Hooks.clear(); if (const Window main_taskbar = Window::Find(TASKBAR)) { const auto pid = main_taskbar.process_id(); if (!manual) { if (m_LastExplorerPid != 0 && pid != m_LastExplorerPid) { const auto now = std::chrono::steady_clock::now(); if (now < m_LastExplorerRestart + std::chrono::seconds(30)) [[unlikely]] { Localization::ShowLocalizedMessageBox(IDS_EXPLORER_RESTARTED_TOO_MUCH, MB_OK | MB_ICONWARNING | MB_SETFOREGROUND, hinstance()).join(); ExitProcess(1); } m_LastExplorerRestart = now; } } m_LastExplorerPid = pid; InsertTaskbar(GetTaskbarMonitor(main_taskbar), main_taskbar); // if we're on 22621, with a XAML Island present, but no WorkerW window, we're on the new taskbar // 22000 doesn't have the new taskbar. On 22621 when you have the old taskbar, there is a WorkerW window. // Because ExplorerPatcher unfortunately exists and can restore the Windows 10 taskbar, // check for a XAML Island always to make sure we're not on the 10 taskbar. if (win32::IsAtLeastBuild(22621) && main_taskbar.find_child(L"Windows.UI.Composition.DesktopWindowContentBridge") && !main_taskbar.find_child(L"WorkerW")) { const HRESULT hr = m_InjectExplorerTAP(pid, IID_PPV_ARGS(m_TaskbarService.put())); if (hr == HRESULT_FROM_WIN32(ERROR_PRODUCT_VERSION)) { Localization::ShowLocalizedMessageBox(IDS_RESTART_REQUIRED, MB_OK | MB_ICONWARNING | MB_SETFOREGROUND, hinstance()).join(); ExitProcess(1); } else { HresultVerify(hr, spdlog::level::critical, L"Failed to initialize XAML Diagnostics."); } HresultVerify(m_TaskbarService->RestoreAllTaskbarsToDefaultWhenProcessDies(GetCurrentProcessId()), spdlog::level::warn, L"Couldn't configure TAP to restore taskbar appearance once " APP_NAME L" dies."); } } for (const Window secondtaskbar : Window::FindEnum(SECONDARY_TASKBAR)) { InsertTaskbar(GetTaskbarMonitor(secondtaskbar), secondtaskbar); } // drop the old hooks. oldHooks.clear(); CreateSearchManager(); // This might race but it's not an issue because // it'll race on a single thread and only ends up // doing something twice. SYSTEM_POWER_STATUS powerStatus; if (GetSystemPowerStatus(&powerStatus)) { m_PowerSaver = powerStatus.SystemStatusFlag; } else { LastErrorHandle(spdlog::level::warn, L"Failed to verify system power status"); } // TODO: check if aero peek is active if (const auto hookWnd = Window::Find(TTBHOOK_TASKVIEWMONITOR, TTBHOOK_TASKVIEWMONITOR); hookWnd && m_IsTaskViewOpenedMessage) { m_TaskViewActive = hookWnd.send_message(*m_IsTaskViewOpenedMessage); } m_ForegroundWindow = Window::ForegroundWindow(); if (IsStartMenuOpened()) { m_CurrentStartMonitor = GetStartMenuMonitor(); } if (IsSearchOpened()) { m_CurrentStartMonitor = GetSearchMonitor(); } for (const Window window : Window::FindEnum()) { InsertWindow(window, false); } if (!m_ResetStateReentered) { // Apply the calculated effects RefreshAllAttributes(); } else { // we got re-entrancy, all this might not even be valid anymore, try it again. guard.reset(); ResetState(manual); } } else { MessagePrint(spdlog::level::debug, L"ResetState re-entrancy detected"); m_ResetStateReentered = true; } } TaskbarAttributeWorker::~TaskbarAttributeWorker() noexcept(false) { m_disableAttributeRefreshReply = true; UnregisterSearchCallbacks(); ReturnToStock(); }
40,192
C++
.cpp
1,182
31.026227
206
0.742856
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,852
messagewindow.cpp
TranslucentTB_TranslucentTB/TranslucentTB/windows/messagewindow.cpp
#include "messagewindow.hpp" #include <member_thunk/member_thunk.hpp> #include "../../ProgramLog/error/win32.hpp" #include "../../ProgramLog/error/std.hpp" void MessageWindow::init(Util::null_terminated_wstring_view windowName, DWORD style, DWORD extended_style, Window parent) { m_WindowHandle = Window::Create(extended_style, *m_WindowClass, windowName, style, 0, 0, 0, 0, parent); if (!m_WindowHandle) { LastErrorHandle(spdlog::level::critical, L"Failed to create message window!"); } const auto proc = m_ProcPage.make_thunk<WNDPROC>(this, &MessageWindow::MessageHandler); m_ProcPage.mark_executable(); set_long_ptr<spdlog::level::critical>(GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(proc)); } MessageWindow::MessageWindow(WindowClass &classRef, Util::null_terminated_wstring_view windowName, DWORD style, DWORD extended_style, Window parent, const wchar_t *iconResource) : m_WindowClass(&classRef, false), m_IconResource(iconResource), m_ProcPage(member_thunk::allocate_page()) { init(windowName, style, extended_style, parent); } MessageWindow::MessageWindow(Util::null_terminated_wstring_view className, Util::null_terminated_wstring_view windowName, HINSTANCE hInstance, DWORD style, DWORD extended_style, Window parent, const wchar_t *iconResource) : m_WindowClass(new WindowClass(MakeWindowClass(className, hInstance, iconResource)), true), m_IconResource(iconResource), m_ProcPage(member_thunk::allocate_page()) { init(windowName, style, extended_style, parent); } MessageWindow::~MessageWindow() { if (!DestroyWindow(m_WindowHandle)) { LastErrorHandle(spdlog::level::info, L"Failed to destroy message window!"); } }
1,654
C++
.cpp
36
44.138889
223
0.780261
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,853
window.cpp
TranslucentTB_TranslucentTB/TranslucentTB/windows/window.cpp
#include "window.hpp" #include <ShObjIdl.h> #include <wil/com.h> #include <wil/resource.h> #include "undoc/winternl.hpp" #include "win32.hpp" std::optional<std::filesystem::path> Window::TryGetNtImageName(DWORD pid) { static const auto NtQuerySystemInformation = []() noexcept -> PFN_NT_QUERY_SYSTEM_INFORMATION { const auto ntdll = GetModuleHandle(L"ntdll.dll"); return ntdll ? reinterpret_cast<PFN_NT_QUERY_SYSTEM_INFORMATION>(GetProcAddress(ntdll, "NtQuerySystemInformation")) : nullptr; }(); if (NtQuerySystemInformation) { SYSTEM_PROCESS_ID_INFORMATION pidInfo = { #pragma warning(suppress: 4312) // intentional, the structure uses a pointer to store PIDs .ProcessId = reinterpret_cast<PVOID>(pid) }; if (NtQuerySystemInformation(static_cast<SYSTEM_INFORMATION_CLASS>(SystemProcessIdInformation), &pidInfo, sizeof(pidInfo), nullptr) == STATUS_INFO_LENGTH_MISMATCH_UNDOC) { std::wstring buf; buf.resize_and_overwrite(pidInfo.ImageName.MaximumLength / 2, [&pidInfo](wchar_t* data, std::size_t count) { pidInfo.ImageName.Buffer = data; pidInfo.ImageName.MaximumLength = static_cast<USHORT>(count + 1) * 2; // hopefully the process didn't die midway through this lol if (NT_SUCCESS(NtQuerySystemInformation(static_cast<SYSTEM_INFORMATION_CLASS>(SystemProcessIdInformation), &pidInfo, sizeof(pidInfo), nullptr))) { return pidInfo.ImageName.Length / 2; } else { return 0; } }); if (!buf.empty()) { return std::move(buf); } } } return std::nullopt; } std::optional<std::wstring> Window::title() const { SetLastError(NO_ERROR); const int titleSize = GetWindowTextLength(m_WindowHandle); if (!titleSize) { if (const DWORD lastErr = GetLastError(); lastErr != NO_ERROR) { HresultHandle(HRESULT_FROM_WIN32(lastErr), spdlog::level::info, L"Getting size of title of a window failed."); return std::nullopt; } else { return std::make_optional<std::wstring>(); } } // We're assuming that a window won't change title between the previous call and this. // But it very well could. It'll either be smaller and waste a bit of RAM, or have // GetWindowText trim it. std::wstring windowTitle; bool failed = false; windowTitle.resize_and_overwrite(titleSize, [hwnd = m_WindowHandle, &failed](wchar_t* data, std::size_t count) { SetLastError(NO_ERROR); const int copiedChars = GetWindowText(hwnd, data, static_cast<int>(count) + 1); if (!copiedChars) { if (const DWORD lastErr = GetLastError(); lastErr != NO_ERROR) { HresultHandle(HRESULT_FROM_WIN32(lastErr), spdlog::level::info, L"Getting title of a window failed."); failed = true; } } return copiedChars; }); if (!failed) { return { std::move(windowTitle) }; } else { return std::nullopt; } } std::optional<std::wstring> Window::classname() const { std::wstring className; bool failed = false; // https://learn.microsoft.com/en-us/windows/win32/api/winuser/ns-winuser-wndclassw // The maximum length for lpszClassName is 256. className.resize_and_overwrite(256, [hwnd = m_WindowHandle, &failed](wchar_t* data, std::size_t count) { const int length = GetClassName(hwnd, data, static_cast<int>(count) + 1); if (!length) { LastErrorHandle(spdlog::level::info, L"Getting class name of a window failed."); failed = true; } return length; }); if (!failed) { return { std::move(className) }; } else { return std::nullopt; } } std::optional<std::filesystem::path> Window::file() const { const auto pid = process_id(); if (auto imageName = TryGetNtImageName(pid)) { return { std::move(*imageName) }; } else { const wil::unique_process_handle processHandle(OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid)); if (!processHandle) { LastErrorHandle(spdlog::level::info, L"Getting process handle of a window failed."); return std::nullopt; } auto [loc, hr] = win32::GetProcessFileName(processHandle.get()); if (FAILED(hr)) { HresultHandle(hr, spdlog::level::info, L"Getting file name of a window failed."); return std::nullopt; } return { std::move(loc) }; } } std::optional<bool> Window::on_current_desktop() const { static const auto desktop_manager = []() -> wil::com_ptr<IVirtualDesktopManager> { try { return wil::CoCreateInstance<IVirtualDesktopManager>(CLSID_VirtualDesktopManager); } catch (const wil::ResultException &err) { ResultExceptionHandle(err, spdlog::level::warn, L"Failed to create virtual desktop manager"); return nullptr; } }(); if (desktop_manager) { BOOL on_current_desktop; if (const HRESULT hr = desktop_manager->IsWindowOnCurrentVirtualDesktop(m_WindowHandle, &on_current_desktop); SUCCEEDED(hr)) { return on_current_desktop; } else { HresultHandle(hr, spdlog::level::info, L"Verifying if a window is on the current virtual desktop failed."); } } return std::nullopt; } bool Window::is_user_window() const { if (valid() && visible() && !cloaked() && ancestor(GA_ROOT) == m_WindowHandle && get(GW_OWNER) == Window::NullWindow) { const auto ex_style = get_long_ptr(GWL_EXSTYLE); if (ex_style && (*ex_style & WS_EX_APPWINDOW || !(*ex_style & (WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE))) && prop(L"ITaskList_Deleted") == nullptr) { // done last because it's expensive due to being reentrant return on_current_desktop().value_or(false); } } return false; }
5,442
C++
.cpp
180
27.372222
171
0.715213
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,854
windowclass.cpp
TranslucentTB_TranslucentTB/TranslucentTB/windows/windowclass.cpp
#include "windowclass.hpp" #include <CommCtrl.h> #include <WinBase.h> #include <winerror.h> #include "../../ProgramLog/error/win32.hpp" #include "window.hpp" void WindowClass::LoadIcons(const wchar_t *iconResource) { if (iconResource) { HresultVerify(LoadIconMetric(m_hInstance, iconResource, LIM_LARGE, m_hIcon.put()), spdlog::level::warn, L"Failed to load large window class icon."); HresultVerify(LoadIconMetric(m_hInstance, iconResource, LIM_SMALL, m_hIconSmall.put()), spdlog::level::warn, L"Failed to load small window class icon."); } else { m_hIcon.reset(); m_hIconSmall.reset(); } } void WindowClass::Unregister() { if (!UnregisterClass(atom(), m_hInstance)) { LastErrorHandle(spdlog::level::info, L"Failed to unregister window class."); } } WindowClass::WindowClass(WNDPROC procedure, Util::null_terminated_wstring_view className, const wchar_t *iconResource, HINSTANCE hInstance, unsigned int style, HBRUSH brush, HCURSOR cursor) : m_hInstance(hInstance) { LoadIcons(iconResource); const WNDCLASSEX classStruct = { .cbSize = sizeof(classStruct), .style = style, .lpfnWndProc = procedure, .hInstance = hInstance, .hIcon = m_hIcon.get(), .hCursor = cursor, .hbrBackground = brush, .lpszClassName = className.c_str(), .hIconSm = m_hIconSmall.get() }; m_Atom = RegisterClassEx(&classStruct); if (!m_Atom) { LastErrorHandle(spdlog::level::critical, L"Failed to register window class!"); } } void WindowClass::ChangeIcon(Window window, const wchar_t *iconResource) { const auto guard = m_Lock.lock_exclusive(); LoadIcons(iconResource); SetLastError(NO_ERROR); if (!SetClassLongPtr(window, GCLP_HICON, reinterpret_cast<LONG_PTR>(m_hIcon.get()))) { LastErrorVerify(spdlog::level::warn, L"Failed to change large window class icon."); } SetLastError(NO_ERROR); if (!SetClassLongPtr(window, GCLP_HICONSM, reinterpret_cast<LONG_PTR>(m_hIconSmall.get()))) { LastErrorVerify(spdlog::level::warn, L"Failed to change small window class icon."); } }
2,014
C++
.cpp
62
30.354839
191
0.748842
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,855
StyleResources.cpp
TranslucentTB_TranslucentTB/Xaml/StyleResources.cpp
#include "pch.h" #include <algorithm> #include "StyleResources.h" #if __has_include("StyleResources.g.cpp") #include "StyleResources.g.cpp" #endif namespace winrt::TranslucentTB::Xaml::implementation { wux::DependencyProperty StyleResources::m_ResourcesProperty = wux::DependencyProperty::RegisterAttached( L"Resources", xaml_typename<wux::ResourceDictionary>(), xaml_typename<TranslucentTB::Xaml::StyleResources>(), wux::PropertyMetadata(nullptr, OnResourcesChanged)); void StyleResources::OnResourcesChanged(const wux::DependencyObject &d, const wux::DependencyPropertyChangedEventArgs &e) { if (const auto source = d.try_as<wux::FrameworkElement>()) { wfc::IVector<wux::ResourceDictionary> mergedDicts(nullptr); if (const auto resources = source.Resources()) { mergedDicts = resources.MergedDictionaries(); } if (mergedDicts) { const auto begin = mergedDicts.begin(); const auto end = mergedDicts.end(); const auto it = std::ranges::find_if(begin, end, [](const wux::ResourceDictionary &resDict) { return resDict.try_as<IStyleResourceDictionary>() != nullptr; }); if (it != end) { mergedDicts.RemoveAt(static_cast<uint32_t>(it - begin)); } if (const auto newVal = e.NewValue().try_as<wux::ResourceDictionary>()) { const auto clonedRes = winrt::make<StyleResourceDictionary>(); CloneResourceDictionary(newVal, clonedRes); mergedDicts.Append(clonedRes); } } } } wux::ResourceDictionary StyleResources::CloneResourceDictionary(const wux::ResourceDictionary &resource, const wux::ResourceDictionary &destination) { if (!resource) { return nullptr; } if (const auto source = resource.Source()) { destination.Source(source); } else { if (const auto themeDicts = resource.ThemeDictionaries()) { for (const auto theme : themeDicts) { if (const auto themeResource = theme.Value().try_as<wux::ResourceDictionary>()) { wux::ResourceDictionary themeDict; CloneResourceDictionary(themeResource, themeDict); destination.ThemeDictionaries().Insert(theme.Key(), themeDict); } else { destination.ThemeDictionaries().Insert(theme.Key(), theme.Value()); } } } if (const auto mergeDicts = resource.MergedDictionaries()) { for (const auto mergedResource : mergeDicts) { wux::ResourceDictionary mergedDict; CloneResourceDictionary(mergedResource, mergedDict); destination.MergedDictionaries().Append(mergedDict); } } for (const auto item : resource) { destination.Insert(item.Key(), item.Value()); } } return destination; } }
2,689
C++
.cpp
89
26.044944
149
0.713789
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,856
FunctionalConverters.cpp
TranslucentTB_TranslucentTB/Xaml/FunctionalConverters.cpp
#include "pch.h" #include "FunctionalConverters.h" #if __has_include("FunctionalConverters.g.cpp") #include "FunctionalConverters.g.cpp" #endif namespace winrt::TranslucentTB::Xaml::implementation { bool FunctionalConverters::InvertedBool(bool value) noexcept { return !value; } wux::Visibility FunctionalConverters::InvertedBoolToVisibility(bool value) noexcept { return value ? wux::Visibility::Collapsed : wux::Visibility::Visible; } bool FunctionalConverters::IsSameLogSinkState(txmp::LogSinkState a, txmp::LogSinkState b) noexcept { return a == b; } bool FunctionalConverters::IsDifferentLogSinkState(txmp::LogSinkState a, txmp::LogSinkState b) noexcept { return a != b; } }
705
C++
.cpp
24
27.333333
104
0.792899
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,857
App.cpp
TranslucentTB_TranslucentTB/Xaml/App.cpp
#include "pch.h" #include "App.h" #if __has_include("App.g.cpp") #include "App.g.cpp" #endif namespace winrt::TranslucentTB::Xaml::implementation { App::App() { // empty } }
181
C++
.cpp
12
13.5
52
0.694611
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,858
RelativeAncestor.cpp
TranslucentTB_TranslucentTB/Xaml/RelativeAncestor.cpp
#include "pch.h" #include "RelativeAncestor.h" #if __has_include("RelativeAncestor.g.cpp") #include "RelativeAncestor.g.cpp" #endif namespace winrt::TranslucentTB::Xaml::implementation { thread_local std::vector<std::pair<weak_ref<wux::FrameworkElement>, event_token>> RelativeAncestor::s_UnloadedTokenList; thread_local std::vector<std::pair<weak_ref<wux::FrameworkElement>, event_token>> RelativeAncestor::s_LoadedTokenList; wux::DependencyProperty RelativeAncestor::m_AncestorProperty = wux::DependencyProperty::RegisterAttached( L"Ancestor", xaml_typename<wf::IInspectable>(), xaml_typename<TranslucentTB::Xaml::RelativeAncestor>(), nullptr); wux::DependencyProperty RelativeAncestor::m_AncestorTypeProperty = wux::DependencyProperty::RegisterAttached( L"AncestorType", xaml_typename<wux::Interop::TypeName>(), xaml_typename<TranslucentTB::Xaml::RelativeAncestor>(), wux::PropertyMetadata(nullptr, OnAncestorTypeChanged)); void RelativeAncestor::OnAncestorTypeChanged(const wux::DependencyObject &d, const wux::DependencyPropertyChangedEventArgs &e) { if (const auto fe = d.try_as<wux::FrameworkElement>()) { RemoveHandlers(fe); if (e.NewValue()) { event_token unloadedToken = fe.Unloaded(OnFrameworkElementUnloaded); try { s_UnloadedTokenList.push_back({ fe, unloadedToken }); } catch (...) { // just in case something happens fe.Unloaded(unloadedToken); throw; } event_token loadedToken = fe.Loaded(OnFrameworkElementLoaded); try { s_LoadedTokenList.push_back({ fe, loadedToken }); } catch (...) { // just in case something happens fe.Unloaded(unloadedToken); fe.Loaded(loadedToken); throw; } if (fe.Parent()) { OnFrameworkElementLoaded(fe, nullptr); } } } } void RelativeAncestor::OnFrameworkElementLoaded(const wf::IInspectable &sender, const wux::RoutedEventArgs &) { if (const auto fe = sender.try_as<wux::FrameworkElement>()) { SetAncestor(fe, FindAscendant(fe, GetAncestorType(fe))); } } void RelativeAncestor::OnFrameworkElementUnloaded(const wf::IInspectable &sender, const wux::RoutedEventArgs &) { if (const auto fe = sender.try_as<wux::FrameworkElement>()) { // avoid an XAML leak SetAncestor(fe, nullptr); } } wux::DependencyObject RelativeAncestor::FindAscendant(const wux::DependencyObject &element, const wux::Interop::TypeName &type) { const auto parent = wux::Media::VisualTreeHelper::GetParent(element); // IsAssignableFrom doesn't exist here but then the WCT also just checks the concrete type, so whatever. if (!parent || get_class_name(parent) == type.Name) { return parent; } else { // haha recursive function go brrr return FindAscendant(parent, type); } } void RelativeAncestor::RemoveHandlers(const wux::FrameworkElement &element) noexcept { for (auto it = s_UnloadedTokenList.begin(); it != s_UnloadedTokenList.end();) { if (const auto fe = it->first.get()) { if (fe == element) { fe.Unloaded(it->second); it = s_UnloadedTokenList.erase(it); } else { ++it; } } else { it = s_UnloadedTokenList.erase(it); } } for (auto it = s_LoadedTokenList.begin(); it != s_LoadedTokenList.end();) { if (const auto fe = it->first.get()) { if (fe == element) { fe.Loaded(it->second); it = s_LoadedTokenList.erase(it); } else { ++it; } } else { it = s_LoadedTokenList.erase(it); } } } }
3,580
C++
.cpp
129
23.813953
128
0.698981
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,859
FluentColorPalette.cpp
TranslucentTB_TranslucentTB/Xaml/Models/FluentColorPalette.cpp
#include "pch.h" #include <tuple> #include "FluentColorPalette.h" #if __has_include("Models/FluentColorPalette.g.cpp") #include "Models/FluentColorPalette.g.cpp" #endif namespace winrt::TranslucentTB::Xaml::Models::implementation { uint32_t FluentColorPalette::ColorCount() noexcept { return std::tuple_size_v<decltype(COLOR_CHART)>; } uint32_t FluentColorPalette::ShadeCount() noexcept { return std::tuple_size_v<decltype(COLOR_CHART)::value_type>; } Windows::UI::Color FluentColorPalette::GetColor(uint32_t colorIndex, uint32_t shadeIndex) { return COLOR_CHART.at(colorIndex).at(shadeIndex); } }
617
C++
.cpp
21
27.47619
90
0.782095
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,860
Action.cpp
TranslucentTB_TranslucentTB/Xaml/Models/Action.cpp
#include "pch.h" #include "Action.h" #if __has_include("Models/Action.g.cpp") #include "Models/Action.g.cpp" #endif namespace winrt::TranslucentTB::Xaml::Models::implementation { void Action::ForwardClick(const IInspectable &sender, const wux::RoutedEventArgs &args) { m_click(sender, args); } }
303
C++
.cpp
12
23.666667
88
0.761246
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,861
WelcomePage.cpp
TranslucentTB_TranslucentTB/Xaml/Pages/WelcomePage.cpp
#include "pch.h" #include "WelcomePage.h" #if __has_include("Pages/WelcomePage.g.cpp") #include "Pages/WelcomePage.g.cpp" #endif namespace winrt::TranslucentTB::Xaml::Pages::implementation { wf::Rect WelcomePage::ExpandedDragRegion() { const auto titleRegion = TitleRegion(); return { 0.0f, 0.0f, static_cast<float>(titleRegion.ActualWidth()), static_cast<float>(titleRegion.ActualHeight()) }; } void WelcomePage::OpenLiberapayLink(const IInspectable &, const wux::RoutedEventArgs &) { m_LiberapayOpenRequestedHandler(); } void WelcomePage::OpenDiscordLink(const IInspectable &, const wux::RoutedEventArgs &) { m_DiscordJoinRequestedHandler(); } void WelcomePage::EditConfigFile(const IInspectable &, const wux::RoutedEventArgs &) { m_ConfigEditRequestedHandler(); } void WelcomePage::AgreeButtonClicked(const IInspectable &, const wux::RoutedEventArgs &) { m_LicenseApprovedHandler(); Close(); } void WelcomePage::DisagreeButtonClicked(const IInspectable &, const wux::RoutedEventArgs &) { Close(); } }
1,059
C++
.cpp
39
24.74359
92
0.765054
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,862
FramelessPage.cpp
TranslucentTB_TranslucentTB/Xaml/Pages/FramelessPage.cpp
#include "pch.h" #include <ranges> #include "FramelessPage.h" #if __has_include("Pages/FramelessPage.g.cpp") #include "Pages/FramelessPage.g.cpp" #endif namespace winrt::TranslucentTB::Xaml::Pages::implementation { void FramelessPage::InitializeComponent() { m_SystemMenuChangedToken = m_SystemMenuContent.VectorChanged({ this, &FramelessPage::SystemMenuChanged }); FramelessPageT::InitializeComponent(); } bool FramelessPage::CanMove() noexcept { return CanMoveCore(); } bool FramelessPage::CanMoveCore() noexcept { return true; } void FramelessPage::ShowSystemMenu(const wf::Point &position) { if (CanMove()) { SystemMenu().ShowAt(*this, position); } } void FramelessPage::HideSystemMenu() { SystemMenu().Hide(); } wf::Rect FramelessPage::DragRegion() { if (!ExpandIntoTitlebar()) { return { 0.0f, 0.0f, static_cast<float>(ActualWidth() - (CloseButton().ActualWidth() + CustomTitlebarControls().ActualWidth())), static_cast<float>(Titlebar().ActualHeight()) }; } else { return ExpandedDragRegion(); } } wf::Rect FramelessPage::ExpandedDragRegion() { throw hresult_not_implemented(L"A page that uses ExpandIntoTitlebar should override ExpandedDragRegion."); } wf::Rect FramelessPage::TitlebarButtonsRegion() { const bool closable = IsClosable(); if (!ExpandIntoTitlebar() || (closable == false && m_TitlebarContent.Size() == 0)) { return { 0.0f, 0.0f, 0.0f, 0.0f }; } else { double height = 0.0f; double width = 0.0f; if (closable) { const auto closeButton = CloseButton(); if (height == 0.0f) { height = closeButton.ActualHeight(); } width += closeButton.ActualWidth(); } for (const auto button : m_TitlebarContent) { if (height == 0.0f) { height = button.ActualHeight(); } width += button.ActualWidth(); } return { static_cast<float>(ActualWidth() - width), 0.0f, static_cast<float>(width), static_cast<float>(height) }; } } bool FramelessPage::RequestClose() { return Close(); } bool FramelessPage::Close() { if (IsClosable()) { m_ClosedHandler(); return true; } else { return false; } } void FramelessPage::CloseClicked(const IInspectable &, const wux::RoutedEventArgs &) { Close(); } void FramelessPage::SystemMenuOpening(const IInspectable &, const IInspectable &) { if (m_NeedsSystemMenuRefresh) { const auto menuItems = SystemMenu().Items(); // remove everything but the Close menu item const auto closeItem = CloseMenuItem(); menuItems.Clear(); menuItems.Append(closeItem); bool needsMergeStyle = false; if (m_SystemMenuContent.Size() > 0) { menuItems.InsertAt(0, wuxc::MenuFlyoutSeparator()); for (const auto newItem : m_SystemMenuContent | std::views::reverse) { if (newItem.try_as<wuxc::ToggleMenuFlyoutItem>()) { needsMergeStyle = true; } menuItems.InsertAt(0, newItem); } } closeItem.Style(needsMergeStyle ? LookupStyle(winrt::box_value(L"MergeIconsMenuFlyoutItem")) : nullptr); m_NeedsSystemMenuRefresh = false; } } FramelessPage::~FramelessPage() { m_SystemMenuContent.VectorChanged(m_SystemMenuChangedToken); } void FramelessPage::SystemMenuChanged(const wfc::IObservableVector<wuxc::MenuFlyoutItemBase> &, const wfc::IVectorChangedEventArgs &) { m_NeedsSystemMenuRefresh = true; } wux::Style FramelessPage::LookupStyle(const IInspectable &key) { return wux::Application::Current().Resources().TryLookup(key).try_as<wux::Style>(); } }
3,604
C++
.cpp
147
21.129252
134
0.704956
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,863
TrayFlyoutPage.cpp
TranslucentTB_TranslucentTB/Xaml/Pages/TrayFlyoutPage.cpp
#include "pch.h" #include "TrayFlyoutPage.h" #if __has_include("Pages/TrayFlyoutPage.g.cpp") #include "Pages/TrayFlyoutPage.g.cpp" #endif #include "arch.h" #include <winbase.h> #include "config/taskbarappearance.hpp" namespace winrt::TranslucentTB::Xaml::Pages::implementation { TrayFlyoutPage::TrayFlyoutPage(bool hasPackageIdentity) : m_BlurSupported(TaskbarAppearance::IsBlurSupported()), m_HasPackageIdentity(hasPackageIdentity) { SYSTEM_POWER_STATUS powerStatus; if (GetSystemPowerStatus(&powerStatus)) { // 128 means no system battery. assume everything else // means the system has one. m_SystemHasBattery = powerStatus.BatteryFlag != 128; } else { m_SystemHasBattery = true; // assume the system has a battery } } void TrayFlyoutPage::SetTaskbarSettings(const txmp::TaskbarState &state, const txmp::TaskbarAppearance &appearance) { if (const auto submenu = GetSubMenuForState(state)) { bool enabled = true; if (const auto optAppearance = appearance.try_as<txmp::OptionalTaskbarAppearance>()) { enabled = optAppearance.Enabled(); } for (const auto item : submenu.Items()) { const auto tag = item.Tag(); if (const auto radioItem = item.try_as<muxc::RadioMenuFlyoutItem>()) { if (tag.try_as<txmp::AccentState>() == appearance.Accent()) { radioItem.IsChecked(true); } radioItem.IsEnabled(enabled); } else if (const auto toggleItem = item.try_as<wuxc::ToggleMenuFlyoutItem>()) { const auto stringTag = tag.try_as<hstring>(); if (stringTag == L"Enabled") { toggleItem.IsChecked(enabled); } else if (stringTag == L"ShowPeek") { toggleItem.IsChecked(appearance.ShowPeek()); toggleItem.IsEnabled(enabled); } else if (stringTag == L"ShowLine") { toggleItem.IsChecked(appearance.ShowLine()); toggleItem.IsEnabled(enabled); } } else if (tag.try_as<hstring>() == L"Color") { item.IsEnabled(enabled && appearance.Accent() != txmp::AccentState::Normal); } } } } void TrayFlyoutPage::SetLogLevel(const txmp::LogLevel &level) { for (const auto item : LogLevelSubMenu().Items()) { if (const auto radioItem = item.try_as<muxc::RadioMenuFlyoutItem>()) { if (radioItem.Tag().try_as<txmp::LogLevel>() == level) { radioItem.IsChecked(true); } } } } void TrayFlyoutPage::SetDisableSavingSettings(const bool &disabled) { DisableSavingSettings().IsChecked(disabled); } void TrayFlyoutPage::SetStartupState(const wf::IReference<Windows::ApplicationModel::StartupTaskState> &state) { const auto startup = StartupState(); if (state) { const auto stateUnbox = state.Value(); using enum Windows::ApplicationModel::StartupTaskState; startup.IsChecked(stateUnbox == Enabled || stateUnbox == EnabledByPolicy); startup.IsEnabled(stateUnbox == Disabled || stateUnbox == DisabledByUser || stateUnbox == Enabled); } else { startup.IsChecked(false); startup.IsEnabled(false); } } void TrayFlyoutPage::AppearanceClicked(const IInspectable &sender, const wux::RoutedEventArgs &) { if (const auto item = sender.try_as<wuxc::MenuFlyoutItemBase>()) { if (const auto submenu = GetItemParent(item)) { if (const auto tag = submenu.Tag().try_as<txmp::TaskbarState>()) { m_TaskbarSettingsChangedDelegate(*tag, BuildAppearanceFromSubMenu(submenu)); } } } } void TrayFlyoutPage::ColorClicked(const IInspectable &sender, const wux::RoutedEventArgs &) { if (const auto item = sender.try_as<wuxc::MenuFlyoutItemBase>()) { if (const auto submenu = GetItemParent(item)) { if (const auto tag = submenu.Tag().try_as<txmp::TaskbarState>()) { m_ColorRequestedDelegate(*tag); } } } } void TrayFlyoutPage::OpenLogFileClicked(const IInspectable &, const wux::RoutedEventArgs &) { m_OpenLogFileRequestedDelegate(); } void TrayFlyoutPage::LogLevelClicked(const IInspectable &sender, const wux::RoutedEventArgs &) { if (const auto item = sender.try_as<wuxc::MenuFlyoutItemBase>()) { if (const auto tag = item.Tag().try_as<txmp::LogLevel>()) { m_LogLevelChangedDelegate(*tag); } } } void TrayFlyoutPage::DumpDynamicStateClicked(const IInspectable &, const wux::RoutedEventArgs &) { m_DumpDynamicStateRequestedDelegate(); } void TrayFlyoutPage::EditSettingsClicked(const IInspectable &, const wux::RoutedEventArgs &) { m_EditSettingsRequestedDelegate(); } void TrayFlyoutPage::ResetSettingsClicked(const IInspectable &, const wux::RoutedEventArgs &) { m_ResetSettingsRequestedDelegate(); } void TrayFlyoutPage::DisableSavingSettingsClicked(const IInspectable &, const wux::RoutedEventArgs &) { m_DisableSavingSettingsChangedDelegate(DisableSavingSettings().IsChecked()); } void TrayFlyoutPage::HideTrayClicked(const IInspectable &, const wux::RoutedEventArgs &) { m_HideTrayRequestedDelegate(); } void TrayFlyoutPage::ResetDynamicStateClicked(const IInspectable &, const wux::RoutedEventArgs&) { m_ResetDynamicStateRequestedDelegate(); } void TrayFlyoutPage::CompactThunkHeapClicked(const IInspectable &, const wux::RoutedEventArgs &) { m_CompactThunkHeapRequestedDelegate(); } void TrayFlyoutPage::StartupClicked(const IInspectable &, const wux::RoutedEventArgs &) { m_StartupStateChangedDelegate(); } void TrayFlyoutPage::TipsAndTricksClicked(const IInspectable &, const wux::RoutedEventArgs &) { m_TipsAndTricksRequestedDelegate(); } void TrayFlyoutPage::AboutClicked(const IInspectable &, const wux::RoutedEventArgs &) { m_AboutRequestedDelegate(); } void TrayFlyoutPage::ExitClicked(const IInspectable &, const wux::RoutedEventArgs &) { m_ExitRequestedDelegate(); } wuxc::MenuFlyoutSubItem TrayFlyoutPage::GetContainingSubMenu(const wuxc::MenuFlyoutItemBase &item, const wuxc::MenuFlyoutSubItem &subItem) { for (const auto menuItem : subItem.Items()) { if (menuItem == item) { return subItem; } else if (const auto subSubMenu = menuItem.try_as<wuxc::MenuFlyoutSubItem>()) { if (const auto parent = GetContainingSubMenu(item, subSubMenu)) { return parent; } } } return nullptr; } wuxc::MenuFlyoutSubItem TrayFlyoutPage::GetItemParent(const wuxc::MenuFlyoutItemBase &item) { for (const auto menuItem : ContextMenu().Items()) { if (const auto subMenu = menuItem.try_as<wuxc::MenuFlyoutSubItem>()) { if (const auto parent = GetContainingSubMenu(item, subMenu)) { return parent; } } } return nullptr; } txmp::TaskbarAppearance TrayFlyoutPage::BuildAppearanceFromSubMenu(const wuxc::MenuFlyoutSubItem &menu) { std::optional<bool> enabled; for (const auto item : menu.Items()) { if (item.Tag().try_as<hstring>() == L"Enabled") { if (const auto toggleButton = item.try_as<wuxc::ToggleMenuFlyoutItem>()) { enabled = toggleButton.IsChecked(); } } } txmp::TaskbarAppearance appearance(nullptr); if (enabled) { txmp::OptionalTaskbarAppearance optAppearance; optAppearance.Enabled(*enabled); appearance = std::move(optAppearance); } else { appearance = { }; } for (const auto item : menu.Items()) { const auto tag = item.Tag(); if (const auto radioItem = item.try_as<muxc::RadioMenuFlyoutItem>()) { if (radioItem.IsChecked()) { if (const auto accent = tag.try_as<txmp::AccentState>()) { appearance.Accent(*accent); } } } else if (const auto toggleItem = item.try_as<wuxc::ToggleMenuFlyoutItem>()) { if (tag.try_as<hstring>() == L"ShowPeek") { appearance.ShowPeek(toggleItem.IsChecked()); } else if (tag.try_as<hstring>() == L"ShowLine") { appearance.ShowLine(toggleItem.IsChecked()); } } } return appearance; } wuxc::MenuFlyoutSubItem TrayFlyoutPage::GetSubMenuForState(txmp::TaskbarState state) { for (const wuxc::MenuFlyoutItemBase item : ContextMenu().Items()) { if (const auto submenu = item.try_as<wuxc::MenuFlyoutSubItem>()) { const auto tag = submenu.Tag().try_as<txmp::TaskbarState>(); if (tag == state) { return submenu; } } } return nullptr; } }
8,256
C++
.cpp
287
25.090592
139
0.715996
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,864
ColorPickerPage.cpp
TranslucentTB_TranslucentTB/Xaml/Pages/ColorPickerPage.cpp
#include "pch.h" #include "ColorPickerPage.h" #if __has_include("Pages/ColorPickerPage.g.cpp") #include "Pages/ColorPickerPage.g.cpp" #endif #include "appinfo.hpp" namespace winrt::TranslucentTB::Xaml::Pages::implementation { ColorPickerPage::ColorPickerPage(txmp::TaskbarState state, Windows::UI::Color originalColor) : m_State(state), m_OriginalColor(originalColor) { } void ColorPickerPage::InitializeComponent() { ComponentConnectorT::InitializeComponent(); const auto resourceLoader = Windows::ApplicationModel::Resources::ResourceLoader::GetForUIContext(UIContext()); Title(winrt::format(L"{} - {} - " APP_NAME, resourceLoader.GetString(GetResourceForState(m_State)), resourceLoader.GetString(L"/TranslucentTB.Xaml/Resources/TrayFlyoutPage_AccentColor/Text"))); } bool ColorPickerPage::CanMoveCore() noexcept { return !m_DialogOpened; } bool ColorPickerPage::Close() { if (m_DialogOpened) { return false; } if (Picker().Color() != m_OriginalColor) { OpenConfirmDialog(); return false; } else { return base_type::Close(); } } void ColorPickerPage::OkButtonClicked(const IInspectable &, const wux::RoutedEventArgs &) { m_ChangesCommittedHandler(Picker().Color()); base_type::Close(); } void ColorPickerPage::CancelButtonClicked(const IInspectable &, const wux::RoutedEventArgs &) { base_type::Close(); } void ColorPickerPage::DialogOpened(const IInspectable &, const wuxc::ContentDialogOpenedEventArgs &) noexcept { m_DialogOpened = true; } void ColorPickerPage::DialogClosed(const IInspectable &, const wuxc::ContentDialogClosedEventArgs &) noexcept { m_DialogOpened = false; } Windows::UI::Color ColorPickerPage::OriginalColor() noexcept { return m_OriginalColor; } void ColorPickerPage::PickerColorChanged(const muxc::ColorPicker &, const muxc::ColorChangedEventArgs &args) { m_ColorChangedHandler(args.NewColor()); } std::wstring_view ColorPickerPage::GetResourceForState(txmp::TaskbarState state) { switch (state) { using enum txmp::TaskbarState; case Desktop: return L"/TranslucentTB.Xaml/Resources/TrayFlyoutPage_Desktop/Text"; case VisibleWindow: return L"/TranslucentTB.Xaml/Resources/TrayFlyoutPage_VisibleWindow/Text"; case MaximisedWindow: return L"/TranslucentTB.Xaml/Resources/TrayFlyoutPage_MaximizedWindow/Text"; case StartOpened: return L"/TranslucentTB.Xaml/Resources/TrayFlyoutPage_StartOpened/Text"; case SearchOpened: return L"/TranslucentTB.Xaml/Resources/TrayFlyoutPage_SearchOpened/Text"; case TaskViewOpened: return L"/TranslucentTB.Xaml/Resources/TrayFlyoutPage_TaskViewOpened/Text"; case BatterySaver: return L"/TranslucentTB.Xaml/Resources/TrayFlyoutPage_BatterySaver/Text"; default: throw std::invalid_argument("Unknown taskbar state"); } } fire_and_forget ColorPickerPage::OpenConfirmDialog() { const auto self_weak = get_weak(); const auto result = co_await ConfirmCloseDialog().ShowAsync(); if (const auto self = self_weak.get()) { if (result != wuxc::ContentDialogResult::None) { if (result == wuxc::ContentDialogResult::Primary) { self->m_ChangesCommittedHandler(self->Picker().Color()); } self->base_type::Close(); } } } }
3,238
C++
.cpp
95
31.231579
142
0.7696
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,865
FocusBorderColorSpectrum.cpp
TranslucentTB_TranslucentTB/Xaml/Controls/FocusBorderColorSpectrum.cpp
#include "pch.h" #include "FocusBorderColorSpectrum.h" #if __has_include("Controls/FocusBorderColorSpectrum.g.cpp") #include "Controls/FocusBorderColorSpectrum.g.cpp" #endif namespace winrt::TranslucentTB::Xaml::Controls::implementation { void FocusBorderColorSpectrum::OnApplyTemplate() { m_SizingGridSizeChangedRevoker.revoke(); m_FocusBorder = GetTemplateChild(L"FocusBorder").try_as<wuxc::Border>(); const auto sizingGrid = GetTemplateChild(L"SizingGrid").try_as<wux::FrameworkElement>(); base_type::OnApplyTemplate(); if (m_FocusBorder && sizingGrid) { UpdateFocusBorder(sizingGrid); m_SizingGridSizeChangedRevoker = sizingGrid.SizeChanged(winrt::auto_revoke, { get_weak(), &FocusBorderColorSpectrum::OnSizingGridSizeChanged }); } } void FocusBorderColorSpectrum::OnSizingGridSizeChanged(const IInspectable &sender, const wux::SizeChangedEventArgs &) { if (const auto sizingGrid = sender.try_as<wux::FrameworkElement>()) { UpdateFocusBorder(sizingGrid); } } void FocusBorderColorSpectrum::UpdateFocusBorder(const wux::FrameworkElement &sizingGrid) { m_FocusBorder.Width(sizingGrid.Width()); m_FocusBorder.Height(sizingGrid.Height()); } }
1,193
C++
.cpp
32
34.71875
147
0.791847
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,866
UniformGrid.cpp
TranslucentTB_TranslucentTB/Xaml/Controls/UniformGrid.cpp
#include "pch.h" #include <numeric> #include <ranges> #include "UniformGrid.h" #if __has_include("Controls/UniformGrid.g.cpp") #include "Controls/UniformGrid.g.cpp" #endif #include "win32.hpp" namespace winrt::TranslucentTB::Xaml::Controls::implementation { wux::DependencyProperty UniformGrid::m_AutoLayoutProperty = wux::DependencyProperty::RegisterAttached( L"AutoLayout", xaml_typename<wf::IReference<bool>>(), xaml_typename<class_type>(), nullptr); void UniformGrid::OnDependencyPropertyChanged(const IInspectable &sender, const wux::DependencyPropertyChangedEventArgs &) { if (const auto that = sender.try_as<UniformGrid>()) { that->InvalidateMeasure(); } } wf::Size UniformGrid::MeasureOverride(const wf::Size &availableSize) { const auto visible = Children() | std::views::transform([](const wux::UIElement& element) noexcept { return element.try_as<wux::FrameworkElement>(); }) | std::views::filter([](const wux::FrameworkElement& element) { return element && element.Visibility() != wux::Visibility::Collapsed; }) | std::ranges::to<std::vector>(); const auto [rows, columns] = GetDimensions(visible, Rows(), Columns(), FirstColumn()); // Now that we know size, setup automatic rows/columns // to utilize Grid for UniformGrid behavior. // We also interleave any specified rows/columns with fixed sizes. SetupRowDefinitions(static_cast<uint32_t>(rows)); SetupColumnDefinitions(static_cast<uint32_t>(columns)); m_TakenSpots.clear(); m_TakenSpots.resize(rows * columns, false); m_SpotsHeight = rows; m_SpotsWidth = columns; // Figure out which children we should automatically layout and where available openings are. for (const auto &child : visible) { const auto autoLayout = GetAutoLayout(child); if (!autoLayout) { // If an element needs to be forced in the 0, 0 position, // they should manually set UniformGrid.AutoLayout to False for that element. const auto row = composable_base::GetRow(child); const auto col = composable_base::GetColumn(child); if (row == 0 && col == 0) { SetAutoLayout(child, true); } else { SetAutoLayout(child, false); FillSpots(true, row, col, composable_base::GetColumnSpan(child), composable_base::GetRowSpan(child)); } } } // Setup available size with our known dimensions now. // UniformGrid expands size based on largest singular item. const float columnSpacingSize = static_cast<float>(ColumnSpacing()) * (columns - 1); const float rowSpacingSize = static_cast<float>(RowSpacing()) * (rows - 1); const wf::Size childSize = { (availableSize.Width - columnSpacingSize) / columns, (availableSize.Height - rowSpacingSize) / rows }; float maxWidth = 0.0; float maxHeight = 0.0; // Set Grid Row/Col for every child with autolayout = true // Backwards with FlowDirection auto freespots = GetFreeSpots(FirstColumn(), Orientation() == wuxc::Orientation::Vertical); auto freespot = freespots.begin(); for (const auto &child : visible) { // Set location if we're in charge const auto autoLayout = GetAutoLayout(child); if (autoLayout && autoLayout.Value()) { if (freespot != freespots.end()) { const auto [row, column] = *freespot; composable_base::SetRow(child, row); composable_base::SetColumn(child, column); const auto rowspan = composable_base::GetRowSpan(child); const auto colspan = composable_base::GetColumnSpan(child); if (rowspan > 1 || colspan > 1) { // TODO: Need to tie this into iterator FillSpots(true, row, column, colspan, rowspan); } ++freespot; } else { // We've run out of spots as the developer has // most likely given us a fixed size and too many elements // Therefore, tell this element it has no size and move on. child.Measure(wf::Size { }); m_Overflow.push_back(child); continue; } } else { const auto row = composable_base::GetRow(child); const auto column = composable_base::GetColumn(child); if (row < 0 || row >= rows || column < 0 || column >= columns) { // A child is specifying a location, but that location is outside // of our grid space, so we should hide it instead. child.Measure(wf::Size { }); m_Overflow.push_back(child); continue; } } // Get measurement for max child child.Measure(childSize); const auto desiredSize = child.DesiredSize(); maxWidth = std::max(desiredSize.Width, maxWidth); maxHeight = std::max(desiredSize.Height, maxHeight); } // Return our desired size based on the largest child we found, our dimensions, and spacing. wf::Size desiredSize = { (maxWidth * columns) + columnSpacingSize, (maxHeight * rows) + rowSpacingSize }; // Required to perform regular grid measurement, but ignore result. base_type::MeasureOverride(desiredSize); return desiredSize; } wf::Size UniformGrid::ArrangeOverride(const wf::Size &finalSize) { // Have grid to the bulk of our heavy lifting. const auto size = base_type::ArrangeOverride(finalSize); // Make sure all overflown elements have no size. for (const auto &child : m_Overflow) { child.Arrange(wf::Rect { }); } m_Overflow.clear(); // Reset for next time. return size; } std::tuple<int, int> UniformGrid::GetDimensions(const std::vector<wux::FrameworkElement> &visible, int rows, int cols, int firstColumn) { // If a dimension isn't specified, we need to figure out the other one (or both). if (rows == 0 || cols == 0) { // Calculate the size & area of all objects in the grid to know how much space we need. const auto sizes = visible | std::views::transform([](const wux::FrameworkElement &item) { return composable_base::GetRowSpan(item) * composable_base::GetColumnSpan(item); }); auto count = std::max(1, std::accumulate(sizes.begin(), sizes.end(), 0)); if (rows == 0) { if (cols > 0) { // Bound check const auto first = (firstColumn >= cols || firstColumn < 0) ? 0 : firstColumn; // If we have columns but no rows, calculate rows based on column offset and number of children. rows = (count + first + (cols - 1)) / cols; return { rows, cols }; } else { // Otherwise, determine square layout if both are zero. const auto size = static_cast<int>(std::ceil(std::sqrt(count))); // Figure out if firstColumn is in bounds const auto first = (firstColumn >= size || firstColumn < 0) ? 0 : firstColumn; rows = static_cast<int>(std::ceil(std::sqrt(count + first))); return { rows, rows }; } } else if (cols == 0) { // If we have rows and no columns, then calculate columns needed based on rows cols = (count + (rows - 1)) / rows; // Now that we know a rough size of our shape, see if the FirstColumn effects that: const auto first = (firstColumn >= cols || firstColumn < 0) ? 0 : firstColumn; cols = (count + first + (rows - 1)) / rows; } } return { rows, cols }; } void UniformGrid::SetupRowDefinitions(uint32_t rows) { const auto definitions = RowDefinitions(); // Mark initial definitions so we don't erase them. for (const auto &rd : definitions) { if (!GetAutoLayout(rd)) { SetAutoLayout(rd, false); } } // Remove non-autolayout rows we've added and then add them in the right spots. if (rows != definitions.Size()) { for (int32_t r = definitions.Size() - 1; r >= 0; r--) { const auto layout = GetAutoLayout(definitions.GetAt(r)); if (layout && layout.Value()) { definitions.RemoveAt(r); } } for (uint32_t r = definitions.Size(); r < rows; r++) { wux::Controls::RowDefinition rd; SetAutoLayout(rd, true); definitions.InsertAt(r, rd); } } } void UniformGrid::SetupColumnDefinitions(uint32_t columns) { const auto definitions = ColumnDefinitions(); // Mark initial definitions so we don't erase them. for (const auto &cd : definitions) { if (!GetAutoLayout(cd)) { SetAutoLayout(cd, false); } } // Remove non-autolayout rows we've added and then add them in the right spots. if (columns != definitions.Size()) { for (int32_t c = definitions.Size() - 1; c >= 0; c--) { const auto layout = GetAutoLayout(definitions.GetAt(c)); if (layout && layout.Value()) { definitions.RemoveAt(c); } } for (uint32_t c = definitions.Size(); c < columns; c++) { wux::Controls::ColumnDefinition cd; SetAutoLayout(cd, true); definitions.InsertAt(c, cd); } } } bool UniformGrid::GetSpot(int i, int j) { return m_TakenSpots[(i * m_SpotsWidth) + j]; } void UniformGrid::FillSpots(bool value, int row, int column, int width, int height) { RECT rect1 = { 0, 0, m_SpotsWidth, m_SpotsHeight }, rect2 = { column, row, column + width, row + height }; // Precompute bounds to skip branching in main loop RECT bounds { }; IntersectRect(&bounds, &rect1, &rect2); for (int i = bounds.top; i < bounds.bottom; i++) { for (int j = bounds.left; j < bounds.right; j++) { m_TakenSpots[(i * m_SpotsWidth) + j] = value; } } } std::experimental::generator<std::tuple<int, int>> UniformGrid::GetFreeSpots(int firstColumn, bool topDown) { // Provides the next spot in the boolean array with a 'false' value. if (topDown) { // Layout spots from Top-Bottom, Left-Right (right-left handled automatically by Grid with Flow-Direction). // Effectively transpose the Grid Layout. for (int c = 0; c < m_SpotsWidth; c++) { int start = (c == 0 && firstColumn > 0 && firstColumn < m_SpotsHeight) ? firstColumn : 0; for (int r = start; r < m_SpotsHeight; r++) { if (!GetSpot(r, c)) { co_yield { r, c }; } } } } else { // Layout spots as normal from Left-Right. // (right-left handled automatically by Grid with Flow-Direction // during its layout, internal model is always left-right). for (int r = 0; r < m_SpotsHeight; r++) { int start = (r == 0 && firstColumn > 0 && firstColumn < m_SpotsWidth) ? firstColumn : 0; for (int c = start; c < m_SpotsWidth; c++) { if (!GetSpot(r, c)) { co_yield { r, c }; } } } } } }
10,326
C++
.cpp
302
30.086093
139
0.671146
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,867
ConstrainedBox.cpp
TranslucentTB_TranslucentTB/Xaml/Controls/ConstrainedBox.cpp
#include "pch.h" #include <cmath> #include "ConstrainedBox.h" #if __has_include("Controls/ConstrainedBox.g.cpp") #include "Controls/ConstrainedBox.g.cpp" #endif namespace winrt::TranslucentTB::Xaml::Controls::implementation { void ConstrainedBox::OnDependencyPropertyChanged(const IInspectable &sender, const wux::DependencyPropertyChangedEventArgs &) { if (const auto that = sender.try_as<ConstrainedBox>()) { that->InvalidateMeasure(); } } wf::Size ConstrainedBox::MeasureOverride(wf::Size availableSize) { m_OriginalSize = availableSize; CalculateConstrainedSize(availableSize); m_LastMeasuredSize = availableSize; // Call base_type::MeasureOverride so any child elements know what room there is to work with. // Don't return this though. An image that hasn't loaded yet for example will request very little space. base_type::MeasureOverride(m_LastMeasuredSize); return m_LastMeasuredSize; } wf::Size ConstrainedBox::ArrangeOverride(wf::Size finalSize) { // Even though we requested in measure to be a specific size, that doesn't mean our parent // panel respected that request. Grid for instance can by default Stretch and if you don't // set Horizontal/VerticalAlignment on the control it won't constrain as we expect. // We could also be in a StackPanel/ScrollViewer where it wants to provide as much space as possible. // However, if we always re-calculate even if we are provided the proper finalSize, this can trigger // multiple arrange passes and cause a rounding error in layout. Therefore, we only want to // re-calculate if we think we will have a significant impact. if (std::abs(finalSize.Width - m_LastMeasuredSize.Width) > CALCULATION_TOLERANCE || std::abs(finalSize.Height - m_LastMeasuredSize.Height) > CALCULATION_TOLERANCE) { // Check if we can re-use our measure calculation if we're given effectively // the same size as we had in the measure step. if (std::abs(finalSize.Width - m_OriginalSize.Width) <= CALCULATION_TOLERANCE && std::abs(finalSize.Height - m_OriginalSize.Height) <= CALCULATION_TOLERANCE) { finalSize = m_LastMeasuredSize; } else { CalculateConstrainedSize(finalSize); // Copy again so if Arrange is re-triggered we won't re-re-calculate. m_LastMeasuredSize = finalSize; } } return base_type::ArrangeOverride(finalSize); } bool ConstrainedBox::IsPositiveRealNumber(double value) noexcept { return std::isfinite(value) && value > 0.0; } void ConstrainedBox::ApplyMultiple(int32_t multiple, float &value) noexcept { if (multiple == 0) { value = 0.0f; } else if (multiple > 1) { value = std::floor(value / multiple) * multiple; } } void ConstrainedBox::CalculateConstrainedSize(wf::Size &availableSize) { // We check for Infinity, in the case we have no constraint from parent // we'll request the child's measurements first, so we can use that as // a starting point to constrain it's dimensions based on the criteria // set in our properties. bool hasWidth = IsPositiveRealNumber(availableSize.Width); bool hasHeight = IsPositiveRealNumber(availableSize.Height); if (!hasWidth && !hasHeight) { // We have infinite space, like a ScrollViewer with both scrolling directions // Ask child how big they want to be first. availableSize = base_type::MeasureOverride(availableSize); hasWidth = IsPositiveRealNumber(availableSize.Width); hasHeight = IsPositiveRealNumber(availableSize.Height); if (!hasWidth && !hasHeight) { // At this point we have no way to determine a constraint, the Panel won't do anything // This should be rare? We don't really have a way to provide a warning here. return; } } // Apply Multiples // --------------- // These floor the Width/Height values to the nearest multiple of the property (if set). // For instance you may have a responsive 4x4 repeated checkerboard pattern for transparency and // want to snap to the nearest interval of 4 so the checkerboard is consistency across the layout. if (hasWidth) { ApplyMultiple(MultipleX(), availableSize.Width); } if (hasHeight) { ApplyMultiple(MultipleY(), availableSize.Height); } } }
4,226
C++
.cpp
105
37.066667
126
0.749513
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,868
SwitchPresenter.cpp
TranslucentTB_TranslucentTB/Xaml/Controls/SwitchPresenter.cpp
#include "pch.h" #include "Controls/SwitchPresenter.h" #if __has_include("Controls/SwitchPresenter.g.cpp") #include "Controls/SwitchPresenter.g.cpp" #endif namespace winrt::TranslucentTB::Xaml::Controls::implementation { void SwitchPresenter::OnValueChanged(const IInspectable &sender, const wux::DependencyPropertyChangedEventArgs &) { if (const auto that = sender.try_as<SwitchPresenter>()) { that->EvaluateCases(); } } SwitchPresenter::SwitchPresenter() { m_LoadedToken = Loaded({ get_weak(), &SwitchPresenter::OnLoaded }); m_CasesChangedToken = m_Cases.VectorChanged({ get_weak(), &SwitchPresenter::OnCasesChanged }); } void SwitchPresenter::OnApplyTemplate() { base_type::OnApplyTemplate(); EvaluateCases(); } SwitchPresenter::~SwitchPresenter() { m_Cases.VectorChanged(m_CasesChangedToken); Loaded(m_LoadedToken); } void SwitchPresenter::EvaluateCases() { const auto current = CurrentCase(); if (m_Cases.Size() == 0) { // If we have no cases, then we can't match anything. if (current) { // Only bother clearing our actual content if we had something before. Content(nullptr); SetValue(CurrentCaseProperty(), nullptr); } return; } else if (current) { const auto currentValue = current.Value(); if (currentValue && currentValue == Value()) { // If the current case we're on already matches our current value, // then we don't have any work to do. return; } } Case xdefault(nullptr); Case newcase(nullptr); const auto value = Value(); for (const auto &xcase : m_Cases) { if (xcase.IsDefault()) { // If there are multiple default cases provided, this will override and just grab the last one, the developer will have to fix this in their XAML. We call this out in the case comments. xdefault = xcase; continue; } if (CompareValues(value, xcase.Value())) { newcase = xcase; break; } } if (!newcase && xdefault) { // Inject default if we found one without matching anything newcase = xdefault; } // Only bother changing things around if we actually have a new case. if (newcase != current) { // If we don't have any cases or default, setting these to null is what we want to be blank again. Content(newcase ? newcase.Content() : nullptr); SetValue(CurrentCaseProperty(), newcase); } } void SwitchPresenter::OnCasesChanged(const wfc::IObservableVector<Case> &, const wfc::IVectorChangedEventArgs &) { EvaluateCases(); } void SwitchPresenter::OnLoaded(const IInspectable &, const wux::RoutedEventArgs &) { EvaluateCases(); } bool SwitchPresenter::CompareValues(const IInspectable &compare, const IInspectable &value) { if (compare == value) { return true; } if (!compare || !value) { return false; } return ValueToString(compare) == ValueToString(value); } hstring SwitchPresenter::ValueToString(const IInspectable &value) { if (const auto str = value.try_as<hstring>()) { return *str; } else { return wux::Markup::XamlBindingHelper::ConvertValue(xaml_typename<hstring>(), value).as<hstring>(); } } }
3,153
C++
.cpp
115
24.217391
189
0.714806
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,869
ActionList.cpp
TranslucentTB_TranslucentTB/Xaml/Controls/ActionList.cpp
#include "pch.h" #include "Controls/ActionList.h" #if __has_include("Controls/ActionList.g.cpp") #include "Controls/ActionList.g.cpp" #endif #include "../Models/Action.h" namespace winrt::TranslucentTB::Xaml::Controls::implementation { void ActionList::ForwardActionKey(const IInspectable &sender, const wux::Input::KeyRoutedEventArgs &args) { using enum Windows::System::VirtualKey; if (args.Key() == Enter || args.Key() == Space) { ForwardAction(sender, args); args.Handled(true); } } void ActionList::ForwardAction(const IInspectable &sender, const wux::RoutedEventArgs &args) { sender.as<wux::FrameworkElement>().Tag().as<Models::implementation::Action>()->ForwardClick(sender, args); } }
720
C++
.cpp
22
30.5
108
0.748918
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,870
colorpickerrendering.cpp
TranslucentTB_TranslucentTB/Xaml/Controls/colorpickerrendering.cpp
#include "pch.h" #include "colorpickerrendering.hpp" void FillChannelBitmap(uint8_t *bgraPixelData, int32_t width, int32_t height, double renderScale, wuxc::Orientation orientation, txmp::ColorRepresentation colorRepresentation, txmp::ColorChannel channel, Util::HsvColor baseHsvColor, Util::Color checkerColor, bool isAlphaMaxForced, bool isSaturationValueMaxForced) { // Maximize alpha channel value if (isAlphaMaxForced && channel != txmp::ColorChannel::Alpha) { baseHsvColor.A = 1.0; } // Convert HSV to RGB once const Util::Color baseRgbColor = colorRepresentation == txmp::ColorRepresentation::Rgba ? Util::Color::FromHSV(baseHsvColor) : Util::Color { 0xFF, 0xFF, 0xFF, 0xFF }; // Colors::White // Maximize Saturation and Value channels when in HSVA mode if (isSaturationValueMaxForced && colorRepresentation == txmp::ColorRepresentation::Hsva && channel != txmp::ColorChannel::Alpha) { switch (channel) { case txmp::ColorChannel::Channel1: baseHsvColor.S = 1.0; baseHsvColor.V = 1.0; break; case txmp::ColorChannel::Channel2: baseHsvColor.V = 1.0; break; case txmp::ColorChannel::Channel3: baseHsvColor.S = 1.0; break; } } // Determine the numerical increment of the color steps within the channel double channelStep; if (colorRepresentation == txmp::ColorRepresentation::Hsva) { if (channel == txmp::ColorChannel::Channel1) { channelStep = 360.0; } else { channelStep = 1.0; } } else { channelStep = 255.0; } // Create the color channel gradient if (orientation == wuxc::Orientation::Horizontal) { channelStep /= width; for (int32_t x = 0; x < width; x++) { const auto rgbColor = GetChannelPixelColor(x * channelStep, channel, colorRepresentation, baseHsvColor, baseRgbColor); for (int32_t y = 0; y < height; y++) { const auto finalColor = !isAlphaMaxForced ? CompositeColors(GetCheckerPixelColor(x, y, checkerColor, renderScale), rgbColor) : rgbColor; // 4 bytes per pixel const int32_t pixelDataIndex = 4 * (x + (width * y)); bgraPixelData[pixelDataIndex + 0] = finalColor.B; bgraPixelData[pixelDataIndex + 1] = finalColor.G; bgraPixelData[pixelDataIndex + 2] = finalColor.R; bgraPixelData[pixelDataIndex + 3] = finalColor.A; } } } else { channelStep /= height; for (int32_t y = 0; y < height; ++y) { // The lowest channel value should be at the 'bottom' of the bitmap const auto rgbColor = GetChannelPixelColor((height - 1 - y) * channelStep, channel, colorRepresentation, baseHsvColor, baseRgbColor); const int32_t pixelRowIndex = width * y; for (int32_t x = 0; x < width; ++x) { const auto finalColor = !isAlphaMaxForced ? CompositeColors(GetCheckerPixelColor(x, y, checkerColor, renderScale), rgbColor) : rgbColor; // 4 bytes per pixel const int32_t pixelDataIndex = 4 * (x + pixelRowIndex); bgraPixelData[pixelDataIndex + 0] = finalColor.B; bgraPixelData[pixelDataIndex + 1] = finalColor.G; bgraPixelData[pixelDataIndex + 2] = finalColor.R; bgraPixelData[pixelDataIndex + 3] = finalColor.A; } } } } Util::Color GetChannelPixelColor(double channelValue, txmp::ColorChannel channel, txmp::ColorRepresentation representation, Util::HsvColor baseHsvColor, Util::Color baseRgbColor) { Util::Color newRgbColor = { 0xFF, 0xFF, 0xFF, 0xFF }; switch (channel) { case txmp::ColorChannel::Channel1: if (representation == txmp::ColorRepresentation::Hsva) { // Sweep hue baseHsvColor.H = std::clamp(channelValue, 0.0, 360.0); newRgbColor = Util::Color::FromHSV(baseHsvColor); } else { // Sweep red baseRgbColor.R = static_cast<uint8_t>(std::clamp(channelValue, 0.0, 255.0)); newRgbColor = baseRgbColor; } break; case txmp::ColorChannel::Channel2: if (representation == txmp::ColorRepresentation::Hsva) { // Sweep saturation baseHsvColor.S = std::clamp(channelValue, 0.0, 1.0); newRgbColor = Util::Color::FromHSV(baseHsvColor); } else { // Sweep green baseRgbColor.G = static_cast<uint8_t>(std::clamp(channelValue, 0.0, 255.0)); newRgbColor = baseRgbColor; } break; case txmp::ColorChannel::Channel3: if (representation == txmp::ColorRepresentation::Hsva) { // Sweep value baseHsvColor.V = std::clamp(channelValue, 0.0, 1.0); newRgbColor = Util::Color::FromHSV(baseHsvColor); } else { // Sweep blue baseRgbColor.B = static_cast<uint8_t>(std::clamp(channelValue, 0.0, 255.0)); newRgbColor = baseRgbColor; } break; case txmp::ColorChannel::Alpha: if (representation == txmp::ColorRepresentation::Hsva) { // Sweep alpha baseHsvColor.A = std::clamp(channelValue, 0.0, 1.0); newRgbColor = Util::Color::FromHSV(baseHsvColor); } else { // Sweep alpha baseRgbColor.A = static_cast<uint8_t>(std::clamp(channelValue, 0.0, 255.0)); newRgbColor = baseRgbColor; } break; } return newRgbColor.Premultiply(); }
4,944
C++
.cpp
151
29.443709
314
0.717761
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,871
ColorPickerSlider.cpp
TranslucentTB_TranslucentTB/Xaml/Controls/ColorPickerSlider.cpp
#include "pch.h" #include "ColorPickerSlider.h" #if __has_include("Controls/ColorPickerSlider.g.cpp") #include "Controls/ColorPickerSlider.g.cpp" #endif #include "../Converters/ContrastBrushConverter.h" #include "util/color.hpp" #include "colorpickerrendering.hpp" namespace winrt::TranslucentTB::Xaml::Controls::implementation { void ColorPickerSlider::OnDependencyPropertyChanged(const IInspectable &sender, const wux::DependencyPropertyChangedEventArgs &args) { if (const auto slider = sender.try_as<ColorPickerSlider>()) { const auto prop = args.Property(); if (prop == ColorProperty()) { slider->HsvColor(Util::Color(slider->Color()).ToHSV()); } else if (prop == CheckerBackgroundColorProperty()) { slider->UpdateBackground(slider->HsvColor()); } else if (slider->IsAutoUpdatingEnabled()) { slider->UpdateColors(); } } } ColorPickerSlider::ColorPickerSlider() { m_LoadedToken = Loaded({ get_weak(), &ColorPickerSlider::OnLoaded }); m_UnloadedToken = Unloaded({ get_weak(), &ColorPickerSlider::OnUnloaded }); m_OrientationPropertyChangedToken.value = RegisterPropertyChangedCallback(composable_base::OrientationProperty(), OnOrientationPropertyChanged); DefaultStyleKey(box_value(name_of<class_type>())); } ColorPickerSlider::~ColorPickerSlider() { UnregisterPropertyChangedCallback(composable_base::OrientationProperty(), m_OrientationPropertyChangedToken.value); Unloaded(m_UnloadedToken); Loaded(m_LoadedToken); } void ColorPickerSlider::UpdateColors() { auto hsvColor = HsvColor(); // Calculate and set the background UpdateBackground(hsvColor); // Calculate and set the foreground ensuring contrast with the background Windows::UI::Color rgbColor = Util::Color::FromHSV(hsvColor); Windows::UI::Color selectedRgbColor; const double sliderPercent = Value() / (Maximum() - Minimum()); const auto colorChannel = ColorChannel(); const auto alphaMaxForced = IsAlphaMaxForced(); if (ColorRepresentation() == txmp::ColorRepresentation::Hsva) { if (alphaMaxForced && colorChannel != txmp::ColorChannel::Alpha) { hsvColor.A = 1.0; } const auto saturationMaxForced = IsSaturationValueMaxForced(); switch (colorChannel) { case txmp::ColorChannel::Channel1: hsvColor.H = std::clamp(sliderPercent * 360.0, 0.0, 360.0); if (saturationMaxForced) { hsvColor.S = hsvColor.V = 1.0; } break; case txmp::ColorChannel::Channel2: hsvColor.S = std::clamp(sliderPercent * 1.0, 0.0, 1.0); if (saturationMaxForced) { hsvColor.V = 1.0; } break; case txmp::ColorChannel::Channel3: hsvColor.V = std::clamp(sliderPercent * 1.0, 0.0, 1.0); if (saturationMaxForced) { hsvColor.S = 1.0; } break; } selectedRgbColor = Util::Color::FromHSV(hsvColor); } else { if (alphaMaxForced && colorChannel != txmp::ColorChannel::Alpha) { rgbColor.A = 255; } const auto channelValue = static_cast<uint8_t>(std::clamp(sliderPercent * 255.0, 0.0, 255.0)); switch (colorChannel) { case txmp::ColorChannel::Channel1: rgbColor.R = channelValue; break; case txmp::ColorChannel::Channel2: rgbColor.G = channelValue; break; case txmp::ColorChannel::Channel3: rgbColor.B = channelValue; break; } selectedRgbColor = rgbColor; } wux::VisualStateManager::GoToState(*this, Util::Color(selectedRgbColor).IsDarkColor() ? L"LightSliderThumb" : L"DarkSliderThumb", false); } void ColorPickerSlider::OnApplyTemplate() { m_HorizontalTrackRect = GetTemplateChild(L"HorizontalTrackRect").try_as<wux::Shapes::Rectangle>(); m_VerticalTrackRect = GetTemplateChild(L"VerticalTrackRect").try_as<wux::Shapes::Rectangle>(); base_type::OnApplyTemplate(); UpdateVisualState(); UpdateBackground(HsvColor()); } wf::Size ColorPickerSlider::MeasureOverride(const wf::Size &availableSize) { if (availableSize != oldSize) { measuredSize = base_type::MeasureOverride(availableSize); oldSize = availableSize; } return measuredSize; } void ColorPickerSlider::OnOrientationPropertyChanged(const wux::DependencyObject &sender, const wux::DependencyProperty &) { if (const auto that = sender.try_as<ColorPickerSlider>()) { that->UpdateVisualState(); that->UpdateBackground(that->HsvColor()); } } void ColorPickerSlider::OnLoaded(const IInspectable &, const wux::RoutedEventArgs &) { if (const auto root = XamlRoot()) { m_XamlRootChangedRevoker = root.Changed(winrt::auto_revoke, m_XamlRootChangedHandler); OnXamlRootChanged(nullptr, nullptr); } } void ColorPickerSlider::OnUnloaded(const IInspectable &, const wux::RoutedEventArgs &) { m_XamlRootChangedRevoker.revoke(); } void ColorPickerSlider::OnXamlRootChanged(const wux::XamlRoot &, const wux::XamlRootChangedEventArgs &) { UpdateBackground(HsvColor()); } void ColorPickerSlider::UpdateVisualState() { wux::VisualStateManager::GoToState(*this, Orientation() == wuxc::Orientation::Vertical ? L"VerticalColorSlider" : L"HorizontalColorSlider", false); } void ColorPickerSlider::UpdateBackground(txmp::HsvColor color) { const auto orientation = Orientation(); if (const auto rect = orientation == wuxc::Orientation::Vertical ? m_VerticalTrackRect : m_HorizontalTrackRect) { auto width = static_cast<int32_t>(rect.ActualWidth()); auto height = static_cast<int32_t>(rect.ActualHeight()); if (width == 0 || height == 0) { if (cachedSize != wf::Size { }) { width = static_cast<int32_t>(cachedSize.Width); height = static_cast<int32_t>(cachedSize.Height); } } else { cachedSize = { static_cast<float>(width), static_cast<float>(height) }; } if (width != 0 && height != 0) { double renderScale = 1.0; if (const auto root = rect.XamlRoot()) { renderScale = root.RasterizationScale(); width = static_cast<int32_t>(width * renderScale); height = static_cast<int32_t>(height * renderScale); } RenderBackground(rect, color, orientation, width, height, renderScale); } } } fire_and_forget ColorPickerSlider::RenderBackground(weak_ref<wux::Shapes::Rectangle> rect_weak, txmp::HsvColor color, wuxc::Orientation orientation, int32_t width, int32_t height, double renderScale) { // retrieve properties before going to the background const auto representation = ColorRepresentation(); const auto channel = ColorChannel(); const auto background = CheckerBackgroundColor(); const auto alphaMaxForced = IsAlphaMaxForced(); const auto saturationMaxForced = IsSaturationValueMaxForced(); // create the bitmap on this thread wux::Media::Imaging::WriteableBitmap bitmap { width, height }; const auto buffer = bitmap.PixelBuffer(); const auto bgraPixelData = buffer.data(); // move to background const auto dispatcher = Windows::System::DispatcherQueue::GetForCurrentThread(); co_await resume_background(); FillChannelBitmap(bgraPixelData, width, height, renderScale, orientation, representation, channel, color, background, alphaMaxForced, saturationMaxForced); if (const auto rect = rect_weak.get()) { // return to main thread co_await wil::resume_foreground(dispatcher); bitmap.Invalidate(); wux::Media::ImageBrush brush; brush.ImageSource(bitmap); brush.Stretch(wux::Media::Stretch::Fill); rect.Fill(brush); } } }
7,419
C++
.cpp
214
31.074766
200
0.732664
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,872
ChromeButton.cpp
TranslucentTB_TranslucentTB/Xaml/Controls/ChromeButton.cpp
#include "pch.h" #include "ChromeButton.h" #if __has_include("Controls/ChromeButton.g.cpp") #include "Controls/ChromeButton.g.cpp" #endif namespace winrt::TranslucentTB::Xaml::Controls::implementation { ChromeButton::ChromeButton() { DefaultStyleKey(box_value(name_of<class_type>())); } void ChromeButton::OnToggle() { if (IsTogglable()) { base_type::OnToggle(); } } }
389
C++
.cpp
19
18.421053
62
0.73842
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,873
ColorPicker.cpp
TranslucentTB_TranslucentTB/Xaml/Controls/ColorPicker.cpp
#include "pch.h" #include "ColorPicker.h" #if __has_include("Controls/ColorPicker.g.cpp") #include "Controls/ColorPicker.g.cpp" #endif #include "colorpickerrendering.hpp" #include "util/color.hpp" #include "util/string_macros.hpp" namespace winrt::TranslucentTB::Xaml::Controls::implementation { wux::DependencyProperty ColorPicker::m_InvertedCheckerboardProperty = wux::DependencyProperty::RegisterAttached( L"InvertedCheckerboard", xaml_typename<bool>(), xaml_typename<TranslucentTB::Xaml::Controls::ColorPicker>(), wux::PropertyMetadata(box_value(false))); void ColorPicker::OnDependencyPropertyChanged(const IInspectable &sender, const wux::DependencyPropertyChangedEventArgs &args) { if (const auto that = sender.try_as<ColorPicker>()) { const auto property = args.Property(); if (property == CustomPaletteProperty()) { that->UpdateCustomPalette(); } else if (property == IsColorPaletteVisibleProperty()) { that->UpdateVisualState(false); } else if (property == CheckerBackgroundColorProperty()) { that->OnXamlRootChanged(nullptr, nullptr); } } } ColorPicker::ColorPicker() { m_DecimalFormatter.FractionDigits(0); SetValue(CustomPaletteColorsProperty(), single_threaded_observable_vector<Windows::UI::Color>()); m_LoadedToken = Loaded({ get_weak(), &ColorPicker::OnLoaded }); m_UnloadedToken = Unloaded({ get_weak(), &ColorPicker::OnUnloaded }); DefaultStyleKey(box_value(name_of<class_type>())); m_ColorPropertyChangedToken.value = RegisterPropertyChangedCallback(composable_base::ColorProperty(), OnColorPropertyChanged); UpdateCustomPalette(); static constexpr int COLOR_UPDATE_INTERVAL = 30; m_DispatcherQueueTimer.Interval(std::chrono::milliseconds(COLOR_UPDATE_INTERVAL)); m_DispatcherQueueTimerTickToken = m_DispatcherQueueTimer.Tick({ get_weak(), &ColorPicker::OnDispatcherQueueTimerTick }); m_DispatcherQueueTimer.Start(); } ColorPicker::~ColorPicker() { ConnectEvents(false); m_DispatcherQueueTimer.Tick(m_DispatcherQueueTimerTickToken); m_DispatcherQueueTimer.Stop(); UnregisterPropertyChangedCallback(composable_base::ColorProperty(), m_ColorPropertyChangedToken.value); Unloaded(m_UnloadedToken); Loaded(m_LoadedToken); } void ColorPicker::OnApplyTemplate() { ConnectEvents(false); #define GET_TEMPLATE_CHILD(NAME) m_ ## NAME = GetTemplateChild(UTIL_STRINGIFY(NAME)).try_as<decltype(m_ ## NAME)>() GET_TEMPLATE_CHILD(AlphaChannelSlider); GET_TEMPLATE_CHILD(AlphaChannelTextBox); GET_TEMPLATE_CHILD(Channel1Slider); GET_TEMPLATE_CHILD(Channel1TextBox); GET_TEMPLATE_CHILD(Channel2Slider); GET_TEMPLATE_CHILD(Channel2TextBox); GET_TEMPLATE_CHILD(Channel3Slider); GET_TEMPLATE_CHILD(Channel3TextBox); GET_TEMPLATE_CHILD(CheckeredBackground1Border); GET_TEMPLATE_CHILD(CheckeredBackground2Border); GET_TEMPLATE_CHILD(CheckeredBackground3Border); GET_TEMPLATE_CHILD(CheckeredBackground4Border); GET_TEMPLATE_CHILD(CheckeredBackground5Border); GET_TEMPLATE_CHILD(CheckeredBackground6Border); GET_TEMPLATE_CHILD(CheckeredBackground7Border); GET_TEMPLATE_CHILD(CheckeredBackground8Border); GET_TEMPLATE_CHILD(CheckeredBackground9Border); GET_TEMPLATE_CHILD(CheckeredBackground10Border); GET_TEMPLATE_CHILD(ColorSpectrumControl); GET_TEMPLATE_CHILD(ColorSpectrumAlphaSlider); GET_TEMPLATE_CHILD(ColorSpectrumThirdDimensionSlider); GET_TEMPLATE_CHILD(HexInputTextBox); GET_TEMPLATE_CHILD(HsvToggleButton); GET_TEMPLATE_CHILD(RgbToggleButton); GET_TEMPLATE_CHILD(P1PreviewBorder); GET_TEMPLATE_CHILD(P2PreviewBorder); GET_TEMPLATE_CHILD(N1PreviewBorder); GET_TEMPLATE_CHILD(N2PreviewBorder); #undef GET_TEMPLATE_CHILD base_type::OnApplyTemplate(); UpdateVisualState(false); SetActiveColorRepresentation(txmp::ColorRepresentation::Rgba); m_IsInitialized = true; UpdateColorControlValues(); ConnectEvents(true); } void ColorPicker::ConnectEvents(bool connected) { if (connected && !m_EventsConnected) { #define CONNECT_EVENT(NAME, EVENT, HANDLER) NAME ## EVENT ## Token = NAME.EVENT(HANDLER) if (m_Channel1Slider) { CONNECT_EVENT(m_Channel1Slider, ValueChanged, m_Channel1SliderValueChangedHandler); CONNECT_EVENT(m_Channel1Slider, Loaded, m_Channel1SliderLoadedHandler); } if (m_Channel2Slider) { CONNECT_EVENT(m_Channel2Slider, ValueChanged, m_Channel2SliderValueChangedHandler); CONNECT_EVENT(m_Channel2Slider, Loaded, m_Channel2SliderLoadedHandler); } if (m_Channel3Slider) { CONNECT_EVENT(m_Channel3Slider, ValueChanged, m_Channel3SliderValueChangedHandler); CONNECT_EVENT(m_Channel3Slider, Loaded, m_Channel3SliderLoadedHandler); } if (m_AlphaChannelSlider) { CONNECT_EVENT(m_AlphaChannelSlider, ValueChanged, m_AlphaChannelSliderValueChangedHandler); CONNECT_EVENT(m_AlphaChannelSlider, Loaded, m_AlphaChannelSliderLoadedHandler); } if (m_ColorSpectrumAlphaSlider) { CONNECT_EVENT(m_ColorSpectrumAlphaSlider, ValueChanged, m_SpectrumAlphaChannelSliderValueChangedHandler); CONNECT_EVENT(m_ColorSpectrumAlphaSlider, Loaded, m_SpectrumAlphaChannelSliderLoadedHandler); } if (m_ColorSpectrumThirdDimensionSlider) { CONNECT_EVENT(m_ColorSpectrumThirdDimensionSlider, ValueChanged, m_ThirdDimensionSliderValueChangedHandler); CONNECT_EVENT(m_ColorSpectrumThirdDimensionSlider, Loaded, m_ThirdDimensionSliderLoadedHandler); } if (m_Channel1TextBox) { CONNECT_EVENT(m_Channel1TextBox, KeyDown, m_Channel1TextBoxKeyDownHandler); CONNECT_EVENT(m_Channel1TextBox, LostFocus, m_Channel1TextBoxLostFocusHandler); } if (m_Channel2TextBox) { CONNECT_EVENT(m_Channel2TextBox, KeyDown, m_Channel2TextBoxKeyDownHandler); CONNECT_EVENT(m_Channel2TextBox, LostFocus, m_Channel2TextBoxLostFocusHandler); } if (m_Channel3TextBox) { CONNECT_EVENT(m_Channel3TextBox, KeyDown, m_Channel3TextBoxKeyDownHandler); CONNECT_EVENT(m_Channel3TextBox, LostFocus, m_Channel3TextBoxLostFocusHandler); } if (m_AlphaChannelTextBox) { CONNECT_EVENT(m_AlphaChannelTextBox, KeyDown, m_AlphaChannelTextBoxKeyDownHandler); CONNECT_EVENT(m_AlphaChannelTextBox, LostFocus, m_AlphaChannelTextBoxLostFocusHandler); } if (m_HexInputTextBox) { CONNECT_EVENT(m_HexInputTextBox, KeyDown, m_HexInputTextBoxKeyDownHandler); CONNECT_EVENT(m_HexInputTextBox, LostFocus, m_HexInputTextBoxLostFocusHandler); } #define CONNECT_INVERTED_PROPERTY_HANDLER(NAME) \ NAME ## InvertedPropertyChangedToken.value = NAME.RegisterPropertyChangedCallback(m_InvertedCheckerboardProperty, m_CheckeredBackgroundBorderInvertedPropertyChangedHandler); if (m_CheckeredBackground1Border) { CONNECT_EVENT(m_CheckeredBackground1Border, Loaded, m_CheckeredBackgroundBorderLoadedHandler); CONNECT_INVERTED_PROPERTY_HANDLER(m_CheckeredBackground1Border); } if (m_CheckeredBackground2Border) { CONNECT_EVENT(m_CheckeredBackground2Border, Loaded, m_CheckeredBackgroundBorderLoadedHandler); CONNECT_INVERTED_PROPERTY_HANDLER(m_CheckeredBackground2Border); } if (m_CheckeredBackground3Border) { CONNECT_EVENT(m_CheckeredBackground3Border, Loaded, m_CheckeredBackgroundBorderLoadedHandler); CONNECT_INVERTED_PROPERTY_HANDLER(m_CheckeredBackground3Border); } if (m_CheckeredBackground4Border) { CONNECT_EVENT(m_CheckeredBackground4Border, Loaded, m_CheckeredBackgroundBorderLoadedHandler); CONNECT_INVERTED_PROPERTY_HANDLER(m_CheckeredBackground4Border); } if (m_CheckeredBackground5Border) { CONNECT_EVENT(m_CheckeredBackground5Border, Loaded, m_CheckeredBackgroundBorderLoadedHandler); CONNECT_INVERTED_PROPERTY_HANDLER(m_CheckeredBackground5Border); } if (m_CheckeredBackground6Border) { CONNECT_EVENT(m_CheckeredBackground6Border, Loaded, m_CheckeredBackgroundBorderLoadedHandler); CONNECT_INVERTED_PROPERTY_HANDLER(m_CheckeredBackground6Border); } if (m_CheckeredBackground7Border) { CONNECT_EVENT(m_CheckeredBackground7Border, Loaded, m_CheckeredBackgroundBorderLoadedHandler); CONNECT_INVERTED_PROPERTY_HANDLER(m_CheckeredBackground7Border); } if (m_CheckeredBackground8Border) { CONNECT_EVENT(m_CheckeredBackground8Border, Loaded, m_CheckeredBackgroundBorderLoadedHandler); CONNECT_INVERTED_PROPERTY_HANDLER(m_CheckeredBackground8Border); } if (m_CheckeredBackground9Border) { CONNECT_EVENT(m_CheckeredBackground9Border, Loaded, m_CheckeredBackgroundBorderLoadedHandler); CONNECT_INVERTED_PROPERTY_HANDLER(m_CheckeredBackground9Border); } if (m_CheckeredBackground10Border) { CONNECT_EVENT(m_CheckeredBackground10Border, Loaded, m_CheckeredBackgroundBorderLoadedHandler); CONNECT_INVERTED_PROPERTY_HANDLER(m_CheckeredBackground10Border); } #undef CONNECT_INVERTED_PROPERTY_HANDLER if (m_ColorSpectrumControl) { CONNECT_EVENT(m_ColorSpectrumControl, ColorChanged, m_ColorSpectrumControlColorChangedHandler); CONNECT_EVENT(m_ColorSpectrumControl, GotFocus, m_ColorSpectrumControlGotFocusHandler); } if (m_HsvToggleButton) { CONNECT_EVENT(m_HsvToggleButton, Checked, m_HsvToggleButtonCheckedChangedHandler); CONNECT_EVENT(m_HsvToggleButton, Unchecked, m_HsvToggleButtonCheckedChangedHandler); } if (m_RgbToggleButton) { CONNECT_EVENT(m_RgbToggleButton, Checked, m_RgbToggleButtonCheckedChangedHandler); CONNECT_EVENT(m_RgbToggleButton, Unchecked, m_RgbToggleButtonCheckedChangedHandler); } if (m_P1PreviewBorder) { CONNECT_EVENT(m_P1PreviewBorder, PointerPressed, m_PreviewBorderPointerPressedHandler); } if (m_P2PreviewBorder) { CONNECT_EVENT(m_P2PreviewBorder, PointerPressed, m_PreviewBorderPointerPressedHandler); } if (m_N1PreviewBorder) { CONNECT_EVENT(m_N1PreviewBorder, PointerPressed, m_PreviewBorderPointerPressedHandler); } if (m_N2PreviewBorder) { CONNECT_EVENT(m_N2PreviewBorder, PointerPressed, m_PreviewBorderPointerPressedHandler); } #undef CONNECT_EVENT m_EventsConnected = true; } else if (!connected && m_EventsConnected) { #define DISCONNECT_EVENT(NAME, EVENT) NAME.EVENT(NAME ## EVENT ## Token) if (m_Channel1Slider) { DISCONNECT_EVENT(m_Channel1Slider, ValueChanged); DISCONNECT_EVENT(m_Channel1Slider, Loaded); } if (m_Channel2Slider) { DISCONNECT_EVENT(m_Channel2Slider, ValueChanged); DISCONNECT_EVENT(m_Channel2Slider, Loaded); } if (m_Channel3Slider) { DISCONNECT_EVENT(m_Channel3Slider, ValueChanged); DISCONNECT_EVENT(m_Channel3Slider, Loaded); } if (m_AlphaChannelSlider) { DISCONNECT_EVENT(m_AlphaChannelSlider, ValueChanged); DISCONNECT_EVENT(m_AlphaChannelSlider, Loaded); } if (m_ColorSpectrumAlphaSlider) { DISCONNECT_EVENT(m_ColorSpectrumAlphaSlider, ValueChanged); DISCONNECT_EVENT(m_ColorSpectrumAlphaSlider, Loaded); } if (m_ColorSpectrumThirdDimensionSlider) { DISCONNECT_EVENT(m_ColorSpectrumThirdDimensionSlider, ValueChanged); DISCONNECT_EVENT(m_ColorSpectrumThirdDimensionSlider, Loaded); } if (m_Channel1TextBox) { DISCONNECT_EVENT(m_Channel1TextBox, KeyDown); DISCONNECT_EVENT(m_Channel1TextBox, LostFocus); } if (m_Channel2TextBox) { DISCONNECT_EVENT(m_Channel2TextBox, KeyDown); DISCONNECT_EVENT(m_Channel2TextBox, LostFocus); } if (m_Channel3TextBox) { DISCONNECT_EVENT(m_Channel3TextBox, KeyDown); DISCONNECT_EVENT(m_Channel3TextBox, LostFocus); } if (m_AlphaChannelTextBox) { DISCONNECT_EVENT(m_AlphaChannelTextBox, KeyDown); DISCONNECT_EVENT(m_AlphaChannelTextBox, LostFocus); } if (m_HexInputTextBox) { DISCONNECT_EVENT(m_HexInputTextBox, KeyDown); DISCONNECT_EVENT(m_HexInputTextBox, LostFocus); } #define DISCONNECT_INVERTED_PROPERTY_HANDLER(NAME) \ NAME.UnregisterPropertyChangedCallback(m_InvertedCheckerboardProperty, NAME ## InvertedPropertyChangedToken.value) if (m_CheckeredBackground1Border) { DISCONNECT_EVENT(m_CheckeredBackground1Border, Loaded); DISCONNECT_INVERTED_PROPERTY_HANDLER(m_CheckeredBackground1Border); } if (m_CheckeredBackground2Border) { DISCONNECT_EVENT(m_CheckeredBackground2Border, Loaded); DISCONNECT_INVERTED_PROPERTY_HANDLER(m_CheckeredBackground2Border); } if (m_CheckeredBackground3Border) { DISCONNECT_EVENT(m_CheckeredBackground3Border, Loaded); DISCONNECT_INVERTED_PROPERTY_HANDLER(m_CheckeredBackground3Border); } if (m_CheckeredBackground4Border) { DISCONNECT_EVENT(m_CheckeredBackground4Border, Loaded); DISCONNECT_INVERTED_PROPERTY_HANDLER(m_CheckeredBackground4Border); } if (m_CheckeredBackground5Border) { DISCONNECT_EVENT(m_CheckeredBackground5Border, Loaded); DISCONNECT_INVERTED_PROPERTY_HANDLER(m_CheckeredBackground5Border); } if (m_CheckeredBackground6Border) { DISCONNECT_EVENT(m_CheckeredBackground6Border, Loaded); DISCONNECT_INVERTED_PROPERTY_HANDLER(m_CheckeredBackground6Border); } if (m_CheckeredBackground7Border) { DISCONNECT_EVENT(m_CheckeredBackground7Border, Loaded); DISCONNECT_INVERTED_PROPERTY_HANDLER(m_CheckeredBackground7Border); } if (m_CheckeredBackground8Border) { DISCONNECT_EVENT(m_CheckeredBackground8Border, Loaded); DISCONNECT_INVERTED_PROPERTY_HANDLER(m_CheckeredBackground8Border); } if (m_CheckeredBackground9Border) { DISCONNECT_EVENT(m_CheckeredBackground9Border, Loaded); DISCONNECT_INVERTED_PROPERTY_HANDLER(m_CheckeredBackground9Border); } if (m_CheckeredBackground10Border) { DISCONNECT_EVENT(m_CheckeredBackground10Border, Loaded); DISCONNECT_INVERTED_PROPERTY_HANDLER(m_CheckeredBackground10Border); } #undef DISCONNECT_INVERTED_PROPERTY_HANDLER if (m_ColorSpectrumControl) { DISCONNECT_EVENT(m_ColorSpectrumControl, ColorChanged); DISCONNECT_EVENT(m_ColorSpectrumControl, GotFocus); } if (m_HsvToggleButton) { DISCONNECT_EVENT(m_HsvToggleButton, Checked); DISCONNECT_EVENT(m_HsvToggleButton, Unchecked); } if (m_RgbToggleButton) { DISCONNECT_EVENT(m_RgbToggleButton, Checked); DISCONNECT_EVENT(m_RgbToggleButton, Unchecked); } if (m_P1PreviewBorder) { DISCONNECT_EVENT(m_P1PreviewBorder, PointerPressed); } if (m_P2PreviewBorder) { DISCONNECT_EVENT(m_P2PreviewBorder, PointerPressed); } if (m_N1PreviewBorder) { DISCONNECT_EVENT(m_N1PreviewBorder, PointerPressed); } if (m_N2PreviewBorder) { DISCONNECT_EVENT(m_N2PreviewBorder, PointerPressed); } #undef DISCONNECT_EVENT m_EventsConnected = false; } } void ColorPicker::OnLoaded(const IInspectable &, const wux::RoutedEventArgs &) { if (const auto root = XamlRoot()) { m_XamlRootChangedRevoker = root.Changed(winrt::auto_revoke, m_XamlRootChangedHandler); OnXamlRootChanged(nullptr, nullptr); } } void ColorPicker::OnUnloaded(const IInspectable &, const wux::RoutedEventArgs &) { m_XamlRootChangedRevoker.revoke(); } template<txmp::ColorChannel channel> void ColorPicker::OnChannelSliderValueChanged(const IInspectable &, const wuxc::Primitives::RangeBaseValueChangedEventArgs &args) { SetColorChannel(GetActiveColorRepresentation(), channel, args.NewValue()); } void ColorPicker::OnSpectrumAlphaChannelSliderValueChanged(const IInspectable &, const wuxc::Primitives::RangeBaseValueChangedEventArgs &args) { SetColorChannel(txmp::ColorRepresentation::Hsva, txmp::ColorChannel::Alpha, args.NewValue()); } void ColorPicker::OnThirdDimensionChannelSliderValueChanged(const IInspectable &, const wuxc::Primitives::RangeBaseValueChangedEventArgs &args) { SetColorChannel(txmp::ColorRepresentation::Hsva, GetActiveColorSpectrumThirdDimension(), args.NewValue()); } template<txmp::ColorChannel channel> void ColorPicker::OnChannelSliderLoaded(const IInspectable &sender, const wux::RoutedEventArgs &) { UpdateChannelSliderBackground(sender.try_as<ColorPickerSlider>(), channel, GetActiveColorRepresentation()); } void ColorPicker::OnSpectrumAlphaChannelSliderLoaded(const IInspectable &, const wux::RoutedEventArgs &) { UpdateChannelSliderBackground(m_ColorSpectrumAlphaSlider, txmp::ColorChannel::Alpha, txmp::ColorRepresentation::Hsva); } void ColorPicker::OnThirdDimensionChannelSliderLoaded(const IInspectable &, const wux::RoutedEventArgs &) { UpdateChannelSliderBackground(m_ColorSpectrumThirdDimensionSlider, GetActiveColorSpectrumThirdDimension(), txmp::ColorRepresentation::Hsva); } template<txmp::ColorChannel channel> void ColorPicker::OnChannelTextBoxKeyDown(const IInspectable &sender, const wux::Input::KeyRoutedEventArgs &args) { if (args.Key() == Windows::System::VirtualKey::Enter) { ApplyChannelTextBoxValue(sender.try_as<wuxc::TextBox>(), channel); } } template<txmp::ColorChannel channel> void ColorPicker::OnChannelTextBoxLostFocus(const IInspectable &sender, const wux::RoutedEventArgs &) { ApplyChannelTextBoxValue(sender.try_as<wuxc::TextBox>(), channel); } void ColorPicker::OnHexInputTextBoxKeyDown(const IInspectable &, const wux::Input::KeyRoutedEventArgs &args) { if (args.Key() == Windows::System::VirtualKey::Enter) { try { UpdateColorRightNow(Util::Color::FromString(m_HexInputTextBox.Text(), true)); } catch (...) { UpdateColorControlValues(); UpdateChannelSliderBackgrounds(); } } } void ColorPicker::OnHexInputTextBoxLostFocus(const IInspectable &, const wux::RoutedEventArgs &) { try { UpdateColorRightNow(Util::Color::FromString(m_HexInputTextBox.Text(), true)); } catch (...) { UpdateColorControlValues(); UpdateChannelSliderBackgrounds(); } } fire_and_forget ColorPicker::OnCheckeredBackgroundBorderLoaded(const IInspectable &sender, const wux::RoutedEventArgs &args) { if (auto border = sender.try_as<wuxc::Border>()) { auto width = static_cast<int32_t>(border.ActualWidth()); auto height = static_cast<int32_t>(border.ActualHeight()); if (width != 0 && height != 0) { // retrieve properties before going to the background const auto background = CheckerBackgroundColor(); const bool inverted = GetInvertedCheckerboard(border); double renderScale = 1.0; if (const auto root = border.XamlRoot()) { renderScale = root.RasterizationScale(); width = static_cast<int32_t>(width * renderScale); height = static_cast<int32_t>(height * renderScale); } // create the bitmap on this thread wux::Media::Imaging::WriteableBitmap bitmap { width, height }; const auto buffer = bitmap.PixelBuffer(); const auto bgraPixelData = buffer.data(); // move to background const weak_ref<wuxc::Border> border_weak = border; border = nullptr; const auto dispatcher = Windows::System::DispatcherQueue::GetForCurrentThread(); co_await resume_background(); FillCheckeredBitmap(bgraPixelData, width, height, renderScale, background, inverted); border = border_weak.get(); if (border) { // return to main thread co_await wil::resume_foreground(dispatcher); bitmap.Invalidate(); wux::Media::ImageBrush brush; brush.ImageSource(bitmap); brush.Stretch(wux::Media::Stretch::Fill); border.Background(brush); } } } } void ColorPicker::OnCheckeredBackgroundInvertedPropertyChanged(const wux::DependencyObject &sender, const wux::DependencyProperty &) { OnCheckeredBackgroundBorderLoaded(sender, nullptr); } void ColorPicker::OnColorSpectrumControlColorChanged(const IInspectable &, const muxc::ColorChangedEventArgs &args) { // It is OK in this case to use the RGB representation ScheduleColorUpdate(args.NewColor(), true); } void ColorPicker::OnColorSpectrumControlGotFocus(const IInspectable &, const wux::RoutedEventArgs &) { Windows::UI::Color rgbColor = m_ColorSpectrumControl.Color(); /* If this control has a color that is currently empty (#00000000), * selecting a new color directly in the spectrum will fail. This is * a bug in the color spectrum. Selecting a new color in the spectrum will * keep zero for all channels (including alpha and the third dimension). * * In practice this means a new color cannot be selected using the spectrum * until both the alpha and third dimension slider are raised above zero. * This is extremely user unfriendly and must be corrected as best as possible. * * In order to work around this, detect when the color spectrum has selected * a new color and then automatically set the alpha and third dimension * channel to maximum. However, the color spectrum has a second bug, the * ColorChanged event is never raised if the color is empty. This prevents * automatically setting the other channels where it normally should be done * (in the ColorChanged event). * * In order to work around this second bug, the GotFocus event is used * to detect when the spectrum is engaged by the user. It's somewhat equivalent * to ColorChanged for this purpose. Then when the GotFocus event is fired * set the alpha and third channel values to maximum. The problem here is that * the GotFocus event does not have access to the new color that was selected * in the spectrum. It is not available due to the afore mentioned bug or due to * timing. This means the best that can be done is to just set a 'neutral' * color such as white. * * There is still a small usability issue with this as it requires two * presses to set a color. That's far better than having to slide up both * sliders though. * * 1. If the color is empty, the first press on the spectrum will set white * and ignore the pressed color on the spectrum * 2. The second press on the spectrum will be correctly handled. * */ if (rgbColor == Windows::UI::Color { }) { ScheduleColorUpdate({ 0xFF, 0xFF, 0xFF, 0xFF }); } else if (rgbColor.A == 0x00) { // As an additional usability improvement, reset alpha to maximum when the spectrum is used. // The color spectrum has no alpha channel and it is much more intuitive to do this for the user // especially if the picker was initially set with Colors.Transparent. rgbColor.A = 0xFF; ScheduleColorUpdate(rgbColor); } } template<txmp::ColorRepresentation representation> void ColorPicker::OnColorRepresentationToggleButtonCheckedChanged(const IInspectable &, const wux::RoutedEventArgs &) { SetActiveColorRepresentation(representation); UpdateColorControlValues(); UpdateChannelSliderBackgrounds(); } void ColorPicker::OnPreviewBorderPointerPressed(const IInspectable &sender, const wux::Input::IPointerRoutedEventArgs &) { if (const auto border = sender.try_as<wuxc::Border>()) { if (const auto brush = border.Background().try_as<wux::Media::SolidColorBrush>()) { ScheduleColorUpdate(brush.Color()); } } } void ColorPicker::OnColorPropertyChanged(const wux::DependencyObject &sender, const wux::DependencyProperty &) { if (const auto that = sender.try_as<ColorPicker>()) { // TODO: Coerce the value if Alpha is disabled, is this handled in the base ColorPicker? if (that->m_SavedHsvColor && that->Color() != that->m_SavedHsvColorRgbEquivalent) { // The color was updated from an unknown source // The RGB and HSV colors are no longer in sync so the HSV color must be cleared that->m_SavedHsvColor.reset(); that->m_SavedHsvColorRgbEquivalent.reset(); } that->UpdateColorControlValues(); that->UpdateChannelSliderBackgrounds(); } } void ColorPicker::OnDispatcherQueueTimerTick(const IInspectable &, const IInspectable &) { if (m_UpdatedRgbColor) { const auto newColor = *m_UpdatedRgbColor; // Clear first to avoid timing issues if it takes longer than the timer interval to set the new color m_UpdatedRgbColor.reset(); // An equality check here is important // Without it, OnColorChanged would continuously be invoked and preserveHsvColor overwritten when not wanted if (newColor != Color()) { // Disable events here so the color update isn't repeated as other controls in the UI are updated through binding. // For example, the Spectrum should be bound to Color, as soon as Color is changed here the Spectrum is updated. // Then however, the ColorSpectrum.ColorChanged event would fire which would schedule a new color update -- // with the same color. This causes several problems: // 1. Layout cycle that may crash the app // 2. A performance hit recalculating for no reason // 3. preserveHsvColor gets overwritten unexpectedly by the ColorChanged handler ConnectEvents(false); UpdateColorRightNow(newColor, m_UpdateFromSpectrum); ConnectEvents(true); } m_UpdateFromSpectrum = false; } } void ColorPicker::OnXamlRootChanged(const wux::XamlRoot &, const wux::XamlRootChangedEventArgs &) { OnCheckeredBackgroundBorderLoaded(m_CheckeredBackground1Border, nullptr); OnCheckeredBackgroundBorderLoaded(m_CheckeredBackground2Border, nullptr); OnCheckeredBackgroundBorderLoaded(m_CheckeredBackground3Border, nullptr); OnCheckeredBackgroundBorderLoaded(m_CheckeredBackground4Border, nullptr); OnCheckeredBackgroundBorderLoaded(m_CheckeredBackground5Border, nullptr); OnCheckeredBackgroundBorderLoaded(m_CheckeredBackground6Border, nullptr); OnCheckeredBackgroundBorderLoaded(m_CheckeredBackground7Border, nullptr); OnCheckeredBackgroundBorderLoaded(m_CheckeredBackground8Border, nullptr); OnCheckeredBackgroundBorderLoaded(m_CheckeredBackground9Border, nullptr); OnCheckeredBackgroundBorderLoaded(m_CheckeredBackground10Border, nullptr); } void ColorPicker::ApplyChannelTextBoxValue(const wuxc::TextBox &channelTextBox, txmp::ColorChannel channel) { if (channelTextBox) { const auto text = channelTextBox.Text(); if (Util::Trim(text).empty()) { // An empty string is allowed and happens when the clear TextBox button is pressed // This case should be interpreted as zero SetColorChannel(GetActiveColorRepresentation(), channel, 0.0); } else if (auto parsed = m_DecimalFormatter.ParseDouble(text)) { SetColorChannel(GetActiveColorRepresentation(), channel, parsed.Value()); } else { // Reset TextBox values UpdateColorControlValues(); UpdateChannelSliderBackgrounds(); } } } void ColorPicker::ScheduleColorUpdate(Windows::UI::Color newColor, bool isFromSpectrum) { if (!IsAlphaEnabled()) { newColor.A = 255; } m_UpdatedRgbColor = newColor; m_UpdateFromSpectrum = isFromSpectrum; } void ColorPicker::UpdateColorRightNow(Windows::UI::Color newColor, bool isFromSpectrum) { m_UpdateFromSpectrum = isFromSpectrum; Color(newColor); } void ColorPicker::SetActiveColorRepresentation(txmp::ColorRepresentation representation) { bool eventsDisconnectedByMethod = false; // Disable events during the update if (m_EventsConnected) { ConnectEvents(false); eventsDisconnectedByMethod = true; } // Sync the UI controls and visual state // The default is always RGBA if (representation == txmp::ColorRepresentation::Hsva) { if (m_RgbToggleButton) { const auto isChecked = m_RgbToggleButton.IsChecked(); if (isChecked && isChecked.Value()) { m_RgbToggleButton.IsChecked(false); } } if (m_HsvToggleButton) { const auto isChecked = m_HsvToggleButton.IsChecked(); if (!isChecked || !isChecked.Value()) { m_HsvToggleButton.IsChecked(true); } } } else { if (m_RgbToggleButton) { const auto isChecked = m_RgbToggleButton.IsChecked(); if (!isChecked || !isChecked.Value()) { m_RgbToggleButton.IsChecked(true); } } if (m_HsvToggleButton) { const auto isChecked = m_HsvToggleButton.IsChecked(); if (isChecked && isChecked.Value()) { m_HsvToggleButton.IsChecked(false); } } } UpdateVisualState(false); if (eventsDisconnectedByMethod) { ConnectEvents(true); } } void ColorPicker::SetColorChannel(txmp::ColorRepresentation representation, txmp::ColorChannel channel, double newValue) { Windows::UI::Color oldRgbColor = Color(); Windows::UI::Color newRgbColor{}; if (representation == txmp::ColorRepresentation::Hsva) { txmp::HsvColor oldHsvColor{}; // Warning: Always maintain/use HSV information in the saved HSV color // This avoids loss of precision and drift caused by continuously converting to/from RGB if (!m_SavedHsvColor) { oldHsvColor = Util::Color(oldRgbColor).ToHSV(); } else { oldHsvColor = *m_SavedHsvColor; } switch (channel) { case txmp::ColorChannel::Channel1: oldHsvColor.H = isnan(newValue) ? 0.0 : std::clamp(newValue, 0.0, 360.0); break; case txmp::ColorChannel::Channel2: oldHsvColor.S = isnan(newValue) ? 0.0 : std::clamp(newValue / 100.0, 0.0, 1.0); break; case txmp::ColorChannel::Channel3: oldHsvColor.V = isnan(newValue) ? 0.0 : std::clamp(newValue / 100.0, 0.0, 1.0); break; case txmp::ColorChannel::Alpha: // Unlike color channels, default to no transparency oldHsvColor.A = isnan(newValue) ? 1.0 : std::clamp(newValue / 100.0, 0.0, 1.0); break; } newRgbColor = Util::Color::FromHSV(oldHsvColor); // Must update HSV color m_SavedHsvColor = oldHsvColor; m_SavedHsvColorRgbEquivalent = newRgbColor; } else { switch (channel) { case txmp::ColorChannel::Channel1: oldRgbColor.R = isnan(newValue) ? 0 : static_cast<uint8_t>(std::clamp(newValue, 0.0, 255.0)); break; case txmp::ColorChannel::Channel2: oldRgbColor.G = isnan(newValue) ? 0 : static_cast<uint8_t>(std::clamp(newValue, 0.0, 255.0)); break; case txmp::ColorChannel::Channel3: oldRgbColor.B = isnan(newValue) ? 0 : static_cast<uint8_t>(std::clamp(newValue, 0.0, 255.0)); break; case txmp::ColorChannel::Alpha: // Unlike color channels, default to no transparency oldRgbColor.A = isnan(newValue) ? 255 : static_cast<uint8_t>(std::clamp(newValue, 0.0, 255.0)); break; } newRgbColor = oldRgbColor; // Must clear saved HSV color m_SavedHsvColor.reset(); m_SavedHsvColorRgbEquivalent.reset(); } ScheduleColorUpdate(newRgbColor); } void ColorPicker::UpdateVisualState(bool useTransitions) { wux::VisualStateManager::GoToState(*this, IsEnabled() ? L"Normal" : L"Disabled", useTransitions); wux::VisualStateManager::GoToState(*this, GetActiveColorRepresentation() == txmp::ColorRepresentation::Hsva ? L"HsvSelected" : L"RgbSelected", useTransitions); wux::VisualStateManager::GoToState(*this, IsColorPaletteVisible() ? L"ColorPaletteVisible" : L"ColorPaletteCollapsed", useTransitions); } void ColorPicker::UpdateColorControlValues() { if (m_IsInitialized) { bool eventsDisconnectedByMethod = false; Util::Color rgbColor = Color(); // Disable events during the update if (m_EventsConnected) { ConnectEvents(false); eventsDisconnectedByMethod = true; } if (m_HexInputTextBox) { uint32_t colorRgba = rgbColor.ToRGBA(); hstring colorHex; if (IsAlphaEnabled()) { colorHex = winrt::format(L"{:08X}", colorRgba); } else { colorHex = winrt::format(L"{:06X}", static_cast<uint32_t>(colorRgba >> 8)); } m_HexInputTextBox.Text(colorHex); } // Regardless of the active color representation, the spectrum is always HSV // Therefore, always calculate HSV color here // Warning: Always maintain/use HSV information in the saved HSV color // This avoids loss of precision and drift caused by continuously converting to/from RGB if (!m_SavedHsvColor) { if (m_UpdateFromSpectrum && m_ColorSpectrumControl) { // grab it from the spectrum for more precision m_SavedHsvColor = Util::HsvColor(m_ColorSpectrumControl.HsvColor()); } else { auto hsvCol = rgbColor.ToHSV(); // Round the channels, be sure rounding matches with the scaling next // Rounding of SVA requires at MINIMUM 2 decimal places hsvCol.H = std::round(hsvCol.H); hsvCol.S = std::floor(hsvCol.S * 100.0) / 100.0; hsvCol.V = std::floor(hsvCol.V * 100.0) / 100.0; hsvCol.A = std::floor(hsvCol.A * 100.0) / 100.0; // Must update HSV color m_SavedHsvColor = hsvCol; } m_SavedHsvColorRgbEquivalent = rgbColor; } const Util::HsvColor hsvColor = *m_SavedHsvColor; // Update the color spectrum // Remember the spectrum is always HSV and must be updated as such to avoid // conversion errors // Don't update HsvColor if the update came from the spectrum, because it makes the cursor "wobble" if (m_ColorSpectrumControl && !m_UpdateFromSpectrum) { m_ColorSpectrumControl.HsvColor(hsvColor); } // Update the color spectrum third dimension channel if (m_ColorSpectrumThirdDimensionSlider) { // Convert the channels into a usable range for the user switch (GetActiveColorSpectrumThirdDimension()) { case txmp::ColorChannel::Channel1: { // Hue m_ColorSpectrumThirdDimensionSlider.Minimum(0.0); m_ColorSpectrumThirdDimensionSlider.Maximum(360.0); m_ColorSpectrumThirdDimensionSlider.Value(hsvColor.H); break; } case txmp::ColorChannel::Channel2: { // Saturation m_ColorSpectrumThirdDimensionSlider.Minimum(0.0); m_ColorSpectrumThirdDimensionSlider.Maximum(100.0); m_ColorSpectrumThirdDimensionSlider.Value(hsvColor.S * 100.0); break; } case txmp::ColorChannel::Channel3: { // Value m_ColorSpectrumThirdDimensionSlider.Minimum(0.0); m_ColorSpectrumThirdDimensionSlider.Maximum(100.0); m_ColorSpectrumThirdDimensionSlider.Value(hsvColor.V * 100.0); break; } } } // Color spectrum alpha if (m_ColorSpectrumAlphaSlider) { m_ColorSpectrumAlphaSlider.Minimum(0.0); m_ColorSpectrumAlphaSlider.Maximum(100.0); m_ColorSpectrumAlphaSlider.Value(hsvColor.A * 100); } // Update all other color channels if (GetActiveColorRepresentation() == txmp::ColorRepresentation::Hsva) { // Convert the channels into a usable range for the user const double saturation = hsvColor.S * 100; const double value = hsvColor.V * 100; const double alpha = hsvColor.A * 100; // Hue if (m_Channel1TextBox) { m_Channel1TextBox.MaxLength(3); m_Channel1TextBox.Text(m_DecimalFormatter.FormatInt(static_cast<int64_t>(hsvColor.H))); } if (m_Channel1Slider) { m_Channel1Slider.Minimum(0.0); m_Channel1Slider.Maximum(360.0); m_Channel1Slider.Value(hsvColor.H); } // Saturation if (m_Channel2TextBox) { m_Channel2TextBox.MaxLength(3); m_Channel2TextBox.Text(m_DecimalFormatter.FormatInt(static_cast<int64_t>(saturation))); } if (m_Channel2Slider) { m_Channel2Slider.Minimum(0.0); m_Channel2Slider.Maximum(100.0); m_Channel2Slider.Value(saturation); } // Value if (m_Channel3TextBox) { m_Channel3TextBox.MaxLength(3); m_Channel3TextBox.Text(m_DecimalFormatter.FormatInt(static_cast<int64_t>(value))); } if (m_Channel3Slider) { m_Channel3Slider.Minimum(0.0); m_Channel3Slider.Maximum(100.0); m_Channel3Slider.Value(value); } // Alpha if (m_AlphaChannelTextBox) { m_AlphaChannelTextBox.MaxLength(3); m_AlphaChannelTextBox.Text(m_DecimalFormatter.FormatInt(static_cast<int64_t>(alpha))); } if (m_AlphaChannelSlider) { m_AlphaChannelSlider.Minimum(0.0); m_AlphaChannelSlider.Maximum(100.0); m_AlphaChannelSlider.Value(alpha); } } else { // Red if (m_Channel1TextBox) { m_Channel1TextBox.MaxLength(3); m_Channel1TextBox.Text(m_DecimalFormatter.FormatInt(rgbColor.R)); } if (m_Channel1Slider) { m_Channel1Slider.Minimum(0.0); m_Channel1Slider.Maximum(255.0); m_Channel1Slider.Value(rgbColor.R); } // Green if (m_Channel2TextBox) { m_Channel2TextBox.MaxLength(3); m_Channel2TextBox.Text(m_DecimalFormatter.FormatInt(rgbColor.G)); } if (m_Channel2Slider) { m_Channel2Slider.Minimum(0.0); m_Channel2Slider.Maximum(255.0); m_Channel2Slider.Value(rgbColor.G); } // Blue if (m_Channel3TextBox) { m_Channel3TextBox.MaxLength(3); m_Channel3TextBox.Text(m_DecimalFormatter.FormatInt(rgbColor.B)); } if (m_Channel3Slider) { m_Channel3Slider.Minimum(0.0); m_Channel3Slider.Maximum(255.0); m_Channel3Slider.Value(rgbColor.B); } // Alpha if (m_AlphaChannelTextBox) { m_AlphaChannelTextBox.MaxLength(3); m_AlphaChannelTextBox.Text(m_DecimalFormatter.FormatInt(rgbColor.A)); } if (m_AlphaChannelSlider) { m_AlphaChannelSlider.Minimum(0.0); m_AlphaChannelSlider.Maximum(255.0); m_AlphaChannelSlider.Value(rgbColor.A); } } if (eventsDisconnectedByMethod) { ConnectEvents(true); } } } void ColorPicker::UpdateChannelSliderBackgrounds() { UpdateChannelSliderBackground(m_Channel1Slider, txmp::ColorChannel::Channel1, GetActiveColorRepresentation()); UpdateChannelSliderBackground(m_Channel2Slider, txmp::ColorChannel::Channel2, GetActiveColorRepresentation()); UpdateChannelSliderBackground(m_Channel3Slider, txmp::ColorChannel::Channel3, GetActiveColorRepresentation()); UpdateChannelSliderBackground(m_AlphaChannelSlider, txmp::ColorChannel::Alpha, GetActiveColorRepresentation()); // Always HSV UpdateChannelSliderBackground(m_ColorSpectrumAlphaSlider, txmp::ColorChannel::Alpha, txmp::ColorRepresentation::Hsva); UpdateChannelSliderBackground(m_ColorSpectrumThirdDimensionSlider, GetActiveColorSpectrumThirdDimension(), txmp::ColorRepresentation::Hsva); } void ColorPicker::UpdateChannelSliderBackground(const ColorPickerSlider &slider, txmp::ColorChannel channel, txmp::ColorRepresentation representation) { if (slider) { // Regardless of the active color representation, the sliders always use HSV // Therefore, always calculate HSV color here // Warning: Always maintain/use HSV information in the saved HSV color // This avoids loss of precision and drift caused by continuously converting to/from RGB if (!m_SavedHsvColor) { const auto rgbColor = Color(); m_SavedHsvColor = Util::Color(rgbColor).ToHSV(); m_SavedHsvColorRgbEquivalent = rgbColor; } slider.IsAutoUpdatingEnabled(false); slider.ColorChannel(channel); slider.ColorRepresentation(representation); slider.HsvColor(*m_SavedHsvColor); slider.UpdateColors(); } } void ColorPicker::UpdateCustomPalette() { if (const auto palette = CustomPalette()) { const auto shadeCount = palette.ShadeCount(); const auto colorCount = palette.ColorCount(); CustomPaletteColumnCount(colorCount); if (const auto colors = CustomPaletteColors()) { colors.Clear(); for (uint32_t shadeIndex = 0; shadeIndex < shadeCount; ++shadeIndex) { for (uint32_t colorIndex = 0; colorIndex < colorCount; ++colorIndex) { colors.Append(palette.GetColor(colorIndex, shadeIndex)); } } } } } txmp::ColorRepresentation ColorPicker::GetActiveColorRepresentation() { if (m_HsvToggleButton) { const auto isChecked = m_HsvToggleButton.IsChecked(); if (isChecked && isChecked.Value()) { return txmp::ColorRepresentation::Hsva; } } return txmp::ColorRepresentation::Rgba; } txmp::ColorChannel ColorPicker::GetActiveColorSpectrumThirdDimension() { switch (ColorSpectrumComponents()) { case muxc::ColorSpectrumComponents::SaturationValue: case muxc::ColorSpectrumComponents::ValueSaturation: return txmp::ColorChannel::Channel1; case muxc::ColorSpectrumComponents::HueValue: case muxc::ColorSpectrumComponents::ValueHue: return txmp::ColorChannel::Channel2; case muxc::ColorSpectrumComponents::HueSaturation: case muxc::ColorSpectrumComponents::SaturationHue: return txmp::ColorChannel::Channel3; // should never get there default: throw std::invalid_argument("ColorSpectrumComponents has an unexpected value"); } } }
40,449
C++
.cpp
1,095
32.796347
174
0.755802
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,874
Case.cpp
TranslucentTB_TranslucentTB/Xaml/Controls/Case.cpp
#include "pch.h" #include "Case.h" #if __has_include("Controls/Case.g.cpp") #include "Controls/Case.g.cpp" #endif namespace winrt::TranslucentTB::Xaml::Controls::implementation { // everything declared in header, this file required for cppwinrt uniform construction }
271
C++
.cpp
9
28.777778
87
0.784615
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,875
ContrastBrushConverter.cpp
TranslucentTB_TranslucentTB/Xaml/Converters/ContrastBrushConverter.cpp
#include "pch.h" #include "ContrastBrushConverter.h" #if __has_include("Converters/ContrastBrushConverter.g.cpp") #include "Converters/ContrastBrushConverter.g.cpp" #endif #include "util/color.hpp" namespace winrt::TranslucentTB::Xaml::Converters::implementation { uint8_t ContrastBrushConverter::AlphaThreshold() noexcept { return m_AlphaThreshold; } void ContrastBrushConverter::AlphaThreshold(uint8_t value) noexcept { m_AlphaThreshold = value; } wf::IInspectable ContrastBrushConverter::Convert(const IInspectable &value, const wux::Interop::TypeName &, const IInspectable &parameter, const hstring &) { Windows::UI::Color comparisonColor; std::optional<Windows::UI::Color> defaultColor; if (const auto valueColor = value.try_as<Windows::UI::Color>()) { comparisonColor = *valueColor; } else if (const auto valueBrush = value.try_as<wux::Media::SolidColorBrush>()) { comparisonColor = valueBrush.Color(); } else { return wux::DependencyProperty::UnsetValue(); } if (const auto parameterColor = parameter.try_as<Windows::UI::Color>()) { defaultColor = *parameterColor; } else if (const auto parameterBrush = parameter.try_as<wux::Media::SolidColorBrush>()) { defaultColor = parameterBrush.Color(); } Windows::UI::Color resultColor; if (comparisonColor.A < m_AlphaThreshold && defaultColor) { resultColor = *defaultColor; } else if (Util::Color(comparisonColor).IsDarkColor()) { // White resultColor = { 0xFF, 0xFF, 0xFF, 0xFF }; } else { // Black resultColor = { 0xFF, 0x00, 0x00, 0x00 }; } return wux::Media::SolidColorBrush(resultColor); } wf::IInspectable ContrastBrushConverter::ConvertBack(const IInspectable &, const wux::Interop::TypeName &, const IInspectable &, const hstring &) { return wux::DependencyProperty::UnsetValue(); } }
1,857
C++
.cpp
62
27.112903
156
0.741176
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,876
ThicknessFilterConverter.cpp
TranslucentTB_TranslucentTB/Xaml/Converters/ThicknessFilterConverter.cpp
#include "pch.h" #include "ThicknessFilterConverter.h" #if __has_include("Converters/ThicknessFilterConverter.g.cpp") #include "Converters/ThicknessFilterConverter.g.cpp" #endif namespace winrt::TranslucentTB::Xaml::Converters::implementation { wf::IInspectable ThicknessFilterConverter::Convert(const IInspectable &value, const wux::Interop::TypeName &, const IInspectable &, const hstring &) { auto thickness = unbox_value<wux::Thickness>(value); const auto scale = Scale(); if (!std::isnan(scale)) { thickness.Left *= scale; thickness.Top *= scale; thickness.Right *= scale; thickness.Bottom *= scale; } return box_value(ApplyFilter(thickness, Filter())); } wf::IInspectable ThicknessFilterConverter::ConvertBack(const IInspectable &, const wux::Interop::TypeName &, const IInspectable &, const hstring&) { return wux::DependencyProperty::UnsetValue(); } wux::Thickness ThicknessFilterConverter::ApplyFilter(wux::Thickness thickness, txmp::ThicknessFilterKind filter) { switch (filter) { case txmp::ThicknessFilterKind::Left: thickness.Left = 0.0; break; case txmp::ThicknessFilterKind::Top: thickness.Top = 0.0; break; case txmp::ThicknessFilterKind::Right: thickness.Right = 0.0; break; case txmp::ThicknessFilterKind::Bottom: thickness.Bottom = 0.0; break; case txmp::ThicknessFilterKind::LeftRight: thickness.Left = 0.0; thickness.Right = 0.0; break; case txmp::ThicknessFilterKind::TopBottom: thickness.Top = 0.0; thickness.Bottom = 0.0; break; } return thickness; } }
1,586
C++
.cpp
52
27.403846
149
0.746386
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,877
ColorToColorShadeConverter.cpp
TranslucentTB_TranslucentTB/Xaml/Converters/ColorToColorShadeConverter.cpp
#include "pch.h" #include "ColorToColorShadeConverter.h" #if __has_include("Converters/ColorToColorShadeConverter.g.cpp") #include "Converters/ColorToColorShadeConverter.g.cpp" #endif #include "util/color.hpp" namespace winrt::TranslucentTB::Xaml::Converters::implementation { wf::IInspectable ColorToColorShadeConverter::Convert(const IInspectable &value, const wux::Interop::TypeName &, const IInspectable &parameter, const hstring &) { Windows::UI::Color rgbColor; if (const auto valueColor = value.try_as<Windows::UI::Color>()) { rgbColor = *valueColor; } else if (const auto valueBrush = value.try_as<wux::Media::SolidColorBrush>()) { rgbColor = valueBrush.Color(); } else { // Invalid color value provided return wux::DependencyProperty::UnsetValue(); } if (const auto shade = parameter.try_as<int32_t>()) { return box_value(GetShade(rgbColor, *shade)); } else { // Non-int provided return wux::DependencyProperty::UnsetValue(); } } wf::IInspectable ColorToColorShadeConverter::ConvertBack(const IInspectable &, const wux::Interop::TypeName &, const IInspectable &, const hstring &) { return wux::DependencyProperty::UnsetValue(); } Windows::UI::Color ColorToColorShadeConverter::GetShade(Windows::UI::Color col, int shade) { static constexpr std::uint8_t TOLERANCE = 5; static constexpr double VALUE_DELTA = 0.25; // Specially handle minimum (black) and maximum (white) if (col.R <= TOLERANCE && col.G <= TOLERANCE && col.B <= TOLERANCE) { switch (shade) { case 1: return { col.A, 0x3F, 0x3F, 0x3F }; case 2: return { col.A, 0x80, 0x80, 0x80 }; case 3: return { col.A, 0xBF, 0xBF, 0xBF }; default: return col; } } else if (col.R >= (0xFF + TOLERANCE) && col.G >= (0xFF + TOLERANCE) && col.B >= (0xFF + TOLERANCE)) { switch (shade) { case -1: return { col.A, 0xBF, 0xBF, 0xBF }; case -2: return { col.A, 0x80, 0x80, 0x80 }; case -3: return { col.A, 0x3F, 0x3F, 0x3F }; default: return col; } } else { Util::HsvColor hsvColor = Util::Color(col).ToHSV(); // Use the HSV representation as it's more perceptual. // Only the value is changed by a fixed percentage so the algorithm is reproducible. // This does not account for perceptual differences and also does not match with // system accent color calculation. if (shade != 0) { hsvColor.V *= 1.0 + (shade * VALUE_DELTA); hsvColor.V = std::clamp(hsvColor.V, 0.0, 1.0); } return Util::Color::FromHSV(hsvColor); } } }
2,584
C++
.cpp
87
26.252874
160
0.686014
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,878
ColorToDisplayNameConverter.cpp
TranslucentTB_TranslucentTB/Xaml/Converters/ColorToDisplayNameConverter.cpp
#include "pch.h" #include "ColorToDisplayNameConverter.h" #if __has_include("Converters/ColorToDisplayNameConverter.g.cpp") #include "Converters/ColorToDisplayNameConverter.g.cpp" #endif namespace winrt::TranslucentTB::Xaml::Converters::implementation { wf::IInspectable ColorToDisplayNameConverter::Convert(const IInspectable &value, const wux::Interop::TypeName&, const IInspectable &, const hstring &) { Windows::UI::Color rgbColor; if (const auto valueColor = value.try_as<Windows::UI::Color>()) { rgbColor = *valueColor; } else if (const auto valueBrush = value.try_as<wux::Media::SolidColorBrush>()) { rgbColor = valueBrush.Color(); } else { // Invalid color value provided return wux::DependencyProperty::UnsetValue(); } return box_value(Windows::UI::ColorHelper::ToDisplayName(rgbColor)); } wf::IInspectable ColorToDisplayNameConverter::ConvertBack(const IInspectable &, const wux::Interop::TypeName &, const IInspectable &, const hstring &) { return wux::DependencyProperty::UnsetValue(); } }
1,049
C++
.cpp
30
32.4
151
0.763314
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,879
version.cpp
TranslucentTB_TranslucentTB/Tests/version.cpp
#include <gtest/gtest.h> #include "version.hpp" TEST(Version_FromHighLow, ConvertsToSameVersion) { ASSERT_EQ(Version::FromHighLow(0x00010002, 0x00030004), (Version { 1, 2, 3, 4 })); } TEST(Version_FromPackageVersion_WinRT, ConvertsToSameVersion) { winrt::Windows::ApplicationModel::PackageVersion winRtVersion = { .Major = 1, .Minor = 2, .Build = 3, .Revision = 4 }; ASSERT_EQ(Version::FromPackageVersion(winRtVersion), (Version { 1, 2, 3, 4 })); } TEST(Version_FromPackageVersion_Win32, ConvertsToSameVersion) { PACKAGE_VERSION win32version = { .Revision = 4, .Build = 3, .Minor = 2, .Major = 1 }; ASSERT_EQ(Version::FromPackageVersion(win32version), (Version { 1, 2, 3, 4 })); } TEST(Version_Format, FormatsProperly) { ASSERT_EQ(std::format(L"{}", Version { 1, 2, 3, 4 }), L"1.2.3.4"); } TEST(Version_Format, SupportsFormatStrings) { ASSERT_EQ(std::format(L"{:04}", Version { 1, 2, 3, 4 }), L"0001.0002.0003.0004"); } TEST(Version_Equality, ReturnsTrueWhenSame) { ASSERT_EQ((Version { 1, 2, 3, 4 }), (Version { 1, 2, 3, 4 })); } TEST(Version_Equality, ReturnsFalseWhenDifferent) { ASSERT_NE((Version { 1, 2, 3, 4 }), (Version { 5, 6, 7, 8 })); }
1,185
C++
.cpp
42
26.333333
83
0.692851
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,880
win32.cpp
TranslucentTB_TranslucentTB/Tests/win32.cpp
#include <compare> #include <gtest/gtest.h> #include "win32.hpp" #include "win32version.h" // to allow ASSERT_EQ with RECT static bool operator==(const RECT &left, const RECT &right) noexcept { // make sure there's no padding static_assert(sizeof(RECT) == 4 * sizeof(LONG)); return std::memcmp(&left, &right, sizeof(RECT)) == 0; } namespace { static constexpr std::pair<std::wstring_view, std::wstring_view> differentContentCases[] = { { L"foo", L"foobar" }, { L"FOOBAR", L"FOO" }, { L"foo", L"foobar" }, { L"FOOBAR", L"FOO" }, { L"foo", L"bar" }, { L"FOO", L"BAR" }, { L"foo bar", L"foobar" }, { L"\u00E9", L"\u00EB" } }; static constexpr std::pair<std::wstring_view, std::wstring_view> sameContentCases[] = { { L"foo", L"FOO" }, { L"FOOBAR", L"foobar" }, { L"foo", L"foo" }, { L"\u00EB", L"\u00CB" }, { L"aAa\u00CB\u00EB\u00CBAaA", L"AaA\u00EB\u00CB\u00EBaAa" } }; } TEST(win32_GetExeLocation, GetsCorrectFileName) { const auto [location, hr] = win32::GetExeLocation(); ASSERT_HRESULT_SUCCEEDED(hr); ASSERT_EQ(location.filename(), L"Tests.exe"); } TEST(win32_GetFixedFileVersion, GetsCorrectFileVersion) { static constexpr Version expected = { EXPECTED_FILE_VERSION }; const auto [location, hr] = win32::GetExeLocation(); ASSERT_HRESULT_SUCCEEDED(hr); const auto [version, hr2] = win32::GetFixedFileVersion(location); ASSERT_HRESULT_SUCCEEDED(hr2); ASSERT_EQ(version, expected); } TEST(win32_RectFitsInRect, FalseWhenBiggerInnerRect) { static constexpr std::pair<RECT, RECT> biggerBounds[] = { { { 2, 2, 3, 3 }, { 0, 0, 4, 4 } }, { { 1, 1, 4, 4 }, { 0, 2, 3, 3 } }, { { 1, 1, 4, 4 }, { 2, 2, 5, 3 } }, { { 1, 1, 4, 4 }, { 2, 0, 3, 3 } }, { { 1, 1, 4, 4 }, { 2, 2, 3, 5 } } }; for (const auto &rects : biggerBounds) { ASSERT_FALSE(win32::RectFitsInRect(rects.first, rects.second)); } } TEST(win32_RectFitsInRect, TrueWhenSmallerInnerRect) { static constexpr std::pair<RECT, RECT> smallerBounds[] = { { { 0, 0, 4, 4 }, { 2, 2, 3, 3 } }, { { 0, 0, 3, 3 }, { 0, 1, 2, 2 } }, { { 0, 0, 3, 3 }, { 1, 1, 3, 2 } }, { { 0, 0, 3, 3 }, { 1, 0, 2, 2 } }, { { 0, 0, 3, 3 }, { 1, 1, 2, 3 } }, { { 0, 0, 1, 1 }, { 0, 0, 1, 1 } } }; for (const auto &rects : smallerBounds) { ASSERT_TRUE(win32::RectFitsInRect(rects.first, rects.second)); } } TEST(win32_OffsetRect, SupportsXOffset) { static constexpr std::tuple<RECT, RECT, int> cases[] = { { { 10, 10, 20, 20 }, { 5, 10, 15, 20 }, -5 }, { { 10, 10, 20, 20 }, { 15, 10, 25, 20 }, 5 }, { { 10, 10, 20, 20 }, { 10, 10, 20, 20 }, 0 } }; for (auto [initial, expected, offset] : cases) { win32::OffsetRect(initial, offset, 0); ASSERT_EQ(initial, expected); } } TEST(win32_OffsetRect, SupportsYOffset) { static constexpr std::tuple<RECT, RECT, int> cases[] = { { { 10, 10, 20, 20 }, { 10, 5, 20, 15 }, -5 }, { { 10, 10, 20, 20 }, { 10, 15, 20, 25 }, 5 }, { { 10, 10, 20, 20 }, { 10, 10, 20, 20 }, 0 } }; for (auto [initial, expected, offset] : cases) { win32::OffsetRect(initial, 0, offset); ASSERT_EQ(initial, expected); } } TEST(win32_IsSameFilename, ReturnsFalse) { for (const auto &testCase : differentContentCases) { ASSERT_FALSE(win32::IsSameFilename(testCase.first, testCase.second)); } } TEST(win32_IsSameFilename, ReturnsTrue) { for (const auto &testCase : sameContentCases) { ASSERT_TRUE(win32::IsSameFilename(testCase.first, testCase.second)); } } TEST(win32_FilenameHash, DifferentHash) { const win32::FilenameHash hasher; for (const auto &testCase : differentContentCases) { ASSERT_NE(hasher(testCase.first), hasher(testCase.second)); } } TEST(win32_FilenameHash, SameHash) { const win32::FilenameHash hasher; for (const auto &testCase : sameContentCases) { ASSERT_EQ(hasher(testCase.first), hasher(testCase.second)); } }
3,819
C++
.cpp
130
27.192308
93
0.638745
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,881
strings.cpp
TranslucentTB_TranslucentTB/Tests/util/strings.cpp
#include <gtest/gtest.h> #include <ranges> #include "../testingdata.hpp" #include "util/strings.hpp" namespace { static constexpr std::pair<std::wstring_view, std::wstring_view> trimTestCases[] = { { L"\t\v \f\n\rfoo \nbar", L"foo \nbar" }, { L"foo \nbar\t\r \f\n\v", L"foo \nbar" }, { L"\t\v \f\n\rfoo \nbar\t\r \f\n\v", L"foo \nbar" }, { L"foo \nbar", L"foo \nbar" }, { L" \f\n\r\t\v", L"" } }; } TEST(Util_IsAscii, ReturnsTrueWhenAscii) { for (const auto number : numbers) { ASSERT_TRUE(Util::IsAscii(number)); } for (const auto [upper, lower] : alphabet) { ASSERT_TRUE(Util::IsAscii(upper)); ASSERT_TRUE(Util::IsAscii(lower)); } for (const auto character : specialCharacters) { ASSERT_TRUE(Util::IsAscii(character)); } } TEST(Util_IsAscii, ReturnsFalseWhenNotAscii) { ASSERT_FALSE(Util::IsAscii(L'\u00CB')); ASSERT_FALSE(Util::IsAscii(L'\u0125')); } TEST(Util_AsciiToUpper, ReturnsUppercaseAsciiFromLowercase) { for (const auto [upper, lower] : alphabet) { ASSERT_EQ(Util::AsciiToUpper(lower), upper); } } TEST(Util_AsciiToUpper, ReturnsUppercaseAsciiFromUppercase) { for (const auto letter : alphabet | std::views::elements<0>) { ASSERT_EQ(Util::AsciiToUpper(letter), letter); } } TEST(Util_AsciiToUpper, DoesNotChangesOtherCharacters) { for (const auto number : numbers) { ASSERT_EQ(Util::AsciiToUpper(number), number); } for (const auto character : specialCharacters) { ASSERT_EQ(Util::AsciiToUpper(character), character); } } TEST(Util_Trim, Trims) { for (const auto &[input, expected] : trimTestCases) { ASSERT_EQ(Util::Trim(input), expected); } } TEST(Util_TrimInplace_StringView, Trims) { for (auto [input, expected] : trimTestCases) { Util::TrimInplace(input); ASSERT_EQ(input, expected); } } TEST(Util_TrimInplace_String, Trims) { for (const auto &[input, expected] : trimTestCases) { std::wstring str(input); Util::TrimInplace(str); ASSERT_EQ(str, expected); } }
1,962
C++
.cpp
83
21.614458
85
0.709539
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,882
color.cpp
TranslucentTB_TranslucentTB/Tests/util/color.cpp
#include <gtest/gtest.h> #include <ranges> #include "util/color.hpp" TEST(Util_HsvColor_Constructor, DefaultConstructorIsTransparentBlack) { const Util::HsvColor col; ASSERT_EQ(col.H, 0.0); ASSERT_EQ(col.S, 0.0); ASSERT_EQ(col.V, 0.0); ASSERT_EQ(col.A, 0.0); } TEST(Util_HsvColor_Constructor, ConstructorFromHSVUsesFullAlpha) { const Util::HsvColor col = { 67.0, 0.68, 0.69 }; ASSERT_EQ(col.H, 67.0); ASSERT_EQ(col.S, 0.68); ASSERT_EQ(col.V, 0.69); ASSERT_EQ(col.A, 1.0); } TEST(Util_HsvColor_Constructor, ConstructorFromHSVAGivesCorrectValue) { const Util::HsvColor col = { 67.0, 0.68, 0.69, 0.70 }; ASSERT_EQ(col.H, 67.0); ASSERT_EQ(col.S, 0.68); ASSERT_EQ(col.V, 0.69); ASSERT_EQ(col.A, 0.70); } TEST(Util_HsvColor_Constructor, ConstructorFromWinRTGivesCorrectValue) { const Util::HsvColor col = txmp::HsvColor { 67.0, 0.68, 0.69, 0.70 }; ASSERT_EQ(col.H, 67.0); ASSERT_EQ(col.S, 0.68); ASSERT_EQ(col.V, 0.69); ASSERT_EQ(col.A, 0.70); } TEST(Util_HsvColor_Constructor, ConstructorFromFloat4GivesCorrectValue) { const Util::HsvColor col = wf::Numerics::float4 { 67.0f, 0.68f, 0.69f, 0.70f }; ASSERT_EQ(col.H, 67.0); ASSERT_EQ(col.S, 0.68f); ASSERT_EQ(col.V, 0.69f); ASSERT_EQ(col.A, 0.70f); } TEST(Util_HsvColor_ToWinRT, ConvertsToSameColor) { const txmp::HsvColor convertedCol = Util::HsvColor { 67.0, 0.68, 0.69, 0.70 }; const txmp::HsvColor originalCol = { .H = 67.0, .S = 0.68, .V = 0.69, .A = 0.70 }; ASSERT_EQ(convertedCol.H, originalCol.H); ASSERT_EQ(convertedCol.S, originalCol.S); ASSERT_EQ(convertedCol.V, originalCol.V); ASSERT_EQ(convertedCol.A, originalCol.A); } TEST(Util_HsvColor_ToFloat4, ConvertsToSameColor) { const wf::Numerics::float4 convertedCol = Util::HsvColor { 67.0, 0.68, 0.69, 0.70 }; const wf::Numerics::float4 originalCol = { 67.0f, 0.68f, 0.69f, 0.70f }; ASSERT_EQ(convertedCol.x, originalCol.x); ASSERT_EQ(convertedCol.y, originalCol.y); ASSERT_EQ(convertedCol.z, originalCol.z); ASSERT_EQ(convertedCol.w, originalCol.w); } TEST(Util_Color_Constructor, DefaultConstructorIsTransparentBlack) { ASSERT_EQ(Util::Color(), Util::Color(0x00, 0x00, 0x00, 0x00)); } TEST(Util_Color_Constructor, ConstructorFromRGBUsesFullAlpha) { ASSERT_EQ(Util::Color(0x00, 0x00, 0x00), Util::Color(0x00, 0x00, 0x00, 0xFF)); } TEST(Util_Color_Constructor, ConstructorFromRGBAGivesCorrectValue) { const Util::Color col = { 0xDE, 0xAD, 0xBE, 0xEF }; ASSERT_EQ(col.R, 0xDE); ASSERT_EQ(col.G, 0xAD); ASSERT_EQ(col.B, 0xBE); ASSERT_EQ(col.A, 0xEF); } TEST(Util_Color_Constructor, ConstructorFromWinRTGivesCorrectValue) { const winrt::Windows::UI::Color winrtCol = { .A = 0xEF, .R = 0xDE, .G = 0xAD, .B = 0xBE }; ASSERT_EQ(Util::Color(winrtCol), Util::Color(0xDE, 0xAD, 0xBE, 0xEF)); } TEST(Util_Color_ToRGBA, ReturnsCorrectValue) { ASSERT_EQ(Util::Color(0xDE, 0xAD, 0xBE, 0xEF).ToRGBA(), 0xDEADBEEF); } TEST(Util_Color_ToABGR, ReturnsCorrectValue) { ASSERT_EQ(Util::Color(0xDE, 0xAD, 0xBE, 0xEF).ToABGR(), 0xEFBEADDE); } TEST(Util_Color_Premultiply, ReturnsCorrectValue) { // [0, 255) for (int i : std::views::iota(0, 256)) { for (int j : std::views::iota(0, 256)) { const auto color = static_cast<uint8_t>(i); const auto alpha = static_cast<uint8_t>(j); const auto expected = static_cast<uint8_t>(color * alpha / 255); ASSERT_EQ(Util::Color(color, 0, 255, alpha).Premultiply(), Util::Color(expected, 0, alpha, alpha)); } } } TEST(Util_Color_ToHSV, ReturnsCorrectValue) { static constexpr std::pair<Util::Color, Util::HsvColor> cases[] = { { { 170, 204, 153, 255 }, { 100.0, 0.25, 0.80, 1.0 } }, { { 255, 105, 180, 255 }, { 330.0, 0.58823529411764708, 1.0, 1.0 } } }; for (const auto &testCase : cases) { const auto result = testCase.first.ToHSV(); ASSERT_DOUBLE_EQ(result.H, testCase.second.H); ASSERT_DOUBLE_EQ(result.S, testCase.second.S); ASSERT_DOUBLE_EQ(result.V, testCase.second.V); ASSERT_DOUBLE_EQ(result.A, testCase.second.A); } } TEST(Util_Color_ToString, ReturnsCorrectString) { static constexpr std::pair<Util::Color, std::wstring_view> cases[] = { { { 0xDE, 0xAD, 0xBE, 0xEF }, L"#DEADBEEF" }, { { 0x00, 0x00, 0xFF, 0x00 }, L"#0000FF00" }, { { 0x00, 0x00, 0x00, 0x00 }, L"#00000000" }, { { 0xFF, 0xFF, 0xFF, 0xFF }, L"#FFFFFFFF" }, }; for (const auto &testCase : cases) { ASSERT_EQ(testCase.first.ToString(), testCase.second); } } TEST(Util_Color_FromString, ParsesColor) { static constexpr std::tuple<std::wstring_view, bool, Util::Color> cases[] = { { L"#FAF", false, { 0xFF, 0xAA, 0xFF } }, { L"#DEAD", false, { 0xDD, 0xEE, 0xAA, 0xDD } }, { L"#C0FFEE", false, { 0xC0, 0xFF, 0xEE } }, { L"#DEADBEEF", false, { 0xDE, 0xAD, 0xBE, 0xEF } }, { L" #FFFFFF \t \n", false, { 0xFF, 0xFF, 0xFF } }, { L"#FAF", true, { 0xFF, 0xAA, 0xFF } }, { L"#DEAD", true, { 0xDD, 0xEE, 0xAA, 0xDD } }, { L"#C0FFEE", true, { 0xC0, 0xFF, 0xEE } }, { L"#DEADBEEF", true, { 0xDE, 0xAD, 0xBE, 0xEF } }, { L" #FFFFFF \t \n", true, { 0xFF, 0xFF, 0xFF } }, { L"FAF", true, { 0xFF, 0xAA, 0xFF } }, { L"DEAD", true, { 0xDD, 0xEE, 0xAA, 0xDD } }, { L"C0FFEE", true, { 0xC0, 0xFF, 0xEE } }, { L"DEADBEEF", true, { 0xDE, 0xAD, 0xBE, 0xEF } }, { L" FFFFFF \t \n", true, { 0xFF, 0xFF, 0xFF } } }; for (const auto [str, allowNoPrefix, expected] : cases) { ASSERT_EQ(Util::Color::FromString(str, allowNoPrefix), expected); } } TEST(Util_Color_FromString, ThrowsWhenInvalidColor) { static constexpr std::wstring_view cases[] = { L"FFFFFF", L"#FFFFFFF", L"#", L"", L" \n \t \r # \n" }; for (const auto &testCase : cases) { ASSERT_THROW(Util::Color::FromString(testCase), std::invalid_argument); } } TEST(Util_Color_FromString, AllowNoPrefixParameter) { ASSERT_EQ(Util::Color::FromString(L"FFFFFF", true), Util::Color(0xFF, 0xFF, 0xFF)); } TEST(Util_Color_FromRGBA, ReturnsCorrectValue) { ASSERT_EQ(Util::Color::FromRGBA(0xDEADBEEF), Util::Color(0xDE, 0xAD, 0xBE, 0xEF)); } TEST(Util_Color_FromABGR, ReturnsCorrectValue) { ASSERT_EQ(Util::Color::FromABGR(0xEFBEADDE), Util::Color(0xDE, 0xAD, 0xBE, 0xEF)); } TEST(Util_Color_FromHSV, ReturnsCorrectValue) { static constexpr std::pair<std::tuple<double, double, double>, Util::Color> cases[] = { { { 0.0, 1.0, 1.0 }, { 0xFF, 0x00, 0x00 } }, { { 0.0, 0.0, 1.0 }, { 0xFF, 0xFF, 0xFF } } }; for (const auto &testCase : cases) { const auto [h, s, v] = testCase.first; ASSERT_EQ(Util::Color::FromHSV(h, s, v), testCase.second); } } TEST(Util_Color_FromHSV, ThrowsWhenInvalidHue) { static constexpr double cases[] = { -0.1, 360.1, 1337 }; for (const auto &testCase : cases) { ASSERT_THROW(Util::Color::FromHSV(testCase, 0.0, 0.0), std::out_of_range); } } TEST(Util_Color_ToWinRT, ConvertsToSameColor) { const winrt::Windows::UI::Color convertedCol = Util::Color { 0xDE, 0xAD, 0xBE, 0xEF }; const winrt::Windows::UI::Color originalCol = { .A = 0xEF, .R = 0xDE, .G = 0xAD, .B = 0xBE }; ASSERT_EQ(convertedCol, originalCol); } TEST(Util_Color_Equality, ReturnsTrueWhenSame) { ASSERT_EQ(Util::Color(0xDE, 0xAD, 0xBE, 0xEF), Util::Color(0xDE, 0xAD, 0xBE, 0xEF)); } TEST(Util_Color_Equality, ReturnsFalseWhenDifferent) { ASSERT_NE(Util::Color(0xDE, 0xAD, 0xBE, 0xEF), Util::Color(0xC0, 0xFF, 0xEE, 0x00)); }
7,261
C++
.cpp
220
30.963636
102
0.682467
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,883
numbers.cpp
TranslucentTB_TranslucentTB/Tests/util/numbers.cpp
#include <cstdint> #include <gtest/gtest.h> #include <ranges> #include "../testingdata.hpp" #include "util/numbers.hpp" TEST(Util_IsDecimalDigit, ReturnsFalseWhenNotDigit) { for (const auto [upper, lower] : alphabet) { ASSERT_FALSE(Util::impl::IsDecimalDigit(upper)); ASSERT_FALSE(Util::impl::IsDecimalDigit(lower)); } for (const auto character : specialCharacters) { ASSERT_FALSE(Util::impl::IsDecimalDigit(character)); } } TEST(Util_IsDecimalDigit, ReturnsTrueWhenDigit) { for (const auto number : numbers) { ASSERT_TRUE(Util::impl::IsDecimalDigit(number)); } } TEST(Util_IsUpperHexDigit, ReturnsFalseWhenNotUpperCaseDigit) { for (const auto number : numbers) { ASSERT_FALSE(Util::impl::IsUpperHexDigit(number)); } for (const auto letter : alphabet | std::views::elements<0> | std::views::drop(6)) { ASSERT_FALSE(Util::impl::IsUpperHexDigit(letter)); } for (const auto letter : alphabet | std::views::elements<1>) { ASSERT_FALSE(Util::impl::IsUpperHexDigit(letter)); } for (const auto character : specialCharacters) { ASSERT_FALSE(Util::impl::IsUpperHexDigit(character)); } } TEST(Util_IsUpperHexDigit, ReturnsTrueWhenUpperCaseDigit) { for (const auto letter : alphabet | std::views::elements<0> | std::views::take(6)) { ASSERT_TRUE(Util::impl::IsUpperHexDigit(letter)); } } TEST(Util_IsLowerHexDigit, ReturnsFalseWhenNotLowerCaseDigit) { for (const auto number : numbers) { ASSERT_FALSE(Util::impl::IsLowerHexDigit(number)); } for (const auto letter : alphabet | std::views::elements<0>) { ASSERT_FALSE(Util::impl::IsLowerHexDigit(letter)); } for (const auto letter : alphabet | std::views::elements<1> | std::views::drop(6)) { ASSERT_FALSE(Util::impl::IsLowerHexDigit(letter)); } for (const auto character : specialCharacters) { ASSERT_FALSE(Util::impl::IsLowerHexDigit(character)); } } TEST(Util_IsLowerHexDigit, ReturnsTrueWhenLowerCaseDigit) { for (const auto letter : alphabet | std::views::elements<1> | std::views::take(6)) { ASSERT_TRUE(Util::impl::IsLowerHexDigit(letter)); } } TEST(Util_ParseHexNumber, ThrowsWhenInputNotANumber) { static constexpr std::wstring_view testCases[] = { L"foobar", L"0x", L"", L" \n \t\r" }; for (const auto &testCase : testCases) { ASSERT_THROW(Util::ParseHexNumber(testCase), std::invalid_argument); } } TEST(Util_ParseHexNumber, ThrowsOnOverflow) { ASSERT_THROW(Util::ParseHexNumber<uint8_t>(L"100"), std::out_of_range); } TEST(Util_ParseHexNumber, ReturnsCorrectValue) { static constexpr std::pair<std::wstring_view, uint64_t> cases[] = { { L"af", 0xAF }, { L"AF", 0xAF }, { L"aF", 0xAF }, { L"0xAF", 0xAF }, { L"0XAF", 0xAF }, { L"0xFFFFFFFFFFFFFFFA", 0xFFFFFFFFFFFFFFFA }, { L"0xFFFFFFFFFFFFFFFF", 0xFFFFFFFFFFFFFFFF }, { L"0x0", 0x0 }, { L"A", 0xA }, { L" \t \n 10 \r ", 0x10 } }; for (const auto &testCase : cases) { ASSERT_EQ(Util::ParseHexNumber<uint64_t>(testCase.first), testCase.second); } } TEST(Util_ExpandOneHexDigitByte, ExpandsByte) { ASSERT_EQ(Util::ExpandOneHexDigitByte(0xF), 0xFF); } TEST(Util_ExpandOneHexDigitByte, IgnoresSecondDigit) { ASSERT_EQ(Util::ExpandOneHexDigitByte(0xAF), 0xFF); }
3,192
C++
.cpp
120
24.491667
83
0.731236
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,884
rapidjsonhelper.cpp
TranslucentTB_TranslucentTB/Tests/config/rapidjsonhelper.cpp
#include <gtest/gtest.h> #include <gmock/gmock.h> #include <string> #include <ranges> #include "config/rapidjsonhelper.hpp" namespace { static constexpr rj::Type types[] = { rj::Type::kNullType, rj::Type::kObjectType, rj::Type::kArrayType, rj::Type::kStringType, rj::Type::kNumberType }; static constexpr rj::Type boolTypes[] = { rj::Type::kFalseType, rj::Type::kTrueType }; static constexpr std::wstring_view testObj = L"test object"; static constexpr std::wstring_view testKey = L"test_key"; enum class TestEnum : std::uint32_t { Foo = 0, Bar = 1, Buz = 2, Quux = 3, Junk = static_cast<std::uint32_t>(-1) }; static constexpr std::array<std::wstring_view, 4> testEnumNameMapping = { L"foo", L"bar", L"buz", L"quux" }; constexpr std::wstring_view TestEnumName(TestEnum value) { return testEnumNameMapping.at(static_cast<std::size_t>(value)); } struct WriterMock { MOCK_METHOD(bool, Key, (const wchar_t *str, rj::SizeType length)); MOCK_METHOD(bool, String, (const wchar_t *str, rj::SizeType length)); MOCK_METHOD(bool, Bool, (bool value)); MOCK_METHOD(bool, StartObject, ()); MOCK_METHOD(bool, EndObject, ()); }; struct JsonObjectMock { MOCK_METHOD(void, Serialize, (WriterMock &writer), (const)); MOCK_METHOD(void, Deserialize, (const rjh::value_t &obj, void (*unknownKeyCallback)(std::wstring_view))); }; void UnknownKeyCallback(std::wstring_view) noexcept { } class SameString { std::wstring_view m_MatchStr; void DescribeHelper(bool matches, std::ostream *os) const { *os << "is"; if (!matches) { *os << "n't"; } *os << " equal to " << testing::PrintToString(std::wstring(m_MatchStr)); } public: using is_gtest_matcher = void; constexpr SameString(std::wstring_view str) noexcept : m_MatchStr(str) { } constexpr bool MatchAndExplain(const std::tuple<const wchar_t *, rj::SizeType> &args, std::ostream *) const noexcept { return m_MatchStr == std::wstring_view { std::get<0>(args), std::get<1>(args) }; } void DescribeTo(std::ostream *os) const { DescribeHelper(true, os); } void DescribeNegationTo(std::ostream *os) const { DescribeHelper(false, os); } }; } TEST(RapidJSONHelper_TypeChecks, ReturnsTrueOnSameType) { for (const auto type : types) { ASSERT_TRUE(rjh::IsType(type, type)); ASSERT_NO_THROW(rjh::EnsureType(type, type, testObj)); } for (const auto type : boolTypes) { ASSERT_TRUE(rjh::IsType(type, type)); ASSERT_NO_THROW(rjh::EnsureType(type, type, testObj)); } } TEST(RapidJSONHelper_TypeChecks, ReturnsTrueOnMismatchingBoolTypes) { ASSERT_TRUE(rjh::IsType(rj::Type::kFalseType, rj::Type::kTrueType)); ASSERT_TRUE(rjh::IsType(rj::Type::kTrueType, rj::Type::kFalseType)); ASSERT_NO_THROW(rjh::EnsureType(rj::Type::kFalseType, rj::Type::kTrueType, testObj)); ASSERT_NO_THROW(rjh::EnsureType(rj::Type::kTrueType, rj::Type::kFalseType, testObj)); } TEST(RapidJSONHelper_TypeChecks, ReturnsFalseOnMismatchingTypes) { for (std::size_t i = 0; i < std::size(types); ++i) { for (std::size_t j = i + 1; j < std::size(types); ++j) { ASSERT_FALSE(rjh::IsType(types[i], types[j])); ASSERT_THROW(rjh::EnsureType(types[i], types[j], testObj), rjh::DeserializationError); } } for (const auto type : types) { for (const auto boolType : boolTypes) { ASSERT_FALSE(rjh::IsType(type, boolType)); ASSERT_THROW(rjh::EnsureType(type, boolType, testObj), rjh::DeserializationError); } } } TEST(RapidJSONHelper_Strings, ConvertsValueToStringView) { const rjh::value_t testValue(L"foo"); ASSERT_EQ(rjh::ValueToStringView(testValue), L"foo"); } TEST(RapidJSONHelper_Strings, ConvertsStringViewToValue) { const std::wstring_view testStrView(L"foo"); const auto resultValue = rjh::StringViewToValue(testStrView); ASSERT_EQ(testStrView, resultValue.Get<std::wstring>()); } TEST(RapidJSONHelper_Serialize, WriteKeyWritesKey) { WriterMock mock; EXPECT_CALL(mock, Key).With(SameString(testKey)); rjh::WriteKey(mock, testKey); } TEST(RapidJSONHelper_Serialize, WriteStringWritesString) { WriterMock mock; EXPECT_CALL(mock, String).With(SameString(testObj)); rjh::WriteString(mock, testObj); } TEST(RapidJSONHelper_Serialize, WritesBool) { for (const bool value : { true, false }) { testing::InSequence s; WriterMock mock; EXPECT_CALL(mock, Key).With(SameString(testKey)); EXPECT_CALL(mock, Bool(value)); rjh::Serialize(mock, value, testKey); } } TEST(RapidJSONHelper_Serialize, WritesString) { testing::InSequence s; WriterMock mock; EXPECT_CALL(mock, Key).With(SameString(testKey)); EXPECT_CALL(mock, String).With(SameString(testObj)); rjh::Serialize(mock, testObj, testKey); } TEST(RapidJSONHelper_Serialize, WritesEnum) { for (const TestEnum value : { TestEnum::Foo, TestEnum::Bar, TestEnum::Buz, TestEnum::Quux }) { testing::InSequence s; WriterMock mock; EXPECT_CALL(mock, Key).With(SameString(testKey)); EXPECT_CALL(mock, String).With(SameString(TestEnumName(value))); rjh::Serialize(mock, value, testKey, testEnumNameMapping); } } TEST(RapidJSONHelper_Serialize, IgnoresUnknownEnumValues) { WriterMock mock; EXPECT_CALL(mock, Key).Times(0); EXPECT_CALL(mock, String).Times(0); rjh::Serialize(mock, TestEnum::Junk, testKey, testEnumNameMapping); } TEST(RapidJSONHelper_Serialize, WritesObject) { testing::InSequence s; WriterMock writerMock; JsonObjectMock objectMock; EXPECT_CALL(writerMock, Key).With(SameString(testKey)); EXPECT_CALL(writerMock, StartObject); EXPECT_CALL(objectMock, Serialize(testing::Ref(writerMock))); EXPECT_CALL(writerMock, EndObject); rjh::Serialize(writerMock, objectMock, testKey); } TEST(RapidJSONHelper_Serialize, WritesOptional) { std::optional<std::wstring> opt(testObj); WriterMock mock; EXPECT_CALL(mock, Key).With(SameString(testKey)); EXPECT_CALL(mock, String).With(SameString(testObj)); rjh::Serialize(mock, opt, testKey); } TEST(RapidJSONHelper_Serialize, IgnoresEmptyOptional) { std::optional<std::wstring> opt; WriterMock mock; EXPECT_CALL(mock, Key).Times(0); EXPECT_CALL(mock, String).Times(0); rjh::Serialize(mock, opt, testKey); } TEST(RapidJSONHelper_Deserialize, DeserializesBool) { for (const bool expected : { true, false }) { const rjh::value_t value(expected); bool member = !expected; rjh::Deserialize(value, member, testObj); ASSERT_EQ(member, expected); } } TEST(RapidJSONHelper_Deserialize, DeserializesEnum) { for (const auto expected : { TestEnum::Foo, TestEnum::Bar, TestEnum::Buz, TestEnum::Quux }) { const std::wstring_view str = TestEnumName(expected); const rjh::value_t value(rjh::StringViewToValue(str)); TestEnum test = TestEnum::Junk; rjh::Deserialize(value, test, testObj, testEnumNameMapping); ASSERT_EQ(test, expected); } } TEST(RapidJSONHelper_Deserialize, ThrowsOnInvalidEnumString) { const rjh::value_t value(L"invalid"); TestEnum test; try { rjh::Deserialize(value, test, testObj, testEnumNameMapping); FAIL(); } catch (const rjh::DeserializationError &err) { ASSERT_EQ(err.what, L"Found invalid enum string \"invalid\" while deserializing key \"test object\""); } } TEST(RapidJSONHelper_Deserialize, DeserializesClass) { const rjh::value_t value(rj::Type::kObjectType); JsonObjectMock mock; EXPECT_CALL(mock, Deserialize(testing::Ref(value), UnknownKeyCallback)); rjh::Deserialize(value, mock, testObj, UnknownKeyCallback); } TEST(RapidJSONHelper_Deserialize, DeserializesOptional) { const rjh::value_t value(true); std::optional<bool> opt; rjh::Deserialize(value, opt, testObj); ASSERT_TRUE(opt.value_or(false)); }
7,612
C++
.cpp
247
28.461538
118
0.742435
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,885
visualtreewatcher.hpp
TranslucentTB_TranslucentTB/ExplorerTAP/visualtreewatcher.hpp
#pragma once #include <string_view> #include <unordered_set> #include <xamlOM.h> #include "winrt.hpp" #include "undefgetcurrenttime.h" #include <winrt/Windows.UI.Xaml.h> #include "redefgetcurrenttime.h" #include "taskbarappearanceservice.hpp" struct VisualTreeWatcher : winrt::implements<VisualTreeWatcher, IVisualTreeServiceCallback2, winrt::non_agile> { public: VisualTreeWatcher(winrt::com_ptr<IUnknown> site); VisualTreeWatcher(const VisualTreeWatcher&) = delete; VisualTreeWatcher& operator=(const VisualTreeWatcher&) = delete; VisualTreeWatcher(VisualTreeWatcher&&) = delete; VisualTreeWatcher& operator=(VisualTreeWatcher&&) = delete; private: HRESULT STDMETHODCALLTYPE OnVisualTreeChange(ParentChildRelation relation, VisualElement element, VisualMutationType mutationType) override; HRESULT STDMETHODCALLTYPE OnElementStateChanged(InstanceHandle element, VisualElementState elementState, LPCWSTR context) noexcept override; wux::FrameworkElement FindParent(std::wstring_view name, wux::FrameworkElement element); template<typename T> T FromHandle(InstanceHandle handle) { wf::IInspectable obj; winrt::check_hresult(m_XamlDiagnostics->GetIInspectableFromHandle(handle, reinterpret_cast<::IInspectable**>(winrt::put_abi(obj)))); return obj.as<T>(); } winrt::com_ptr<IXamlDiagnostics> m_XamlDiagnostics; winrt::com_ptr<TaskbarAppearanceService> m_AppearanceService; std::unordered_set<InstanceHandle> m_NonMatchingXamlSources; };
1,466
C++
.h
32
43.875
141
0.827368
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,886
api.hpp
TranslucentTB_TranslucentTB/ExplorerTAP/api.hpp
#pragma once #include "arch.h" #include <windef.h> extern "C" #ifdef EXPLORERTAP_EXPORTS __declspec(dllexport) #else __declspec(dllimport) #endif HRESULT InjectExplorerTAP(DWORD pid, REFIID riid, LPVOID* ppv); using PFN_INJECT_EXPLORER_TAP = decltype(&InjectExplorerTAP);
274
C++
.h
11
23.727273
63
0.804598
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,887
tapsite.hpp
TranslucentTB_TranslucentTB/ExplorerTAP/tapsite.hpp
#pragma once #include <ocidl.h> #include <xamlOM.h> #include "winrt.hpp" #include <wil/resource.h> #include "ExplorerTAP.h" #include "visualtreewatcher.hpp" class TAPSite : public winrt::implements<TAPSite, IObjectWithSite, winrt::non_agile> { public: static wil::unique_event_nothrow GetReadyEvent(); private: HRESULT STDMETHODCALLTYPE SetSite(IUnknown* pUnkSite) override; HRESULT STDMETHODCALLTYPE GetSite(REFIID riid, void** ppvSite) noexcept override; static winrt::weak_ref<VisualTreeWatcher> s_VisualTreeWatcher; winrt::com_ptr<IUnknown> site; };
564
C++
.h
17
31.588235
84
0.806273
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,888
taskbarappearanceservice.hpp
TranslucentTB_TranslucentTB/ExplorerTAP/taskbarappearanceservice.hpp
#pragma once #include <unordered_map> #include <xamlOM.h> #include "winrt.hpp" #include "undefgetcurrenttime.h" #include <winrt/Windows.System.h> #include <winrt/Windows.UI.Xaml.Media.h> #include <winrt/Windows.UI.Xaml.Shapes.h> #include "redefgetcurrenttime.h" #include <wil/resource.h> #include "ExplorerTAP.h" #include "wilx.hpp" class TaskbarAppearanceService : public winrt::implements<TaskbarAppearanceService, ITaskbarAppearanceService, IVersionedApi, winrt::non_agile> { public: TaskbarAppearanceService(); TaskbarAppearanceService(const TaskbarAppearanceService&) = delete; TaskbarAppearanceService& operator=(const TaskbarAppearanceService&) = delete; TaskbarAppearanceService(TaskbarAppearanceService&&) = delete; TaskbarAppearanceService& operator=(TaskbarAppearanceService&&) = delete; HRESULT STDMETHODCALLTYPE GetVersion(DWORD* apiVersion) noexcept override; HRESULT STDMETHODCALLTYPE SetTaskbarAppearance(HWND taskbar, TaskbarBrush brush, UINT color) override; HRESULT STDMETHODCALLTYPE ReturnTaskbarToDefaultAppearance(HWND taskbar) override; HRESULT STDMETHODCALLTYPE SetTaskbarBorderVisibility(HWND taskbar, BOOL visible) override; HRESULT STDMETHODCALLTYPE RestoreAllTaskbarsToDefault() override; HRESULT STDMETHODCALLTYPE RestoreAllTaskbarsToDefaultWhenProcessDies(DWORD pid) override; void RegisterTaskbar(InstanceHandle frameHandle, HWND window); void RegisterTaskbarBackground(InstanceHandle frameHandle, wux::Shapes::Shape element); void RegisterTaskbarBorder(InstanceHandle frameHandle, wux::Shapes::Shape element); void UnregisterTaskbar(InstanceHandle frameHandle); ~TaskbarAppearanceService(); static void InstallProxyStub(); static void UninstallProxyStub(); private: template<typename T> struct ControlInfo { T control = nullptr; wux::Media::Brush originalFill = nullptr; }; struct TaskbarInfo { ControlInfo<wux::Shapes::Shape> background, border; HWND window; }; winrt::fire_and_forget OnProcessDied(); static void RestoreDefaultControlFill(const ControlInfo<wux::Shapes::Shape> &info); static void NTAPI ProcessWaitCallback(void *parameter, BOOLEAN timedOut); DWORD m_RegisterCookie; std::unordered_map<InstanceHandle, TaskbarInfo> m_Taskbars; winrt::Windows::System::DispatcherQueue m_XamlThreadQueue; wil::unique_process_handle m_Process; wilx::unique_any<UnregisterWait> m_WaitHandle; static DWORD s_ProxyStubRegistrationCookie; };
2,429
C++
.h
55
42.054545
143
0.835244
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,889
lazyfilesink.hpp
TranslucentTB_TranslucentTB/ProgramLog/lazyfilesink.hpp
#pragma once #include "arch.h" #include <filesystem> #include <mutex> #include <spdlog/details/null_mutex.h> #include <spdlog/sinks/base_sink.h> #include <string_view> #include <type_traits> #include <wil/resource.h> #include "api.h" enum class lazy_sink_state { opened = 0, nothing_logged = 1, failed = 2 }; template<typename Mutex> class lazy_file_sink final : public spdlog::sinks::base_sink<Mutex> { using path_getter_t = std::add_pointer_t<std::filesystem::path()>; public: explicit lazy_file_sink(std::filesystem::path path) : m_File(std::move(path)), m_Tried(false) { } const std::filesystem::path &file() const noexcept { return m_File; } PROGRAMLOG_API lazy_sink_state state(); protected: void sink_it_(const spdlog::details::log_msg &msg) override; void flush_() override; private: bool m_Tried; wil::unique_hfile m_Handle; std::filesystem::path m_File; void open(); template<typename T> void write(const T &thing); }; using lazy_file_sink_mt = lazy_file_sink<std::mutex>; using lazy_file_sink_st = lazy_file_sink<spdlog::details::null_mutex>;
1,080
C++
.h
35
29.114286
98
0.739845
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,890
log.hpp
TranslucentTB_TranslucentTB/ProgramLog/log.hpp
#pragma once #include <atomic> #include <ctime> #include <filesystem> #include <memory> #include <optional> #include <string> #include <string_view> #include "api.h" #include "lazyfilesink.hpp" class Log { private: enum class InitStatus { NotInitialized, Initializing, Initialized }; static std::atomic<InitStatus> s_LogInitStatus; static std::weak_ptr<lazy_file_sink_mt> s_LogSink; static std::time_t GetProcessCreationTime() noexcept; static std::filesystem::path GetPath(const std::optional<std::filesystem::path> &storageFolder); static void LogErrorHandler(const std::string &message); public: PROGRAMLOG_API static bool IsInitialized() noexcept; PROGRAMLOG_API static std::shared_ptr<lazy_file_sink_mt> GetSink() noexcept; PROGRAMLOG_API static void Initialize(const std::optional<std::filesystem::path> &storageFolder); };
851
C++
.h
27
29.740741
98
0.788767
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
true
false
false
true
false
false
4,892
win32.hpp
TranslucentTB_TranslucentTB/ProgramLog/error/win32.hpp
#pragma once #include "arch.h" #include <windef.h> #include <winerror.h> #include <wil/result_macros.h> #include <wil/resource.h> #include "error.hpp" namespace Error { namespace impl { std::wstring FormatHRESULT(HRESULT result, std::wstring_view description); wil::unique_hlocal_string FormatMessageForLanguage(HRESULT result, DWORD langId, DWORD &count); } PROGRAMLOG_API std::wstring MessageFromHRESULT(HRESULT result); } #define HresultHandle(hresult_, level_, message_) ErrorHandleCommonMacro((level_), (message_), Error::MessageFromHRESULT((hresult_))) #define HresultVerify(hresult_, level_, message_) do { \ if (const HRESULT hr_ = (hresult_); FAILED(hr_)) [[unlikely]] \ { \ HresultHandle(hr_, (level_), (message_)); \ } \ } while (0) #define LastErrorHandle(level_, message_) do { \ const HRESULT hr_ = HRESULT_FROM_WIN32(GetLastError()); \ HresultHandle(hr_, (level_), (message_)); \ } while (0) #define LastErrorVerify(level_, message_) do { \ if (const DWORD lastErr_ = GetLastError(); lastErr_ != NO_ERROR) [[unlikely]] \ { \ HresultHandle(HRESULT_FROM_WIN32(lastErr_), (level_), (message_)); \ } \ } while (0) #define ResultExceptionHandle(exception_, level_, message_) HresultHandle((exception_).GetErrorCode(), (level_), (message_)) #define ResultExceptionCatch(level_, message_) catch (const wil::ResultException &exception_) { ResultExceptionHandle(exception_, (level_), (message_)); }
1,433
C++
.h
33
41.575758
154
0.72394
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,893
error.hpp
TranslucentTB_TranslucentTB/ProgramLog/error/error.hpp
#pragma once #include "arch.h" #include <spdlog/common.h> #include <source_location> #include <string_view> #include <thread> #include "../api.h" #include "appinfo.hpp" #include "util/null_terminated_string_view.hpp" #define UTF8_ERROR_TITLE UTF8_APP_NAME " - Error" namespace Error { namespace impl { PROGRAMLOG_API bool ShouldLogInternal(spdlog::level::level_enum level); // Needs to be in DLL because spdlog log registry is per-module. PROGRAMLOG_API void Log(std::wstring_view msg, spdlog::level::level_enum level, std::source_location location); PROGRAMLOG_API std::wstring GetLogMessage(std::wstring_view message, std::wstring_view error_message); template<spdlog::level::level_enum level> inline void Handle(std::wstring_view message, std::wstring_view error_message, std::source_location location) { Log(GetLogMessage(message, error_message), level, location); } template<> PROGRAMLOG_API void Handle<spdlog::level::err>(std::wstring_view message, std::wstring_view error_message, std::source_location location); template<> [[noreturn]] PROGRAMLOG_API void Handle<spdlog::level::critical>(std::wstring_view message, std::wstring_view error_message, std::source_location location); std::thread HandleCommon(spdlog::level::level_enum level, std::wstring_view message, std::wstring_view error_message, std::source_location location, Util::null_terminated_wstring_view title, std::wstring_view description, unsigned int type); void HandleCriticalCommon(std::wstring_view message, std::wstring_view error_message, std::source_location location); } template<spdlog::level::level_enum level> inline bool ShouldLog() { return impl::ShouldLogInternal(level); } template<> constexpr bool ShouldLog<spdlog::level::critical>() { return true; } template<> constexpr bool ShouldLog<spdlog::level::err>() { return true; } }; #define PROGRAMLOG_ERROR_LOCATION std::source_location::current() #define MessagePrint(level_, message_) Error::impl::Handle<(level_)>((message_), std::wstring_view { }, PROGRAMLOG_ERROR_LOCATION) #define ErrorHandleCommonMacro(level_, message_, error_message_) do { \ if constexpr ((level_) == spdlog::level::critical || (level_) == spdlog::level::err) \ { \ Error::impl::Handle<(level_)>((message_), (error_message_), PROGRAMLOG_ERROR_LOCATION); \ } \ else if (Error::ShouldLog<(level_)>()) \ { \ Error::impl::Handle<(level_)>((message_), (error_message_), PROGRAMLOG_ERROR_LOCATION); \ } \ } while (0)
2,497
C++
.h
56
42.267857
243
0.745881
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,894
std.hpp
TranslucentTB_TranslucentTB/ProgramLog/error/std.hpp
#pragma once #include <system_error> #include "error.hpp" namespace Error { PROGRAMLOG_API std::wstring MessageFromStdErrorCode(const std::error_code &err); } #define StdErrorCodeHandle(errc_, level_, message_) ErrorHandleCommonMacro((level_), (message_), Error::MessageFromStdErrorCode((errc_))) #define StdErrorCodeVerify(errc_, level_, message_) do { \ if (const std::error_code ec_ = (errc_); ec_) [[unlikely]] \ { \ StdErrorCodeHandle(ec_, (level_), (message_)); \ } \ } while (0) #define StdSystemErrorHandle(exception_, level_, message_) ErrorHandleCommonMacro((level_), (message_), Error::MessageFromStdErrorCode((exception_).code())) #define StdSystemErrorCatch(level_, message_) catch (const std::system_error &exception_) { StdSystemErrorHandle(exception_, (level_), (message_)); }
805
C++
.h
15
51.866667
156
0.735969
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,895
rapidjson.hpp
TranslucentTB_TranslucentTB/ProgramLog/error/rapidjson.hpp
#pragma once #include <rapidjson/error/en.h> #include "error.hpp" #include "../../Common/config/rapidjsonhelper.hpp" #define ParseErrorCodeHandle(code_, level_, message_) ErrorHandleCommonMacro((level_), (message_), rj::GetParseError_En((code_))) #define HelperDeserializationErrorHandle(exception_, level_, message_) ErrorHandleCommonMacro((level_), (message_), (exception_).what) #define HelperDeserializationErrorCatch(level_, message_) catch (const rjh::DeserializationError &exception_) { HelperDeserializationErrorHandle(exception_, (level_), (message_)); }
568
C++
.h
7
79.571429
181
0.777379
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,896
errno.hpp
TranslucentTB_TranslucentTB/ProgramLog/error/errno.hpp
#pragma once #include <cerrno> #include "error.hpp" namespace Error { PROGRAMLOG_API std::wstring MessageFromErrno(errno_t err); } #define ErrnoTHandle(err_, level_, message_) ErrorHandleCommonMacro((level_), (message_), Error::MessageFromErrno((err_)))
258
C++
.h
7
35.285714
122
0.770161
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,897
winrt.hpp
TranslucentTB_TranslucentTB/ProgramLog/error/winrt.hpp
#pragma once #include "arch.h" #include <restrictederrorinfo.h> #include <windef.h> #include <winerror.h> #include "../Common/winrt.hpp" #include "error.hpp" namespace Error { namespace impl { std::wstring FormatIRestrictedErrorInfo(HRESULT result, BSTR description); [[noreturn]] PROGRAMLOG_API void HandleCriticalWithErrorInfo(std::wstring_view message, std::wstring_view error_message, std::source_location location, HRESULT err, IRestrictedErrorInfo* errInfo); } PROGRAMLOG_API std::wstring MessageFromIRestrictedErrorInfo(IRestrictedErrorInfo *info, HRESULT errCode); PROGRAMLOG_API std::wstring MessageFromHresultError(const winrt::hresult_error &error); } #define HresultErrorHandle(exception_, level_, message_) do { \ const winrt::hresult_error &hresultError_ = (exception_); \ if constexpr ((level_) == spdlog::level::critical) \ { \ Error::impl::HandleCriticalWithErrorInfo((message_), Error::MessageFromHresultError(hresultError_), PROGRAMLOG_ERROR_LOCATION, hresultError_.code(), hresultError_.try_as<IRestrictedErrorInfo>().get()); \ } \ else if (Error::ShouldLog<(level_)>()) \ { \ Error::impl::Handle<(level_)>((message_), Error::MessageFromHresultError(hresultError_), PROGRAMLOG_ERROR_LOCATION); \ } \ } while (0) #define HresultErrorCatch(level_, message_) catch (const winrt::hresult_error &exception_) { HresultErrorHandle(exception_, (level_), (message_)); }
1,406
C++
.h
27
50.148148
205
0.764749
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,898
appinfo.hpp
TranslucentTB_TranslucentTB/Common/appinfo.hpp
#pragma once #include "util/string_macros.hpp" #if defined(BUILD_TYPE) && BUILD_TYPE == 0 #define UTF8_APP_NAME "TranslucentTB" #elif defined(BUILD_TYPE) && BUILD_TYPE == 1 #define UTF8_APP_NAME "TranslucentTB (Canary)" #else #define UTF8_APP_NAME "TranslucentTB (Dev)" #endif #define APP_NAME UTIL_WIDEN(UTF8_APP_NAME) #define APP_COPYRIGHT_YEAR_NUM 2024 #define APP_COPYRIGHT_YEAR UTIL_STRINGIFY(APP_COPYRIGHT_YEAR_NUM) #define APP_VERSION_FIXED 1,0,0,1 #define APP_VERSION UTIL_WIDEN("1.0.0.1")
502
C++
.h
14
34.571429
65
0.768595
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,899
version.hpp
TranslucentTB_TranslucentTB/Common/version.hpp
#pragma once #include "arch.h" #include <compare> #include <cstdint> #include <format> #include <string> #include <windef.h> #include <winbase.h> #include <appmodel.h> #include "winrt.hpp" #include <winrt/Windows.ApplicationModel.h> struct Version { uint16_t Major; uint16_t Minor; uint16_t Build; uint16_t Revision; static constexpr Version FromHighLow(DWORD high, DWORD low) { return { HIWORD(high), LOWORD(high), HIWORD(low), LOWORD(low) }; } static constexpr Version FromPackageVersion(winrt::Windows::ApplicationModel::PackageVersion version) { return { version.Major, version.Minor, version.Build, version.Revision }; } static constexpr Version FromPackageVersion(PACKAGE_VERSION version) { return { version.Major, version.Minor, version.Build, version.Revision }; } auto operator<=>(const Version &) const = default; }; template<> struct std::formatter<Version, wchar_t> : std::formatter<uint16_t, wchar_t> { private: template<typename FormatContext> static void insert_dot(FormatContext &fc) { auto o = fc.out(); *o = L'.'; ++o; fc.advance_to(std::move(o)); } public: template<typename FormatContext> auto format(Version v, FormatContext &fc) const { std::formatter<uint16_t, wchar_t>::format(v.Major, fc); insert_dot(fc); std::formatter<uint16_t, wchar_t>::format(v.Minor, fc); insert_dot(fc); std::formatter<uint16_t, wchar_t>::format(v.Build, fc); insert_dot(fc); return std::formatter<uint16_t, wchar_t>::format(v.Revision, fc); } };
1,503
C++
.h
54
25.777778
102
0.739945
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,900
win32.hpp
TranslucentTB_TranslucentTB/Common/win32.hpp
#pragma once #include "arch.h" #include <bit> #include <windef.h> #include <cstddef> #include <cstdint> #include <errhandlingapi.h> #include <filesystem> #include <memory> #include <libloaderapi.h> #include <processthreadsapi.h> #include <winbase.h> #include <shellapi.h> #include <Shlobj.h> #include <string> #include <string_view> #include <stringapiset.h> #include <sysinfoapi.h> #include <system_error> #include <unordered_set> #include <utility> #include <wil/resource.h> #include <wil/safecast.h> #include <wil/win32_helpers.h> #include <winerror.h> #include <wingdi.h> #include <winver.h> #include "constants.hpp" #include "util/hash.hpp" #include "util/null_terminated_string_view.hpp" #include "util/strings.hpp" #include "version.hpp" class win32 { private: static std::unique_ptr<std::byte[]> LoadFileVersionInfo(const std::filesystem::path &file, DWORD flags = 0) { const DWORD size = GetFileVersionInfoSizeEx(flags, file.c_str(), nullptr); if (!size) { return nullptr; } auto data = std::make_unique<std::byte[]>(size); if (!GetFileVersionInfoEx(flags, file.c_str(), 0, size, data.get())) { return nullptr; } return data; } public: // Gets location of the file of a process inline static std::pair<std::filesystem::path, HRESULT> GetProcessFileName(HANDLE process) { std::wstring exeLocation; HRESULT hr = S_OK; exeLocation.resize_and_overwrite(wil::max_extended_path_length, [process, &hr](wchar_t* data, std::size_t count) -> std::size_t { DWORD bufSize = static_cast<DWORD>(count) + 1; if (QueryFullProcessImageName(process, 0, data, &bufSize)) { return bufSize; } else { hr = HRESULT_FROM_WIN32(GetLastError()); return 0; } }); return { std::move(exeLocation), hr }; } // Gets location of current process inline static std::pair<std::filesystem::path, HRESULT> GetExeLocation() { return GetProcessFileName(GetCurrentProcess()); } // Gets the location of a loaded DLL inline static std::pair<std::filesystem::path, HRESULT> GetDllLocation(HMODULE hModule) { std::wstring location; HRESULT hr = S_OK; location.resize_and_overwrite(wil::max_extended_path_length, [hModule, &hr](wchar_t* data, std::size_t count) { const DWORD length = GetModuleFileName(hModule, data, static_cast<DWORD>(count) + 1); if (!length) [[unlikely]] { hr = HRESULT_FROM_WIN32(GetLastError()); } return length; }); return { std::move(location), hr }; } // Opens a file in the default text editor. inline static HRESULT EditFile(const std::filesystem::path &file) noexcept { SHELLEXECUTEINFO info = { .cbSize = sizeof(info), .fMask = SEE_MASK_CLASSNAME | SEE_MASK_FLAG_NO_UI, .lpVerb = L"open", .lpFile = file.c_str(), .nShow = SW_SHOW, .lpClass = L".txt" }; if (ShellExecuteEx(&info)) { return S_OK; } else { return HRESULT_FROM_WIN32(GetLastError()); } } // Gets the current Windows build identifier. // Unfortunately there is no good generic way to detect if a KB is installed. // Checking via WIM or the WU API only lists KBs installed since the OS // was clean installed, so if a KB superseding the one we are looking for // has been released, then the OS will directly install that and never list // the specific KB we want. We have to check the revision ID for that // but VerifyVersionInfo doesn't support checking revision ID, so we have // to manually read it off ntoskrnl.exe (which is the lesser evil compared // to calling a driver-only API like RtlGetVersion). // Prefer feature checking where possible - however sometimes for mundane // bug fixes or fixes/changes to undocumented feature that isn't possible. inline static std::pair<Version, HRESULT> GetWindowsBuild() { wil::unique_cotaskmem_string system32; const HRESULT hr = SHGetKnownFolderPath(FOLDERID_System, KF_FLAG_DEFAULT, nullptr, system32.put()); if (FAILED(hr)) { return { { }, hr }; } std::filesystem::path ntoskrnl = system32.get(); ntoskrnl /= L"ntoskrnl.exe"; return GetFixedFileVersion(ntoskrnl); } inline static bool IsAtLeastBuild(uint32_t buildNumber) noexcept { OSVERSIONINFOEX versionInfo = { sizeof(versionInfo), 10, 0, buildNumber }; DWORDLONG mask = 0; VER_SET_CONDITION(mask, VER_MAJORVERSION, VER_GREATER_EQUAL); VER_SET_CONDITION(mask, VER_MINORVERSION, VER_GREATER_EQUAL); VER_SET_CONDITION(mask, VER_BUILDNUMBER, VER_GREATER_EQUAL); return VerifyVersionInfo(&versionInfo, VER_MAJORVERSION | VER_MINORVERSION | VER_BUILDNUMBER, mask); } inline static bool IsExactBuild(uint32_t buildNumber) noexcept { OSVERSIONINFOEX versionInfo = { sizeof(versionInfo), 10, 0, buildNumber }; DWORDLONG mask = 0; VER_SET_CONDITION(mask, VER_MAJORVERSION, VER_EQUAL); VER_SET_CONDITION(mask, VER_MINORVERSION, VER_EQUAL); VER_SET_CONDITION(mask, VER_BUILDNUMBER, VER_EQUAL); return VerifyVersionInfo(&versionInfo, VER_MAJORVERSION | VER_MINORVERSION | VER_BUILDNUMBER, mask); } // Gets the language-neutral FileVersion of a PE binary. inline static std::pair<Version, HRESULT> GetFixedFileVersion(const std::filesystem::path &file) { const auto data = LoadFileVersionInfo(file, FILE_VER_GET_NEUTRAL); if (!data) { return { { }, HRESULT_FROM_WIN32(GetLastError()) }; } VS_FIXEDFILEINFO *fixedFileInfo; unsigned int length; if (!VerQueryValue(data.get(), L"\\", reinterpret_cast<void **>(&fixedFileInfo), &length)) { return { { }, HRESULT_FROM_WIN32(GetLastError()) }; } return { Version::FromHighLow(fixedFileInfo->dwProductVersionMS, fixedFileInfo->dwProductVersionLS), S_OK }; } // Gets the current processor architecture as a string. inline static Util::null_terminated_wstring_view GetProcessorArchitecture() noexcept { SYSTEM_INFO info; GetNativeSystemInfo(&info); switch (info.wProcessorArchitecture) { case PROCESSOR_ARCHITECTURE_AMD64: return L"x64"; case PROCESSOR_ARCHITECTURE_INTEL: return L"x86"; case PROCESSOR_ARCHITECTURE_ARM64: return L"ARM64"; case PROCESSOR_ARCHITECTURE_ARM: return L"ARM"; case PROCESSOR_ARCHITECTURE_IA64: return L"Itanium"; case PROCESSOR_ARCHITECTURE_UNKNOWN: return L"Unknown"; default: return L"Invalid"; } } static constexpr bool RectFitsInRect(const RECT &outer, const RECT &inner) noexcept { return inner.right <= outer.right && inner.left >= outer.left && outer.top <= inner.top && outer.bottom >= inner.bottom; } static constexpr void OffsetRect(RECT &rect, int x, int y) noexcept { rect.left += x; rect.right += x; rect.top += y; rect.bottom += y; } inline static bool IsSameFilename(std::wstring_view l, std::wstring_view r) { const int result = CompareStringOrdinal( l.data(), wil::safe_cast<int>(l.length()), r.data(), wil::safe_cast<int>(r.length()), true ); if (result) { return result == CSTR_EQUAL; } else { throw std::system_error(static_cast<int>(GetLastError()), std::system_category(), "Failed to compare strings"); } } struct FilenameEqual { using is_transparent = void; inline bool operator()(std::wstring_view l, std::wstring_view r) const { return IsSameFilename(l, r); } }; struct FilenameHash { using transparent_key_equal = FilenameEqual; inline std::size_t operator()(std::wstring_view k) const { std::size_t hash = Util::INITIAL_HASH_VALUE; for (std::size_t i = 0; i < k.length(); ++i) { if (Util::IsAscii(k[i])) { // if the string is all ascii characters, avoid API calls // this is much faster due to being branchless code Util::HashCharacter(hash, Util::AsciiToUpper(k[i])); } else { // when we encounter a non-ascii character, call an API to hash the rest and break out SlowHash(hash, k.substr(i)); break; } } return hash; } private: inline static void SlowHash(std::size_t &hash, std::wstring_view k) { std::wstring buf; buf.resize_and_overwrite(k.length(), [k](wchar_t* data, std::size_t count) { const int result = LCMapStringEx( LOCALE_NAME_INVARIANT, LCMAP_UPPERCASE, k.data(), wil::safe_cast<int>(k.length()), data, wil::safe_cast<int>(count), nullptr, nullptr, 0 ); if (result) { return result; } else { throw std::system_error(static_cast<int>(GetLastError()), std::system_category(), "Failed to hash string"); } }); for (const wchar_t &c : buf) { Util::HashCharacter(hash, c); } } }; using FilenameSet = std::unordered_set<std::wstring, FilenameHash, FilenameEqual>; template<typename T> using FilenameMap = std::unordered_map<std::wstring, T, FilenameHash, FilenameEqual>; };
8,712
C++
.h
278
28.219424
129
0.714184
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false
4,901
constants.hpp
TranslucentTB_TranslucentTB/Common/constants.hpp
#pragma once #include "arch.h" #include <cstdint> #include <guiddef.h> #include "util/null_terminated_string_view.hpp" #pragma region App // Mutex name for app uniqueness static constexpr Util::null_terminated_wstring_view MUTEX_GUID = L"344635E9-9AE4-4E60-B128-D53E25AB70A7"; // Event used to signal when the TAP is ready static constexpr Util::null_terminated_wstring_view TAP_READY_EVENT = L"TTBTAP_Ready"; // Current version of the API used for IPC with the TAP static constexpr std::uint32_t TAP_API_VERSION = 2; // Tray icon GUID static constexpr GUID TRAY_GUID = { 0x2EA4687, 0xE0EC, 0x4B84, { 0x9B, 0x68, 0xBD, 0x1B, 0xB4, 0xCC, 0xD2, 0x24 } }; // GUID of payload injected in Explorer static constexpr GUID EXPLORER_PAYLOAD = { 0xF5E0B1A9, 0x9D5D, 0x4EB3, { 0x8F, 0x6D, 0x1F, 0x4D, 0x43, 0xD7, 0xCD, 0x0E } }; #pragma endregion #pragma region Messages // Message sent by explorer when the taskbar is created static constexpr Util::null_terminated_wstring_view WM_TASKBARCREATED = L"TaskbarCreated"; // Sent by the hook to the worker when the taskbar is trying to change its composition attribute static constexpr Util::null_terminated_wstring_view WM_TTBHOOKREQUESTREFRESH = L"TTBHook_RequestAttributeRefresh"; // Sent by the hook to the worker when Task View closes/opens static constexpr Util::null_terminated_wstring_view WM_TTBHOOKTASKVIEWVISIBILITYCHANGE = L"TTBHook_TaskViewVisibilityChange"; // Sent by the worker to the hook to get the current Task View status static constexpr Util::null_terminated_wstring_view WM_TTBHOOKISTASKVIEWOPENED = L"TTBHook_IsTaskViewOpened"; // Sent by LauncherVisibilitySink when the start menu opens/closes static constexpr Util::null_terminated_wstring_view WM_TTBSTARTVISIBILITYCHANGE = L"TTB_StartVisibilityChange"; // Sent by TaskbarAttributeWorker to itself to switch back to main thread static constexpr Util::null_terminated_wstring_view WM_TTBSEARCHVISIBILITYCHANGE = L"TTB_SearchVisibilityChange"; // Sent to the worker to force the taskbar to toggle to normal and back to the expected appearance static constexpr Util::null_terminated_wstring_view WM_TTBFORCEREFRESHTASKBAR = L"TTB_ForceRefreshTaskbar"; // Sent by another instance of TranslucentTB to signal that it was started while this instance is running. static constexpr Util::null_terminated_wstring_view WM_TTBNEWINSTANCESTARTED = L"TTB_NewInstanceStarted"; #pragma endregion #pragma region Window classes // Window class used by our tray icon static constexpr Util::null_terminated_wstring_view TRAY_WINDOW = L"TrayWindow"; // Window class and title used by our attribute worker static constexpr Util::null_terminated_wstring_view TTB_WORKERWINDOW = L"TTB_WorkerWindow"; // Window class and title used by the Task View monitor static constexpr Util::null_terminated_wstring_view TTBHOOK_TASKVIEWMONITOR = L"TTBHook_TaskViewMonitor"; // Window class for taskbar on primary monitor static constexpr Util::null_terminated_wstring_view TASKBAR = L"Shell_TrayWnd"; // Window class for taskbars on other monitors static constexpr Util::null_terminated_wstring_view SECONDARY_TASKBAR = L"Shell_SecondaryTrayWnd"; // Window class used by UWP static constexpr Util::null_terminated_wstring_view CORE_WINDOW = L"Windows.UI.Core.CoreWindow"; #pragma endregion #pragma region Other // UTF-8 Byte Order Mark static constexpr Util::null_terminated_string_view UTF8_BOM = "\xEF\xBB\xBF"; // Serialization Keys static constexpr std::wstring_view CLASS_KEY = L"window_class"; static constexpr std::wstring_view TITLE_KEY = L"window_title"; static constexpr std::wstring_view FILE_KEY = L"process_name"; #pragma endregion
3,651
C++
.h
57
62.526316
125
0.8078
TranslucentTB/TranslucentTB
15,526
1,125
171
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
true
false
false