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,902
|
simplefactory.hpp
|
TranslucentTB_TranslucentTB/Common/simplefactory.hpp
|
#pragma once
#include <Unknwn.h>
#include "winrt.hpp"
template<class T>
struct SimpleFactory : winrt::implements<SimpleFactory<T>, IClassFactory, winrt::non_agile>
{
HRESULT STDMETHODCALLTYPE CreateInstance(IUnknown* pUnkOuter, REFIID riid, void** ppvObject) override try
{
if (!pUnkOuter)
{
*ppvObject = nullptr;
return winrt::make<T>().as(riid, ppvObject);
}
else
{
return CLASS_E_NOAGGREGATION;
}
}
catch (...)
{
return winrt::to_hresult();
}
HRESULT STDMETHODCALLTYPE LockServer(BOOL fLock) noexcept override
{
if (fLock)
{
++winrt::get_module_lock();
}
else
{
--winrt::get_module_lock();
}
return S_OK;
}
};
| 668
|
C++
|
.h
| 35
| 16.514286
| 106
| 0.703175
|
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,903
|
undefgetcurrenttime.h
|
TranslucentTB_TranslucentTB/Common/undefgetcurrenttime.h
|
#ifndef GET_CURRENT_TIME_UNDEFINED
# ifdef GetCurrentTime
# pragma push_macro("GetCurrentTime")
# undef GetCurrentTime
# define GET_CURRENT_TIME_UNDEFINED
# else
# error "GetCurrentTime is not defined"
# endif
#else
# error "GetCurrentTime has already been undefined"
#endif
| 279
|
C++
|
.h
| 11
| 24.363636
| 51
| 0.80597
|
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,904
|
arch.h
|
TranslucentTB_TranslucentTB/Common/arch.h
|
#pragma once
// Those are defines required by various Windows headers to build.
#if defined(_M_AMD64)
# ifndef _AMD64_
# define _AMD64_
# endif
#elif defined(_M_ARM64)
# ifndef _ARM64_
# define _ARM64_
# endif
#else
# error "Target architecture not recognized"
#endif
| 272
|
C++
|
.h
| 13
| 19.769231
| 66
| 0.754864
|
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,905
|
wilx.hpp
|
TranslucentTB_TranslucentTB/Common/wilx.hpp
|
#pragma once
#include "arch.h"
#include <cstddef>
#include <tuple>
#include <type_traits>
#include <utility>
#include <wil/resource.h>
#include <winnt.h>
#include "util/concepts.hpp"
namespace wilx {
// Send help
namespace impl {
template<typename T>
struct function_traits;
template<typename Parent, typename Return, typename... Args>
struct function_traits<Return(STDMETHODCALLTYPE Parent:: *)(Args...)> {
using parent = Parent;
template<std::size_t I>
using arg = std::tuple_element_t<I, std::tuple<Args...>>;
};
template<typename Parent, typename Return, typename... Args>
struct function_traits<Return(STDMETHODCALLTYPE Parent:: *)(Args...) noexcept> {
using parent = Parent;
template<std::size_t I>
using arg = std::tuple_element_t<I, std::tuple<Args...>>;
};
template<typename Return, typename... Args>
struct function_traits<Return(STDMETHODCALLTYPE *)(Args...)> {
template<std::size_t I>
using arg = std::tuple_element_t<I, std::tuple<Args...>>;
};
template<typename Return, typename... Args>
struct function_traits<Return(STDMETHODCALLTYPE *)(Args...) noexcept> {
template<std::size_t I>
using arg = std::tuple_element_t<I, std::tuple<Args...>>;
};
template<typename T>
using parent_t = typename function_traits<T>::parent;
template<typename T, std::size_t I>
using arg_t = typename function_traits<T>::template arg<I>;
}
template<auto close_fn, impl::arg_t<decltype(close_fn), 0> invalid_token = {}>
requires std::is_member_function_pointer_v<decltype(close_fn)>
using unique_com_token = wil::unique_com_token<impl::parent_t<decltype(close_fn)>, decltype(invalid_token), decltype(close_fn), close_fn, invalid_token>;
template<auto close_fn>
requires std::is_member_function_pointer_v<decltype(close_fn)>
using unique_com_call = wil::unique_com_call<impl::parent_t<decltype(close_fn)>, decltype(close_fn), close_fn>;
template<Util::function_pointer auto close_fn>
using unique_any = wil::unique_any<impl::arg_t<decltype(close_fn), 0>, decltype(close_fn), close_fn>;
template<Util::function_pointer auto close_fn>
using unique_any_handle_invalid = wil::unique_any_handle_invalid<decltype(close_fn), close_fn>;
template<Util::function_pointer auto close_fn>
using unique_call = wil::unique_call<decltype(close_fn), close_fn>;
template<Util::function_pointer auto delete_fn>
using function_deleter = wil::function_deleter<decltype(delete_fn), delete_fn>;
}
| 2,463
|
C++
|
.h
| 56
| 41.214286
| 154
| 0.72982
|
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,906
|
redefgetcurrenttime.h
|
TranslucentTB_TranslucentTB/Common/redefgetcurrenttime.h
|
#ifdef GET_CURRENT_TIME_UNDEFINED
# pragma pop_macro("GetCurrentTime")
# undef GET_CURRENT_TIME_UNDEFINED
#else
# error "GetCurrentTime has not been undefined"
#endif
| 167
|
C++
|
.h
| 6
| 26.833333
| 47
| 0.813665
|
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,907
|
winrt.hpp
|
TranslucentTB_TranslucentTB/Common/winrt.hpp
|
#pragma once
#include <guiddef.h>
#include <Unknwn.h>
#include <winrt/base.h>
// forward declare namespaces we alias
namespace winrt {
namespace Microsoft::UI::Xaml::Controls {}
namespace TranslucentTB::Xaml::Models::Primitives {}
namespace Windows {
namespace ApplicationModel {}
namespace Foundation::Collections {}
namespace UI::Xaml {
namespace Controls {}
namespace Hosting {}
}
}
}
// alias some long namespaces for convenience
namespace mux = winrt::Microsoft::UI::Xaml;
namespace muxc = winrt::Microsoft::UI::Xaml::Controls;
namespace txmp = winrt::TranslucentTB::Xaml::Models::Primitives;
namespace wam = winrt::Windows::ApplicationModel;
namespace wf = winrt::Windows::Foundation;
namespace wfc = wf::Collections;
namespace wux = winrt::Windows::UI::Xaml;
namespace wuxc = wux::Controls;
namespace wuxh = wux::Hosting;
| 849
|
C++
|
.h
| 27
| 29.703704
| 64
| 0.768293
|
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,908
|
numbers.hpp
|
TranslucentTB_TranslucentTB/Common/util/numbers.hpp
|
#pragma once
#include <concepts>
#include <cstddef>
#include <cstdint>
#include <limits>
#include <stdexcept>
#include <string_view>
#include "strings.hpp"
namespace Util {
namespace impl {
constexpr bool IsDecimalDigit(wchar_t character)
{
return character >= L'0' && character <= L'9';
}
constexpr bool IsUpperHexDigit(wchar_t character)
{
return character >= L'A' && character <= L'F';
}
constexpr bool IsLowerHexDigit(wchar_t character)
{
return character >= L'a' && character <= L'f';
}
}
// Apparently no wide string to number parser accepted an explicit ending to the string
// so here I am. Also C locales sucks.
template<std::unsigned_integral T = uint32_t>
constexpr T ParseHexNumber(std::wstring_view number)
{
TrimInplace(number);
if (number.empty())
{
throw std::invalid_argument("Cannot convert empty string to number");
}
if (number.length() > 2 && number[0] == L'0' && (number[1] == L'x' || number[1] == L'X'))
{
number.remove_prefix(2);
}
if (number.length() > std::numeric_limits<T>::digits / 4)
{
throw std::out_of_range("Number being converted is off-limits");
}
T result { };
for (std::size_t i = 0; i < number.length(); i++)
{
const T power = static_cast<T>(1) << ((number.length() - i - 1) * 4);
if (impl::IsDecimalDigit(number[i]))
{
result += static_cast<T>(number[i] - L'0') * power;
}
else if (impl::IsUpperHexDigit(number[i]))
{
result += static_cast<T>(number[i] - L'A' + 10) * power;
}
else if (impl::IsLowerHexDigit(number[i]))
{
result += static_cast<T>(number[i] - L'a' + 10) * power;
}
else
{
throw std::invalid_argument("Not a number");
}
}
return result;
}
constexpr uint8_t ExpandOneHexDigitByte(uint8_t byte)
{
const uint8_t firstDigit = byte & 0xF;
return (firstDigit << 4) + firstDigit;
}
}
| 1,878
|
C++
|
.h
| 70
| 23.728571
| 91
| 0.652755
|
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,909
|
maybe_delete.hpp
|
TranslucentTB_TranslucentTB/Common/util/maybe_delete.hpp
|
#pragma once
namespace Util {
struct maybe_delete {
private:
bool m_ShouldDelete;
public:
template<class T>
void operator()(T *that) const noexcept
{
if (m_ShouldDelete)
{
delete that;
}
}
maybe_delete(bool shouldDelete) noexcept : m_ShouldDelete(shouldDelete) { }
};
}
| 302
|
C++
|
.h
| 17
| 14.882353
| 77
| 0.705674
|
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,910
|
type_traits.hpp
|
TranslucentTB_TranslucentTB/Common/util/type_traits.hpp
|
#pragma once
#include <type_traits>
namespace Util {
template<typename T>
class decay_array {
using U = std::remove_reference_t<T>;
public:
using type = std::conditional_t<std::is_array_v<U>, std::remove_extent_t<U>*, T>;
};
template<typename T>
using decay_array_t = typename decay_array<T>::type;
template<typename T>
inline constexpr bool is_optional_v = false;
template<typename T>
inline constexpr bool is_optional_v<std::optional<T>> = true;
template<typename T>
struct is_optional : std::bool_constant<is_optional_v<T>> {};
}
| 555
|
C++
|
.h
| 18
| 28.611111
| 83
| 0.73258
|
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,911
|
thread_independent_mutex.hpp
|
TranslucentTB_TranslucentTB/Common/util/thread_independent_mutex.hpp
|
#pragma once
#include <chrono>
#include <semaphore>
namespace Util {
class thread_independent_mutex {
std::binary_semaphore semaphore;
public:
constexpr thread_independent_mutex() noexcept /* strengthened */ : semaphore(1) { }
void lock() noexcept /* strengthened */
{
semaphore.acquire();
}
void unlock() noexcept /* strengthened */
{
semaphore.release();
}
bool try_lock() noexcept
{
return semaphore.try_acquire();
}
template<class Rep, class Period>
bool try_lock_for(const std::chrono::duration<Rep, Period> &time)
{
return semaphore.try_acquire_for(time);
}
template<class Clock, class Duration>
bool try_lock_until(const std::chrono::time_point<Clock, Duration> &time)
{
return semaphore.try_acquire_until(time);
}
};
}
| 790
|
C++
|
.h
| 32
| 21.71875
| 85
| 0.713715
|
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,912
|
color.hpp
|
TranslucentTB_TranslucentTB/Common/util/color.hpp
|
#pragma once
#include <bit>
#include <cstdint>
#include <format>
#include <stdexcept>
#include <string>
#include <string_view>
#include "../winrt.hpp"
#include <winrt/Windows.Foundation.Numerics.h>
#include <winrt/Windows.UI.h>
#include "numbers.hpp"
#include "strings.hpp"
#if __has_include(<winrt/TranslucentTB.Xaml.Models.Primitives.h>)
#define HAS_WINRT_COLOR
#include <winrt/TranslucentTB.Xaml.Models.Primitives.h>
#endif
namespace Util {
struct HsvColor {
double H, S, V, A;
constexpr HsvColor() noexcept : H(0), S(0), V(0), A(0) { }
constexpr HsvColor(double h, double s, double v, double a = 1.0) noexcept : H(h), S(s), V(v), A(a) { }
constexpr HsvColor(const wf::Numerics::float4 &col) noexcept : H(col.x), S(col.y), V(col.z), A(col.w) { }
#ifdef HAS_WINRT_COLOR
constexpr HsvColor(txmp::HsvColor col) noexcept : H(col.H), S(col.S), V(col.V), A(col.A) { }
constexpr operator txmp::HsvColor() const noexcept
{
return { .H = H, .S = S, .V = V, .A = A };
}
#endif
constexpr operator wf::Numerics::float4() const noexcept
{
return {
static_cast<float>(H),
static_cast<float>(S),
static_cast<float>(V),
static_cast<float>(A)
};
}
};
struct Color {
uint8_t R, G, B, A;
constexpr Color() noexcept : R(0), G(0), B(0), A(0) { }
constexpr Color(uint8_t r, uint8_t g, uint8_t b, uint8_t a = 255) noexcept : R(r), G(g), B(b), A(a) { }
constexpr Color(winrt::Windows::UI::Color col) noexcept : Color(std::bit_cast<Color>(std::rotr(std::bit_cast<uint32_t>(col), 8))) { }
constexpr uint32_t ToRGBA() const noexcept
{
return SwapBytes(ToABGR());
}
constexpr uint32_t ToABGR() const noexcept
{
return std::bit_cast<uint32_t>(*this);
}
constexpr Color Premultiply() const noexcept
{
return {
FastPremultiply(R, A),
FastPremultiply(G, A),
FastPremultiply(B, A),
A
};
}
inline HsvColor ToHSV() const
{
static constexpr double toDouble = 1.0 / 255.0;
const double r = toDouble * R;
const double g = toDouble * G;
const double b = toDouble * B;
const double max = std::max({ r, g, b });
const double min = std::min({ r, g, b });
const double chroma = max - min;
double h1;
if (chroma == 0.0)
{
h1 = 0.0;
}
else if (max == r)
{
// fmod doesn't do proper modulo on negative
// numbers, so we'll add 6 before using it
h1 = std::fmod(((g - b) / chroma) + 6.0, 6.0);
}
else if (max == g)
{
h1 = 2.0 + ((b - r) / chroma);
}
else
{
h1 = 4.0 + ((r - g) / chroma);
}
const double saturation = chroma == 0.0 ? 0.0 : chroma / max;
return { 60.0 * h1, saturation, max, toDouble * A };
}
inline std::wstring ToString() const
{
return std::format(L"#{:08X}", ToRGBA());
}
constexpr static Color FromString(std::wstring_view str, bool allowNoPrefix = false)
{
Util::TrimInplace(str);
if (str.starts_with(L'#'))
{
str.remove_prefix(1);
}
else if (!allowNoPrefix)
{
throw std::invalid_argument("Not a valid color");
}
if (str.length() == 3)
{
const uint16_t col = Util::ParseHexNumber<uint16_t>(str);
const uint8_t r = Util::ExpandOneHexDigitByte((col & 0xF00) >> 8);
const uint8_t g = Util::ExpandOneHexDigitByte((col & 0xF0) >> 4);
const uint8_t b = Util::ExpandOneHexDigitByte(col & 0xF);
return Color { r, g, b };
}
else if (str.length() == 4)
{
const auto col = Util::ParseHexNumber<uint16_t>(str);
const uint8_t r = Util::ExpandOneHexDigitByte((col & 0xF000) >> 12);
const uint8_t g = Util::ExpandOneHexDigitByte((col & 0xF00) >> 8);
const uint8_t b = Util::ExpandOneHexDigitByte((col & 0xF0) >> 4);
const uint8_t a = Util::ExpandOneHexDigitByte(col & 0xF);
return Color { r, g, b, a };
}
else if (str.length() == 6)
{
return FromRGBA(Util::ParseHexNumber<uint32_t>(str) << 8 | 0xFF);
}
else if (str.length() == 8)
{
return FromRGBA(Util::ParseHexNumber<uint32_t>(str));
}
else
{
throw std::invalid_argument("Not a valid color");
}
}
constexpr static Color FromRGBA(uint32_t col) noexcept
{
return std::bit_cast<Color>(SwapBytes(col));
}
constexpr static Color FromABGR(uint32_t col) noexcept
{
return std::bit_cast<Color>(col);
}
inline static Color FromHSV(double hue, double saturation, double value, double alpha = 1.0)
{
if (hue < 0 || hue > 360)
{
throw std::out_of_range("hue must be between 0 and 360");
}
const double chroma = value * saturation;
const double h1 = hue / 60.0;
const double x = chroma * (1.0 - std::abs(std::fmod(h1, 2.0) - 1.0));
const double m = value - chroma;
double r1, g1, b1;
if (h1 < 1.0)
{
r1 = chroma;
g1 = x;
b1 = 0.0;
}
else if (h1 < 2.0)
{
r1 = x;
g1 = chroma;
b1 = 0.0;
}
else if (h1 < 3.0)
{
r1 = 0.0;
g1 = chroma;
b1 = x;
}
else if (h1 < 4.0)
{
r1 = 0.0;
g1 = x;
b1 = chroma;
}
else if (h1 < 5.0)
{
r1 = x;
g1 = 0.0;
b1 = chroma;
}
else
{
r1 = chroma;
g1 = 0.0;
b1 = x;
}
return {
static_cast<uint8_t>(255.0 * (r1 + m)),
static_cast<uint8_t>(255.0 * (g1 + m)),
static_cast<uint8_t>(255.0 * (b1 + m)),
static_cast<uint8_t>(255.0 * alpha)
};
}
inline static Color FromHSV(const HsvColor &hsvColor)
{
return FromHSV(hsvColor.H, hsvColor.S, hsvColor.V, hsvColor.A);
}
constexpr operator winrt::Windows::UI::Color() const noexcept
{
return std::bit_cast<winrt::Windows::UI::Color>(std::rotl(ToABGR(), 8));
}
constexpr bool operator ==(Color other) const noexcept
{
return ToABGR() == other.ToABGR();
}
double Luminance() const noexcept
{
const double rg = R <= 10 ? R / 3294.0 : std::pow((R / 269.0) + 0.0513, 2.4);
const double gg = G <= 10 ? G / 3294.0 : std::pow((G / 269.0) + 0.0513, 2.4);
const double bg = B <= 10 ? B / 3294.0 : std::pow((B / 269.0) + 0.0513, 2.4);
return (0.2126 * rg) + (0.7152 * gg) + (0.0722 * bg);
}
bool IsDarkColor() const noexcept
{
return Luminance() <= 0.5;
}
private:
static constexpr uint8_t FastPremultiply(uint8_t x, uint8_t frac) noexcept
{
// magic that avoids a division.
return static_cast<uint8_t>(static_cast<uint32_t>(x * frac * 0x8081) >> 23);
}
static constexpr uint32_t SwapBytes(uint32_t num) noexcept
{
return (num >> 24) | ((num & 0xFF0000) >> 8) | ((num & 0xFF00) << 8) | (num << 24);
}
};
}
| 6,514
|
C++
|
.h
| 234
| 24.021368
| 135
| 0.610924
|
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,913
|
hash.hpp
|
TranslucentTB_TranslucentTB/Common/util/hash.hpp
|
#pragma once
#include <cstddef>
#include <cstdint>
namespace Util {
#ifdef _WIN64
namespace impl {
static constexpr std::size_t FNV_PRIME = 0x100000001B3;
}
static constexpr std::size_t INITIAL_HASH_VALUE = 0xCBF29CE484222325;
#else
namespace impl {
static constexpr std::size_t FNV_PRIME = 0x1000193;
}
static constexpr std::size_t INITIAL_HASH_VALUE = 0x811C9DC5;
#endif
constexpr void HashByte(std::size_t &h, uint8_t b) noexcept
{
h ^= b;
h *= impl::FNV_PRIME;
}
constexpr void HashCharacter(std::size_t &h, wchar_t c) noexcept
{
HashByte(h, static_cast<uint8_t>((c & 0xFF00) >> 8));
HashByte(h, c & 0xFF);
}
}
| 644
|
C++
|
.h
| 26
| 22.653846
| 70
| 0.722675
|
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,914
|
string_macros.hpp
|
TranslucentTB_TranslucentTB/Common/util/string_macros.hpp
|
#pragma once
#define UTIL_WIDEN_INNER(x) L##x
#define UTIL_WIDEN(x) UTIL_WIDEN_INNER(x)
#define UTIL_STRINGIFY_INNER(x) #x
#define UTIL_STRINGIFY(x) UTIL_WIDEN(UTIL_STRINGIFY_INNER(x))
#define UTIL_STRINGIFY_UTF8(x) UTIL_STRINGIFY_INNER(x)
| 241
|
C++
|
.h
| 6
| 39
| 61
| 0.773504
|
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,915
|
concepts.hpp
|
TranslucentTB_TranslucentTB/Common/util/concepts.hpp
|
#pragma once
#include <type_traits>
namespace Util {
template<typename T>
concept function_pointer = std::is_pointer_v<T> && std::is_function_v<std::remove_pointer_t<T>>;
}
| 176
|
C++
|
.h
| 6
| 27.833333
| 97
| 0.739645
|
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,916
|
null_terminated_string_view.hpp
|
TranslucentTB_TranslucentTB/Common/util/null_terminated_string_view.hpp
|
#pragma once
#include <format>
#include <string>
#include <string_view>
namespace Util {
template<typename char_type, class traits = std::char_traits<char_type>>
class basic_null_terminated_string_view : public std::basic_string_view<char_type, traits> {
using base = std::basic_string_view<char_type, traits>;
constexpr basic_null_terminated_string_view(const typename base::const_pointer str, const typename base::size_type length) noexcept :
base(str, length)
{ }
public:
using base::base;
constexpr void remove_suffix(const typename base::size_type) noexcept = delete;
constexpr base substr(const typename base::size_type, typename base::size_type) const = delete;
template<class allocator>
constexpr basic_null_terminated_string_view(const std::basic_string<char_type, traits, allocator> &str) :
base(str.c_str(), str.length())
{ }
constexpr typename base::const_pointer c_str() const noexcept
{
return base::data();
}
// only call this if you're sure it actually is terminated by a null pointer.
static constexpr basic_null_terminated_string_view make_unsafe(const typename base::const_pointer str, const typename base::size_type length) noexcept
{
return { str, length };
}
};
using null_terminated_string_view = basic_null_terminated_string_view<char>;
using null_terminated_u8string_view = basic_null_terminated_string_view<char8_t>;
using null_terminated_u16string_view = basic_null_terminated_string_view<char16_t>;
using null_terminated_u32string_view = basic_null_terminated_string_view<char32_t>;
using null_terminated_wstring_view = basic_null_terminated_string_view<wchar_t>;
}
template<typename char_type, class traits>
struct std::formatter<Util::basic_null_terminated_string_view<char_type, traits>, char_type> : std::formatter<std::basic_string_view<char_type, traits>, char_type>
{};
| 1,867
|
C++
|
.h
| 38
| 46.5
| 163
| 0.764835
|
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,917
|
strings.hpp
|
TranslucentTB_TranslucentTB/Common/util/strings.hpp
|
#pragma once
#include <cassert>
#include <cstddef>
#include <iterator>
#include <string>
#include <string_view>
namespace Util {
namespace impl {
// https://en.cppreference.com/w/cpp/string/wide/iswspace
static constexpr std::wstring_view WHITESPACES = L" \f\n\r\t\v";
}
constexpr bool IsAscii(wchar_t c)
{
return (c & ~0x007F) == 0;
}
constexpr wchar_t AsciiToUpper(wchar_t c)
{
assert(IsAscii(c));
const wchar_t lower = c + 0x0080 - 0x0061;
const wchar_t upper = c + 0x0080 - 0x007B;
const wchar_t combined = lower ^ upper;
const wchar_t mask = (combined & 0x0080) >> 2;
return c ^ mask;
}
// Removes instances of a character at the beginning and end of the string.
constexpr std::wstring_view Trim(std::wstring_view str, std::wstring_view characters = impl::WHITESPACES)
{
const std::size_t first = str.find_first_not_of(characters);
if (first != std::wstring_view::npos)
{
const std::size_t last = str.find_last_not_of(characters);
return str.substr(first, last - first + 1);
}
else
{
return { };
}
}
// Removes instances of a character at the beginning and end of the string.
constexpr void TrimInplace(std::wstring_view &str, std::wstring_view characters = impl::WHITESPACES)
{
const std::size_t first = str.find_first_not_of(characters);
if (first != std::wstring_view::npos)
{
str.remove_prefix(first);
const std::size_t last = str.find_last_not_of(characters);
str.remove_suffix(str.length() - last - 1);
}
else
{
str = { };
}
}
// Removes instances of a character at the beginning and end of the string.
inline void TrimInplace(std::wstring &str, std::wstring_view characters = impl::WHITESPACES)
{
const std::size_t first = str.find_first_not_of(characters);
if (first != std::wstring::npos)
{
const std::size_t last = str.find_last_not_of(characters);
str.erase(last + 1);
str.erase(0, first);
}
else
{
str.erase();
}
}
}
| 1,959
|
C++
|
.h
| 69
| 25.57971
| 106
| 0.691693
|
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,918
|
winternl.hpp
|
TranslucentTB_TranslucentTB/Common/undoc/winternl.hpp
|
#pragma once
#include "../arch.h"
#include <windef.h>
#include <winternl.h>
// UserDefinedType: _SYSTEM_PROCESS_ID_INFORMATION
// Data : this+0x0, Member, Type: void *, ProcessId
// Data : this+0x8, Member, Type: struct _UNICODE_STRING, ImageName
struct SYSTEM_PROCESS_ID_INFORMATION {
PVOID ProcessId;
UNICODE_STRING ImageName;
};
// Enum : _SYSTEM_INFORMATION_CLASS, Type: int
// Data : constant 0x0, Constant, Type: int, SystemBasicInformation
// Data : constant 0x1, Constant, Type: int, SystemProcessorInformation
// Data : constant 0x2, Constant, Type: int, SystemPerformanceInformation
// ...
// Data : constant 0x58, Constant, Type: int, SystemProcessIdInformation
// ...
// Data : constant 0xE4, Constant, Type: int, MaxSystemInfoClass
enum SYSTEM_INFORMATION_CLASS_UNDOC : INT {
SystemProcessIdInformation = 0x58
};
// This is normally defined in ntstatus.h but that header conflicts with user mode headers
static constexpr NTSTATUS STATUS_INFO_LENGTH_MISMATCH_UNDOC = 0xC0000004L;
typedef __kernel_entry NTSTATUS (NTAPI* PFN_NT_QUERY_SYSTEM_INFORMATION)(IN SYSTEM_INFORMATION_CLASS SystemInformationClass, OUT PVOID SystemInformation, IN ULONG SystemInformationLength, OUT PULONG ReturnLength OPTIONAL);
| 1,325
|
C++
|
.h
| 25
| 51.72
| 222
| 0.722994
|
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,919
|
winuser.hpp
|
TranslucentTB_TranslucentTB/Common/undoc/winuser.hpp
|
#pragma once
#include "../arch.h"
#include <windef.h>
static constexpr DWORD EVENT_SYSTEM_PEEKSTART = 0x0021;
static constexpr DWORD EVENT_SYSTEM_PEEKEND = 0x0022;
| 167
|
C++
|
.h
| 5
| 32.2
| 55
| 0.782609
|
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,920
|
explorer.hpp
|
TranslucentTB_TranslucentTB/Common/undoc/explorer.hpp
|
#pragma once
#include "../arch.h"
#include <guiddef.h>
#include <rpcndr.h>
#include <Unknwn.h>
#include <windef.h>
#include <winerror.h>
static constexpr CLSID CLSID_ImmersiveShell = { 0xC2F03A33, 0x21F5, 0x47FA, { 0xB4, 0xBB, 0x15, 0x63, 0x62, 0xA2, 0xF2, 0x39 } };
static constexpr GUID SID_MultitaskingViewVisibilityService = { 0x785702DD, 0xB8EF, 0x469F, { 0x8C, 0x19, 0xE9, 0x1B, 0x5F, 0x4C, 0xA5, 0x64 } };
static constexpr wchar_t SEH_Cortana[] = L"Windows.Internal.ShellExperience.Cortana";
static constexpr wchar_t SEH_SearchApp[] = L"Windows.Internal.ShellExperience.SearchApp";
enum MULTITASKING_VIEW_TYPES : INT {
MVT_NONE = 0x0,
MVT_ALT_TAB_VIEW = 0x1,
MVT_ALL_UP_VIEW = 0x2,
MVT_SNAP_ASSIST_VIEW = 0x4,
MVT_PPI_ALL_UP_VIEW = 0x8, // this is used by Windows 10 Team, so not of interest to us
MVT_ANY = 0xF
};
MIDL_INTERFACE("c59a7a3c-0676-4526-8192-5d0bf9b89b95")
IMultitaskingViewVisibilityNotification : public IUnknown {
public:
virtual HRESULT STDMETHODCALLTYPE MultitaskingViewShown(MULTITASKING_VIEW_TYPES flags) = 0;
virtual HRESULT STDMETHODCALLTYPE MultitaskingViewDismissed(MULTITASKING_VIEW_TYPES flags) = 0;
};
MIDL_INTERFACE("ac11cda3-1601-4ad7-a40e-fe2ced187307")
IMultitaskingViewVisibilityService : public IUnknown {
public:
virtual HRESULT STDMETHODCALLTYPE IsViewVisible(MULTITASKING_VIEW_TYPES flags, MULTITASKING_VIEW_TYPES *retFlags) = 0;
virtual HRESULT STDMETHODCALLTYPE Register(IMultitaskingViewVisibilityNotification *pVisibilityNotification, DWORD *pdwCookie) = 0;
virtual HRESULT STDMETHODCALLTYPE Unregister(DWORD dwCookie) = 0;
};
| 1,589
|
C++
|
.h
| 32
| 48.1875
| 145
| 0.795235
|
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,921
|
user32.hpp
|
TranslucentTB_TranslucentTB/Common/undoc/user32.hpp
|
#pragma once
#include "../arch.h"
#include <windef.h>
// Enum : ACCENT_STATE, Type: int
// Data : constant 0x0, Constant, Type: int, ACCENT_DISABLED
// Data : constant 0x1, Constant, Type: int, ACCENT_ENABLE_GRADIENT
// Data : constant 0x2, Constant, Type: int, ACCENT_ENABLE_TRANSPARENTGRADIENT
// Data : constant 0x3, Constant, Type: int, ACCENT_ENABLE_BLURBEHIND
// Data : constant 0x4, Constant, Type: int, ACCENT_ENABLE_ACRYLICBLURBEHIND
// Data : constant 0x5, Constant, Type: int, ACCENT_ENABLE_HOSTBACKDROP
// Data : constant 0x6, Constant, Type: int, ACCENT_INVALID_STATE
enum ACCENT_STATE : INT { // Affects the rendering of the background of a window.
ACCENT_DISABLED = 0, // Default value. Background is black.
ACCENT_ENABLE_GRADIENT = 1, // Background is GradientColor, alpha channel ignored.
ACCENT_ENABLE_TRANSPARENTGRADIENT = 2, // Background is GradientColor.
ACCENT_ENABLE_BLURBEHIND = 3, // Background is GradientColor, with blur effect.
ACCENT_ENABLE_ACRYLICBLURBEHIND = 4, // Background is GradientColor, with acrylic blur effect.
ACCENT_ENABLE_HOSTBACKDROP = 5, // Allows desktop apps to use Compositor.CreateHostBackdropBrush
ACCENT_INVALID_STATE = 6, // Unknown. Seems to draw background fully transparent.
ACCENT_NORMAL = 0x0 // Fake value: tells TTB to send a message to the taskbar for it restore its default effect.
};
// UserDefinedType: ACCENT_POLICY
// Data : this+0x0, Member, Type: enum ACCENT_STATE, AccentState
// Data : this+0x4, Member, Type: unsigned int, AccentFlags
// Data : this+0x8, Member, Type: unsigned long, GradientColor
// Data : this+0xC, Member, Type: long, AnimationId
struct ACCENT_POLICY { // Determines how a window's background is rendered.
ACCENT_STATE AccentState; // Background effect.
UINT AccentFlags; // Flags. Set to 2 to tell GradientColor is used, rest is unknown.
COLORREF GradientColor; // Background color.
LONG AnimationId; // Unknown
};
// Enum : WINDOWCOMPOSITIONATTRIB, Type: int
// Data : constant 0x0, Constant, Type: int, WCA_UNDEFINED
// Data : constant 0x1, Constant, Type: int, WCA_NCRENDERING_ENABLED
// Data : constant 0x2, Constant, Type: int, WCA_NCRENDERING_POLICY
// ...
// Data : constant 0x13, Constant, Type: int, WCA_ACCENT_POLICY
// ...
// Data : constant 0x1A, Constant, Type: int, WCA_LAST
enum WINDOWCOMPOSITIONATTRIB : INT { // Determines what attribute is being manipulated.
WCA_ACCENT_POLICY = 0x13 // The attribute being get or set is an accent policy.
};
// UserDefinedType: tagWINDOWCOMPOSITIONATTRIBDATA
// Data : this+0x0, Member, Type: enum WINDOWCOMPOSITIONATTRIB, Attrib
// Data : this+0x8, Member, Type: void *, pvData
// Data : this+0x10, Member, Type: unsigned int, cbData
struct WINDOWCOMPOSITIONATTRIBDATA { // Options for [Get/Set]WindowCompositionAttribute.
WINDOWCOMPOSITIONATTRIB Attrib; // Type of what is being get or set.
LPVOID pvData; // Pointer to memory that will receive what is get or that contains what will be set.
UINT cbData; // Size of the data being pointed to by pvData.
};
typedef BOOL (WINAPI* PFN_SET_WINDOW_COMPOSITION_ATTRIBUTE)(HWND, const WINDOWCOMPOSITIONATTRIBDATA *);
| 3,422
|
C++
|
.h
| 53
| 63.150943
| 118
| 0.694618
|
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,922
|
uxtheme.hpp
|
TranslucentTB_TranslucentTB/Common/undoc/uxtheme.hpp
|
#pragma once
#include "../arch.h"
#include <windef.h>
// Enum : PreferredAppMode, Type: int
// Data : constant 0x0, Constant, Type: int, Default
// Data : constant 0x1, Constant, Type: int, AllowDark
// Data : constant 0x2, Constant, Type: int, ForceDark
// Data : constant 0x3, Constant, Type: int, ForceLight
// Data : constant 0x4, Constant, Type: int, Max
enum class PreferredAppMode : INT {
Default = 0,
AllowDark = 1,
ForceDark = 2,
ForceLight = 3,
Max = 4
};
typedef PreferredAppMode(WINAPI* PFN_SET_PREFERRED_APP_MODE)(PreferredAppMode appMode);
typedef BOOL(WINAPI* PFN_ALLOW_DARK_MODE_FOR_WINDOW)(HWND window, bool allow);
typedef BOOL(WINAPI* PFN_SHOULD_SYSTEM_USE_DARK_MODE)();
| 767
|
C++
|
.h
| 19
| 39
| 87
| 0.670241
|
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,923
|
optionaltaskbarappearance.hpp
|
TranslucentTB_TranslucentTB/Common/config/optionaltaskbarappearance.hpp
|
#pragma once
#include <string_view>
#include "rapidjsonhelper.hpp"
#include "taskbarappearance.hpp"
struct OptionalTaskbarAppearance : TaskbarAppearance {
bool Enabled = false;
constexpr OptionalTaskbarAppearance() noexcept = default;
constexpr OptionalTaskbarAppearance(bool enabled, ACCENT_STATE accent, Util::Color color, bool showPeek, bool showLine) noexcept :
TaskbarAppearance(accent, color, showPeek, showLine),
Enabled(enabled)
{ }
template<typename Writer>
inline void Serialize(Writer &writer) const
{
rjh::Serialize(writer, Enabled, ENABLED_KEY);
TaskbarAppearance::Serialize(writer);
}
void Deserialize(const rjh::value_t &obj, void (*unknownKeyCallback)(std::wstring_view))
{
rjh::EnsureType(rj::Type::kObjectType, obj.GetType(), L"root node");
for (auto it = obj.MemberBegin(); it != obj.MemberEnd(); ++it)
{
rjh::EnsureType(rj::Type::kStringType, it->name.GetType(), L"member name");
OptionalInnerDeserialize(rjh::ValueToStringView(it->name), it->value, unknownKeyCallback);
}
}
#ifdef HAS_WINRT_CONFIG
OptionalTaskbarAppearance(const txmp::OptionalTaskbarAppearance &winrtObj) noexcept :
TaskbarAppearance(winrtObj),
Enabled(winrtObj.Enabled())
{ }
operator txmp::OptionalTaskbarAppearance() const
{
return { Enabled, static_cast<txmp::AccentState>(Accent), Color, ShowPeek, ShowLine };
}
#endif
protected:
void OptionalInnerDeserialize(std::wstring_view key, const rjh::value_t &val, void (*unknownKeyCallback)(std::wstring_view))
{
if (key == ENABLED_KEY)
{
rjh::Deserialize(val, Enabled, key);
}
else
{
InnerDeserialize(key, val, unknownKeyCallback);
}
}
private:
static constexpr std::wstring_view ENABLED_KEY = L"enabled";
};
| 1,725
|
C++
|
.h
| 51
| 31.313725
| 131
| 0.762477
|
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,924
|
taskbarappearance.hpp
|
TranslucentTB_TranslucentTB/Common/config/taskbarappearance.hpp
|
#pragma once
#include "../arch.h"
#include <array>
#include <string_view>
#include <windef.h>
#if __has_include(<winrt/TranslucentTB.Xaml.Models.Primitives.h>)
#define HAS_WINRT_CONFIG
#include "../winrt.hpp"
#include <winrt/TranslucentTB.Xaml.Models.Primitives.h>
#endif
#if __has_include(<rapidjson/rapidjson.h>)
#define HAS_RAPIDJSON
#include <rapidjson/document.h>
#include <rapidjson/encodings.h>
#include "rapidjsonhelper.hpp"
#endif
#include "../undoc/user32.hpp"
#include "../util/color.hpp"
#include "../win32.hpp"
struct TaskbarAppearance {
inline static bool IsBlurSupported()
{
static const bool isBlurSupported = []
{
if (win32::IsExactBuild(22000))
{
// Windows 11 RTM. sometimes very laggy at release, fixed in KB5006746 (22000.282)
if (const auto [version, hr] = win32::GetWindowsBuild(); SUCCEEDED(hr))
{
return version.Revision >= 282;
}
else
{
return false;
}
}
else
{
// always works in Windows 10, but broken in Windows 11 besides RTM with KB5006746.
// since we check IsExactBuild above, using an inverted IsAtLeastBuild here
// makes sure we return false for future versions of Windows 11 as well.
return !win32::IsAtLeastBuild(22000);
}
}();
return isBlurSupported;
}
ACCENT_STATE Accent = ACCENT_NORMAL;
Util::Color Color = { 0, 0, 0, 0 };
bool ShowPeek = true;
bool ShowLine = true;
constexpr TaskbarAppearance() noexcept = default;
constexpr TaskbarAppearance(ACCENT_STATE accent, Util::Color color, bool showPeek, bool showLine) noexcept :
Accent(accent),
Color(color),
ShowPeek(showPeek),
ShowLine(showLine)
{ }
#ifdef HAS_RAPIDJSON
template<class Writer>
inline void Serialize(Writer &writer) const
{
rjh::Serialize(writer, Accent, ACCENT_KEY, ACCENT_MAP);
rjh::Serialize(writer, Color.ToString(), COLOR_KEY);
rjh::Serialize(writer, ShowPeek, SHOW_PEEK_KEY);
rjh::Serialize(writer, ShowLine, SHOW_LINE_KEY);
}
void Deserialize(const rjh::value_t &obj, void (*unknownKeyCallback)(std::wstring_view))
{
rjh::EnsureType(rj::Type::kObjectType, obj.GetType(), L"root node");
for (auto it = obj.MemberBegin(); it != obj.MemberEnd(); ++it)
{
rjh::EnsureType(rj::Type::kStringType, it->name.GetType(), L"member name");
InnerDeserialize(rjh::ValueToStringView(it->name), it->value, unknownKeyCallback);
}
}
protected:
void InnerDeserialize(std::wstring_view key, const rjh::value_t &val, void (*unknownKeyCallback)(std::wstring_view))
{
if (key == ACCENT_KEY)
{
rjh::Deserialize(val, Accent, key, ACCENT_MAP);
// when blur is broken upgrade people to acrylic
if (Accent == ACCENT_ENABLE_BLURBEHIND && !IsBlurSupported())
{
Accent = ACCENT_ENABLE_ACRYLICBLURBEHIND;
}
}
else if (key == COLOR_KEY)
{
rjh::EnsureType(rj::Type::kStringType, val.GetType(), key);
const auto colorStr = rjh::ValueToStringView(val);
try
{
Color = Util::Color::FromString(colorStr);
}
catch (...)
{
throw rjh::DeserializationError {
std::format(L"Found invalid string \"{}\" while deserializing {}", colorStr, key)
};
}
}
else if (key == SHOW_PEEK_KEY)
{
rjh::Deserialize(val, ShowPeek, key);
}
else if (key == SHOW_LINE_KEY)
{
rjh::Deserialize(val, ShowLine, key);
}
else if (unknownKeyCallback)
{
unknownKeyCallback(key);
}
}
private:
static constexpr std::array<std::wstring_view, 5> ACCENT_MAP = {
L"normal",
L"opaque",
L"clear",
L"blur",
L"acrylic"
};
static constexpr std::wstring_view ACCENT_KEY = L"accent";
static constexpr std::wstring_view COLOR_KEY = L"color";
static constexpr std::wstring_view SHOW_PEEK_KEY = L"show_peek";
static constexpr std::wstring_view SHOW_LINE_KEY = L"show_line";
#endif
#ifdef HAS_WINRT_CONFIG
public:
TaskbarAppearance(const txmp::TaskbarAppearance &winrtObj) noexcept :
Accent(static_cast<ACCENT_STATE>(winrtObj.Accent())),
Color(winrtObj.Color()),
ShowPeek(winrtObj.ShowPeek()),
ShowLine(winrtObj.ShowLine())
{ }
operator txmp::TaskbarAppearance() const
{
return { static_cast<txmp::AccentState>(Accent), Color, ShowPeek, ShowLine };
}
#endif
};
| 4,164
|
C++
|
.h
| 142
| 26.359155
| 117
| 0.712038
|
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,925
|
activeinactivetaskbarappearance.hpp
|
TranslucentTB_TranslucentTB/Common/config/activeinactivetaskbarappearance.hpp
|
#pragma once
#include <string_view>
#include <optional>
#include "rapidjsonhelper.hpp"
#include "taskbarappearance.hpp"
struct ActiveInactiveTaskbarAppearance : TaskbarAppearance {
std::optional<TaskbarAppearance> Inactive;
constexpr ActiveInactiveTaskbarAppearance() noexcept = default;
constexpr ActiveInactiveTaskbarAppearance(std::optional<TaskbarAppearance> inactive, ACCENT_STATE accent, Util::Color color, bool showPeek, bool showLine) noexcept :
TaskbarAppearance(accent, color, showPeek, showLine),
Inactive(std::move(inactive))
{ }
template<typename Writer>
inline void Serialize(Writer &writer) const
{
TaskbarAppearance::Serialize(writer);
rjh::Serialize(writer, Inactive, INACTIVE_KEY);
}
inline void Deserialize(const rjh::value_t &obj, void (*unknownKeyCallback)(std::wstring_view))
{
rjh::EnsureType(rj::Type::kObjectType, obj.GetType(), L"root node");
for (auto it = obj.MemberBegin(); it != obj.MemberEnd(); ++it)
{
rjh::EnsureType(rj::Type::kStringType, it->name.GetType(), L"member name");
const auto key = rjh::ValueToStringView(it->name);
if (key == INACTIVE_KEY)
{
rjh::Deserialize(it->value, Inactive, key, unknownKeyCallback);
}
else
{
InnerDeserialize(key, it->value, unknownKeyCallback);
}
}
}
private:
static constexpr std::wstring_view INACTIVE_KEY = L"inactive";
};
| 1,365
|
C++
|
.h
| 38
| 33.105263
| 166
| 0.75569
|
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,926
|
rapidjsonhelper.hpp
|
TranslucentTB_TranslucentTB/Common/config/rapidjsonhelper.hpp
|
#pragma once
#include <algorithm>
#include <array>
#include <cassert>
#include <concepts>
#include <format>
#include <optional>
#include <rapidjson/document.h>
#include <rapidjson/encodings.h>
#include <string>
#include <string_view>
#include <type_traits>
#include <utility>
#include "../util/type_traits.hpp"
namespace rj = rapidjson;
namespace rjh {
using value_t = rj::GenericValue<rj::UTF16LE<>>;
struct DeserializationError {
const std::wstring what;
};
static constexpr std::array<std::wstring_view, 7> TYPE_NAMES = {
L"null",
L"bool",
L"bool",
L"object",
L"array",
L"string",
L"number"
};
constexpr bool IsType(rj::Type a, rj::Type b) noexcept
{
return a == b ||
(a == rj::Type::kFalseType && b == rj::Type::kTrueType) ||
(a == rj::Type::kTrueType && b == rj::Type::kFalseType);
}
inline void EnsureType(rj::Type expected, rj::Type actual, std::wstring_view obj)
{
if (!IsType(expected, actual)) [[unlikely]]
{
throw DeserializationError {
std::format(L"Expected {} but found {} while deserializing {}", TYPE_NAMES.at(expected), TYPE_NAMES.at(actual), obj)
};
}
}
inline void AssertLength(std::wstring_view str)
{
assert(str.length() <= std::numeric_limits<rj::SizeType>::max());
}
inline std::wstring_view ValueToStringView(const value_t &val)
{
assert(val.GetType() == rj::Type::kStringType); // caller should have already ensured
return { val.GetString(), val.GetStringLength() };
}
inline value_t StringViewToValue(std::wstring_view str)
{
AssertLength(str);
return { str.data(), static_cast<rj::SizeType>(str.length()) };
}
template<class Writer>
inline void WriteKey(Writer &writer, std::wstring_view key)
{
AssertLength(key);
writer.Key(key.data(), static_cast<rj::SizeType>(key.length()));
}
template<class Writer>
inline void WriteString(Writer &writer, std::wstring_view str)
{
AssertLength(str);
writer.String(str.data(), static_cast<rj::SizeType>(str.length()));
}
// prevent this overload from being picked on stuff implicitly convertible to bool
template<class Writer, std::same_as<bool> T>
inline void Serialize(Writer &writer, T value, std::wstring_view key)
{
WriteKey(writer, key);
writer.Bool(value);
}
template<class Writer>
inline void Serialize(Writer &writer, std::wstring_view value, std::wstring_view key)
{
WriteKey(writer, key);
WriteString(writer, value);
}
template<class Writer, class T, std::size_t size>
requires std::is_enum_v<T>
inline void Serialize(Writer &writer, const T &member, std::wstring_view key, const std::array<std::wstring_view, size> &arr)
{
if (const auto i = static_cast<std::size_t>(member); i < size)
{
WriteKey(writer, key);
WriteString(writer, arr[i]);
}
}
template<class Writer, class T>
// prevent ambiguous overload errors
requires (std::is_class_v<T> && !std::is_convertible_v<T, std::wstring_view> && !Util::is_optional_v<T>)
inline void Serialize(Writer &writer, const T &member, std::wstring_view key)
{
WriteKey(writer, key);
writer.StartObject();
member.Serialize(writer);
writer.EndObject();
}
template<class Writer, class T, typename... Args>
void Serialize(Writer &writer, const std::optional<T> &member, std::wstring_view key, Args &&...args)
{
if (member)
{
Serialize(writer, *member, key, std::forward<Args>(args)...);
}
}
inline void Deserialize(const value_t &obj, bool &member, std::wstring_view key)
{
EnsureType(rj::Type::kFalseType, obj.GetType(), key);
member = obj.GetBool();
}
template<typename T, std::size_t size>
requires std::is_enum_v<T>
inline void Deserialize(const value_t &obj, T &member, std::wstring_view key, const std::array<std::wstring_view, size> &arr)
{
EnsureType(rj::Type::kStringType, obj.GetType(), key);
const auto str = ValueToStringView(obj);
if (const auto it = std::ranges::find(arr.begin(), arr.end(), str); it != arr.end())
{
member = static_cast<T>(it - arr.begin());
}
else
{
throw rjh::DeserializationError {
std::format(L"Found invalid enum string \"{}\" while deserializing key \"{}\"", str, key)
};
}
}
template<class T>
// prevent ambiguous overload errors
requires (std::is_class_v<T> && !Util::is_optional_v<T>)
inline void Deserialize(const value_t &obj, T &member, std::wstring_view key, void (*unknownKeyCallback)(std::wstring_view))
{
EnsureType(rj::Type::kObjectType, obj.GetType(), key);
member.Deserialize(obj, unknownKeyCallback);
}
template<typename T, typename... Args>
void Deserialize(const value_t &obj, std::optional<T> &member, std::wstring_view key, Args &&...args)
{
Deserialize(obj, member.emplace(), key, std::forward<Args>(args)...);
}
}
| 4,711
|
C++
|
.h
| 147
| 29.489796
| 126
| 0.70412
|
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,927
|
windowfilter.hpp
|
TranslucentTB_TranslucentTB/Common/config/windowfilter.hpp
|
#pragma once
#include <rapidjson/document.h>
#include <rapidjson/encodings.h>
#include <string>
#include <string_view>
#include <unordered_set>
#include "rapidjsonhelper.hpp"
#include "../win32.hpp"
#include "../constants.hpp"
#ifdef _TRANSLUCENTTB_EXE
#include "../../TranslucentTB/windows/window.hpp"
#include "../../ProgramLog/error/std.hpp"
#endif
struct WindowFilter {
std::unordered_set<std::wstring> ClassList;
std::unordered_set<std::wstring> TitleList;
win32::FilenameSet FileList;
WindowFilter() = default;
WindowFilter(std::unordered_set<std::wstring> classList, std::unordered_set<std::wstring> titleList, win32::FilenameSet fileList) :
ClassList(std::move(classList)),
TitleList(std::move(titleList)),
FileList(std::move(fileList))
{ }
template<class Writer>
inline void Serialize(Writer &writer) const
{
SerializeStringSet(writer, ClassList, CLASS_KEY);
SerializeStringSet(writer, TitleList, TITLE_KEY);
SerializeStringSet(writer, FileList, FILE_KEY);
}
inline void Deserialize(const rjh::value_t &obj, void (*unknownKeyCallback)(std::wstring_view))
{
rjh::EnsureType(rj::Type::kObjectType, obj.GetType(), L"root node");
for (auto it = obj.MemberBegin(); it != obj.MemberEnd(); ++it)
{
rjh::EnsureType(rj::Type::kStringType, it->name.GetType(), L"member name");
const auto key = rjh::ValueToStringView(it->name);
if (key == CLASS_KEY)
{
DeserializeStringSet(it->value, ClassList, key);
}
else if (key == TITLE_KEY)
{
DeserializeStringSet(it->value, TitleList, key);
}
else if (key == FILE_KEY)
{
DeserializeStringSet(it->value, FileList, key);
}
else if (unknownKeyCallback)
{
unknownKeyCallback(key);
}
}
}
#ifdef _TRANSLUCENTTB_EXE
inline bool IsFiltered(Window window) const
{
// TODO: add logging
// This is the fastest because we do the less string manipulation, so always try it first
if (!ClassList.empty())
{
if (const auto className = window.classname())
{
if (ClassList.contains(*className))
{
return true;
}
}
else
{
return false;
}
}
if (!FileList.empty())
{
if (const auto file = window.file())
{
try
{
if (FileList.contains(file->filename().native()))
{
return true;
}
}
StdSystemErrorCatch(spdlog::level::warn, L"Failed to check if window process is part of window filter");
}
else
{
return false;
}
}
// Do it last because titles can change, so it's less reliable.
if (!TitleList.empty())
{
if (const auto title = window.title())
{
for (const auto &value : TitleList)
{
if (title->find(value) != std::wstring::npos)
{
return true;
}
}
}
}
return false;
}
#endif
private:
template<typename Writer, typename Hash, typename Equal, typename Alloc>
inline static void SerializeStringSet(Writer &writer, const std::unordered_set<std::wstring, Hash, Equal, Alloc> &set, std::wstring_view key)
{
rjh::WriteKey(writer, key);
writer.StartArray();
for (const std::wstring &str : set)
{
rjh::WriteString(writer, str);
}
writer.EndArray();
}
template<typename Hash, typename Equal, typename Alloc>
inline static void DeserializeStringSet(const rjh::value_t &arr, std::unordered_set<std::wstring, Hash, Equal, Alloc> &set, std::wstring_view key)
{
rjh::EnsureType(rj::Type::kArrayType, arr.GetType(), key);
for (const auto &elem : arr.GetArray())
{
rjh::EnsureType(rj::Type::kStringType, elem.GetType(), L"array element");
set.emplace(rjh::ValueToStringView(elem));
}
}
};
| 3,601
|
C++
|
.h
| 132
| 23.916667
| 147
| 0.693688
|
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,928
|
ruledtaskbarappearance.hpp
|
TranslucentTB_TranslucentTB/Common/config/ruledtaskbarappearance.hpp
|
#pragma once
#include <format>
#include <string_view>
#include <vector>
#include "optionaltaskbarappearance.hpp"
#include "activeinactivetaskbarappearance.hpp"
#include "rapidjsonhelper.hpp"
#include "taskbarappearance.hpp"
#include "../constants.hpp"
#include "../win32.hpp"
#ifdef _TRANSLUCENTTB_EXE
#include "../../TranslucentTB/windows/window.hpp"
#include "../../ProgramLog/error/std.hpp"
#endif
struct RuledTaskbarAppearance : OptionalTaskbarAppearance {
std::unordered_map<std::wstring, ActiveInactiveTaskbarAppearance> ClassRules;
std::unordered_map<std::wstring, ActiveInactiveTaskbarAppearance> TitleRules;
win32::FilenameMap<ActiveInactiveTaskbarAppearance> FileRules;
RuledTaskbarAppearance() = default;
RuledTaskbarAppearance(std::unordered_map<std::wstring, ActiveInactiveTaskbarAppearance> classRules, std::unordered_map<std::wstring, ActiveInactiveTaskbarAppearance> titleRules, win32::FilenameMap<ActiveInactiveTaskbarAppearance> fileRules, bool enabled, ACCENT_STATE accent, Util::Color color, bool showPeek, bool showLine) :
OptionalTaskbarAppearance(enabled, accent, color, showPeek, showLine),
ClassRules(std::move(classRules)),
TitleRules(std::move(titleRules)),
FileRules(std::move(fileRules))
{ }
template<typename Writer>
inline void Serialize(Writer &writer) const
{
OptionalTaskbarAppearance::Serialize(writer);
rjh::WriteKey(writer, RULES_KEY);
writer.StartObject();
SerializeRulesMap(writer, ClassRules, CLASS_KEY);
SerializeRulesMap(writer, TitleRules, TITLE_KEY);
SerializeRulesMap(writer, FileRules, FILE_KEY);
writer.EndObject();
}
inline void Deserialize(const rjh::value_t &obj, void (*unknownKeyCallback)(std::wstring_view))
{
rjh::EnsureType(rj::Type::kObjectType, obj.GetType(), L"root node");
for (auto it = obj.MemberBegin(); it != obj.MemberEnd(); ++it)
{
rjh::EnsureType(rj::Type::kStringType, it->name.GetType(), L"member name");
const auto key = rjh::ValueToStringView(it->name);
if (key == RULES_KEY)
{
DeserializeRulesMap(it->value, unknownKeyCallback);
}
else
{
OptionalInnerDeserialize(key, it->value, unknownKeyCallback);
}
}
}
#ifdef _TRANSLUCENTTB_EXE
inline std::optional<TaskbarAppearance> FindRule(const Window window) const
{
if (const auto rule = FindRuleInner(window))
{
if (!window.active() && rule->Inactive)
{
return rule->Inactive.value();
}
else
{
return rule;
}
}
else
{
return std::nullopt;
}
}
private:
inline std::optional<ActiveInactiveTaskbarAppearance> FindRuleInner(const Window window) const
{
// This is the fastest because we do the less string manipulation, so always try it first
if (!ClassRules.empty())
{
if (const auto className = window.classname())
{
if (const auto it = ClassRules.find(*className); it != ClassRules.end())
{
return it->second;
}
}
else
{
return std::nullopt;
}
}
if (!FileRules.empty())
{
if (const auto file = window.file())
{
try
{
if (const auto it = FileRules.find(file->filename().native()); it != FileRules.end())
{
return it->second;
}
}
StdSystemErrorCatch(spdlog::level::warn, L"Failed to check if window process is part of window filter");
}
else
{
return std::nullopt;
}
}
// Do it last because titles can change, so it's less reliable.
if (!TitleRules.empty())
{
if (const auto title = window.title())
{
for (const auto &[key, value] : TitleRules)
{
if (title->find(key) != std::wstring::npos)
{
return value;
}
}
}
}
return std::nullopt;
}
#endif
public:
inline bool HasRules() const noexcept
{
return !(ClassRules.empty() && FileRules.empty() && TitleRules.empty());
}
private:
template<typename Writer, typename Hash, typename Equal, typename Alloc>
inline static void SerializeRulesMap(Writer &writer, const std::unordered_map<std::wstring, ActiveInactiveTaskbarAppearance, Hash, Equal, Alloc> &map, std::wstring_view mapKey)
{
rjh::WriteKey(writer, mapKey);
writer.StartObject();
for (const auto &[key, value] : map)
{
rjh::Serialize(writer, value, key);
}
writer.EndObject();
}
inline void DeserializeRulesMap(const rjh::value_t &obj, void (*unknownKeyCallback)(std::wstring_view))
{
rjh::EnsureType(rj::Type::kObjectType, obj.GetType(), L"root node");
for (auto it = obj.MemberBegin(); it != obj.MemberEnd(); ++it)
{
rjh::EnsureType(rj::Type::kStringType, it->name.GetType(), L"member name");
const auto key = rjh::ValueToStringView(it->name);
if (key == CLASS_KEY)
{
DeserializeMap(it->value, ClassRules, unknownKeyCallback);
}
else if (key == TITLE_KEY)
{
DeserializeMap(it->value, TitleRules, unknownKeyCallback);
}
else if (key == FILE_KEY)
{
DeserializeMap(it->value, FileRules, unknownKeyCallback);
}
else
{
unknownKeyCallback(key);
}
}
}
template<typename Hash, typename Equal, typename Alloc>
inline static void DeserializeMap(const rjh::value_t &obj, std::unordered_map<std::wstring, ActiveInactiveTaskbarAppearance, Hash, Equal, Alloc> &map, void (*unknownKeyCallback)(std::wstring_view))
{
rjh::EnsureType(rj::Type::kObjectType, obj.GetType(), L"root node");
for (auto it = obj.MemberBegin(); it != obj.MemberEnd(); ++it)
{
rjh::EnsureType(rj::Type::kStringType, it->name.GetType(), L"member name");
const auto key = rjh::ValueToStringView(it->name);
ActiveInactiveTaskbarAppearance rule;
rjh::Deserialize(it->value, rule, key, unknownKeyCallback);
map[std::wstring(key)] = rule;
}
}
static constexpr std::wstring_view RULES_KEY = L"rules";
};
| 5,703
|
C++
|
.h
| 182
| 27.967033
| 328
| 0.716209
|
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,929
|
config.hpp
|
TranslucentTB_TranslucentTB/Common/config/config.hpp
|
#pragma once
#include <array>
#include <format>
#include <regex>
#include <spdlog/common.h>
#include <string_view>
#include <optional>
#include "optionaltaskbarappearance.hpp"
#include "rapidjsonhelper.hpp"
#include "ruledtaskbarappearance.hpp"
#include "taskbarappearance.hpp"
#include "../win32.hpp"
#include "windowfilter.hpp"
class Config {
private:
// TODO: move to some common place? osversion helper and move some win32.hpp stuff there?
inline static bool IsWindows11() noexcept
{
static const bool isWindows11 = win32::IsAtLeastBuild(22000);
return isWindows11;
}
inline static const std::wregex &LanguageRegex()
{
static const std::wregex languageRegex(L"^[a-z]{2}(-[A-Z]{2})?$");
return languageRegex;
}
public:
static constexpr spdlog::level::level_enum DEFAULT_LOG_VERBOSITY =
#ifdef _DEBUG
spdlog::level::debug;
#else
spdlog::level::warn;
#endif
// Appearances
TaskbarAppearance DesktopAppearance = { ACCENT_ENABLE_TRANSPARENTGRADIENT, { 0, 0, 0, 0 }, false, false };
RuledTaskbarAppearance VisibleWindowAppearance = { {}, {}, {}, false, ACCENT_ENABLE_TRANSPARENTGRADIENT, { 0, 0, 0, 0 }, true, false };
RuledTaskbarAppearance MaximisedWindowAppearance = { {}, {}, {}, false, ACCENT_ENABLE_ACRYLICBLURBEHIND, { 0, 0, 0, 0 }, true, true };
OptionalTaskbarAppearance StartOpenedAppearance = { !IsWindows11(), ACCENT_NORMAL, { 0, 0, 0, 0 }, true, true };
OptionalTaskbarAppearance SearchOpenedAppearance = { !IsWindows11(), ACCENT_NORMAL, { 0, 0, 0, 0 }, true, true };
OptionalTaskbarAppearance TaskViewOpenedAppearance = { true, ACCENT_NORMAL, { 0, 0, 0, 0 }, false, true };
OptionalTaskbarAppearance BatterySaverAppearance = { false, ACCENT_ENABLE_GRADIENT, { 0, 0, 0, 0 }, true, false };
// Advanced
WindowFilter IgnoredWindows;
bool HideTray = false;
bool DisableSaving = false;
spdlog::level::level_enum LogVerbosity = DEFAULT_LOG_VERBOSITY;
std::wstring Language;
std::optional<bool> UseXamlContextMenu;
template<class Writer>
inline void Serialize(Writer &writer) const
{
rjh::Serialize(writer, DesktopAppearance, DESKTOP_KEY);
rjh::Serialize(writer, VisibleWindowAppearance, VISIBLE_KEY);
rjh::Serialize(writer, MaximisedWindowAppearance, MAXIMISED_KEY);
rjh::Serialize(writer, StartOpenedAppearance, START_KEY);
rjh::Serialize(writer, SearchOpenedAppearance, SEARCH_KEY);
rjh::Serialize(writer, TaskViewOpenedAppearance, TASKVIEW_KEY);
rjh::Serialize(writer, BatterySaverAppearance, BATTERYSAVER_KEY);
rjh::Serialize(writer, IgnoredWindows, IGNORED_WINDOWS_KEY);
rjh::Serialize(writer, HideTray, TRAY_KEY);
rjh::Serialize(writer, DisableSaving, SAVING_KEY);
rjh::Serialize(writer, LogVerbosity, LOG_KEY, LOG_MAP);
if (!Language.empty())
{
rjh::Serialize(writer, Language, LANGUAGE_KEY);
}
rjh::Serialize(writer, UseXamlContextMenu, USE_XAML_CONTEXT_MENU_KEY);
}
inline void Deserialize(const rjh::value_t &obj, void (*unknownKeyCallback)(std::wstring_view) = nullptr)
{
rjh::EnsureType(rj::Type::kObjectType, obj.GetType(), L"root node");
for (auto it = obj.MemberBegin(); it != obj.MemberEnd(); ++it)
{
rjh::EnsureType(rj::Type::kStringType, it->name.GetType(), L"member name");
const auto key = rjh::ValueToStringView(it->name);
if (key == DESKTOP_KEY)
{
rjh::Deserialize(it->value, DesktopAppearance, key, unknownKeyCallback);
}
else if (key == VISIBLE_KEY)
{
rjh::Deserialize(it->value, VisibleWindowAppearance, key, unknownKeyCallback);
}
else if (key == MAXIMISED_KEY)
{
rjh::Deserialize(it->value, MaximisedWindowAppearance, key, unknownKeyCallback);
}
else if (key == START_KEY)
{
rjh::Deserialize(it->value, StartOpenedAppearance, key, unknownKeyCallback);
}
else if (key == SEARCH_KEY)
{
rjh::Deserialize(it->value, SearchOpenedAppearance, key, unknownKeyCallback);
}
else if (key == TASKVIEW_KEY)
{
rjh::Deserialize(it->value, TaskViewOpenedAppearance, key, unknownKeyCallback);
}
else if (key == BATTERYSAVER_KEY)
{
rjh::Deserialize(it->value, BatterySaverAppearance, key, unknownKeyCallback);
}
else if (key == IGNORED_WINDOWS_KEY)
{
rjh::Deserialize(it->value, IgnoredWindows, key, unknownKeyCallback);
}
else if (key == TRAY_KEY)
{
rjh::Deserialize(it->value, HideTray, key);
}
else if (key == SAVING_KEY)
{
rjh::Deserialize(it->value, DisableSaving, key);
}
else if (key == LOG_KEY)
{
rjh::Deserialize(it->value, LogVerbosity, key, LOG_MAP);
}
else if (key == LANGUAGE_KEY)
{
rjh::EnsureType(rj::Type::kStringType, it->value.GetType(), key);
const auto languageStr = rjh::ValueToStringView(it->value);
if (languageStr.empty() || std::regex_match(languageStr.begin(), languageStr.end(), LanguageRegex()))
{
Language = languageStr;
}
else
{
throw rjh::DeserializationError {
std::format(L"Found invalid string \"{}\" while deserializing {}", languageStr, key)
};
}
}
else if (key == USE_XAML_CONTEXT_MENU_KEY)
{
rjh::Deserialize(it->value, UseXamlContextMenu, key);
}
else if (unknownKeyCallback)
{
unknownKeyCallback(key);
}
}
}
private:
static constexpr std::array<std::wstring_view, spdlog::level::n_levels> LOG_MAP = {
L"trace",
L"debug",
L"info",
L"warn",
L"err",
L"critical",
L"off"
};
static constexpr std::wstring_view DESKTOP_KEY = L"desktop_appearance";
static constexpr std::wstring_view VISIBLE_KEY = L"visible_window_appearance";
static constexpr std::wstring_view MAXIMISED_KEY = L"maximized_window_appearance";
static constexpr std::wstring_view START_KEY = L"start_opened_appearance";
static constexpr std::wstring_view SEARCH_KEY = L"search_opened_appearance";
static constexpr std::wstring_view TASKVIEW_KEY = L"task_view_opened_appearance";
static constexpr std::wstring_view BATTERYSAVER_KEY = L"battery_saver_appearance";
static constexpr std::wstring_view IGNORED_WINDOWS_KEY = L"ignored_windows";
static constexpr std::wstring_view TRAY_KEY = L"hide_tray";
static constexpr std::wstring_view SAVING_KEY = L"disable_saving";
static constexpr std::wstring_view LOG_KEY = L"verbosity";
static constexpr std::wstring_view LANGUAGE_KEY = L"language";
static constexpr std::wstring_view USE_XAML_CONTEXT_MENU_KEY = L"use_xaml_context_menu";
};
| 6,355
|
C++
|
.h
| 168
| 34.678571
| 136
| 0.725786
|
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,930
|
swcadetour.hpp
|
TranslucentTB_TranslucentTB/ExplorerHooks/swcadetour.hpp
|
#pragma once
#include "arch.h"
#include <wil/resource.h>
#include <windef.h>
#include "undoc/user32.hpp"
#include "wilx.hpp"
class SWCADetour {
private:
static void FreeLibraryFailFast(HMODULE hModule) noexcept;
using unique_module_failfast = wilx::unique_any<FreeLibraryFailFast>;
static unique_module_failfast s_User32;
static PFN_SET_WINDOW_COMPOSITION_ATTRIBUTE SetWindowCompositionAttribute;
static UINT s_RequestAttribute;
static bool s_DetourInstalled;
static BOOL WINAPI FunctionDetour(HWND hWnd, const WINDOWCOMPOSITIONATTRIBDATA *data) noexcept;
static void Install() noexcept;
static void Uninstall() noexcept;
friend BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID) noexcept;
};
| 723
|
C++
|
.h
| 19
| 36.210526
| 96
| 0.823782
|
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,931
|
detourtransaction.hpp
|
TranslucentTB_TranslucentTB/ExplorerHooks/detourtransaction.hpp
|
#pragma once
#include "arch.h"
#include <memory>
#include <type_traits>
#include <windef.h>
#include <processsnapshot.h>
#include <wil/resource.h>
#include "common.hpp"
#include "util/concepts.hpp"
#include "util/null_terminated_string_view.hpp"
#include "wilx.hpp"
class DetourTransaction {
private:
static void HeapDestroyFailFast(HANDLE hHeap) noexcept;
using unique_hheap_failfast = wilx::unique_any<HeapDestroyFailFast>;
static void PssFreeSnapshotFailFast(HPSS snapshot) noexcept;
using unique_hpss_failfast = wilx::unique_any<PssFreeSnapshotFailFast>;
static void PssWalkMarkerFreeFailFast(HPSSWALK marker) noexcept;
using unique_hpsswalk_failfast = wilx::unique_any<PssWalkMarkerFreeFailFast>;
static void* WINAPI PssAllocRoutineFailFast(void* context, DWORD size) noexcept;
static void WINAPI PssFreeRoutineFailFast(void* context, void* address) noexcept;
struct node;
struct node_deleter {
void operator()(node *ptr) const noexcept;
};
using node_ptr = std::unique_ptr<node, node_deleter>;
struct node {
unique_handle_failfast thread;
node_ptr next;
};
static unique_hheap_failfast s_Heap;
static const PSS_ALLOCATOR s_PssAllocator;
node_ptr m_Head;
bool m_IsTransacting = false;
void attach_internal(void **function, void *detour) noexcept;
void detach_internal(void **function, void *detour) noexcept;
void update_thread(unique_handle_failfast hThread) noexcept;
public:
DetourTransaction() noexcept;
DetourTransaction(const DetourTransaction &) = delete;
DetourTransaction &operator =(const DetourTransaction &) = delete;
void update_all_threads() noexcept;
void commit() noexcept;
~DetourTransaction() noexcept;
template<Util::function_pointer T>
void attach(T &function, std::type_identity_t<T> detour) noexcept
{
attach_internal(reinterpret_cast<void **>(&function), reinterpret_cast<void *>(detour));
}
template<Util::function_pointer T>
void detach(T &function, std::type_identity_t<T> detour) noexcept
{
detach_internal(reinterpret_cast<void **>(&function), reinterpret_cast<void *>(detour));
}
};
| 2,079
|
C++
|
.h
| 55
| 35.672727
| 90
| 0.787743
|
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,932
|
api.hpp
|
TranslucentTB_TranslucentTB/ExplorerHooks/api.hpp
|
#pragma once
#include "arch.h"
#include <windef.h>
extern "C"
#ifdef EXPLORERHOOKS_EXPORTS
__declspec(dllexport)
#else
__declspec(dllimport)
#endif
HHOOK InjectExplorerHook(HWND window) noexcept;
using PFN_INJECT_EXPLORER_HOOK = decltype(&InjectExplorerHook);
| 262
|
C++
|
.h
| 11
| 22.636364
| 63
| 0.819277
|
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,933
|
multitaskingviewvisibilitysink.hpp
|
TranslucentTB_TranslucentTB/ExplorerHooks/multitaskingviewvisibilitysink.hpp
|
#pragma once
#include "arch.h"
#include <type_traits>
#include <wrl/implements.h>
#include "constants.hpp"
#include "taskviewvisibilitymonitor.hpp"
#include "undoc/explorer.hpp"
class MultitaskingViewVisibilitySink : public Microsoft::WRL::RuntimeClass<Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>, IMultitaskingViewVisibilityNotification> {
private:
UINT m_ChangeMessage;
void NotifyWorker(bool opened) const noexcept
{
if (const auto worker = FindWindow(TTB_WORKERWINDOW.c_str(), TTB_WORKERWINDOW.c_str()))
{
PostMessage(worker, m_ChangeMessage, opened, 0);
}
}
IFACEMETHODIMP MultitaskingViewShown(MULTITASKING_VIEW_TYPES flags) noexcept override
{
if (flags & MVT_ALL_UP_VIEW)
{
NotifyWorker(true);
}
return S_OK;
}
IFACEMETHODIMP MultitaskingViewDismissed(MULTITASKING_VIEW_TYPES flags) noexcept override
{
if (flags & MVT_ALL_UP_VIEW)
{
NotifyWorker(false);
}
return S_OK;
}
public:
MultitaskingViewVisibilitySink(UINT changeMessage) noexcept : m_ChangeMessage(changeMessage) { }
};
| 1,056
|
C++
|
.h
| 36
| 26.944444
| 180
| 0.784585
|
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,934
|
taskviewvisibilitymonitor.hpp
|
TranslucentTB_TranslucentTB/ExplorerHooks/taskviewvisibilitymonitor.hpp
|
#pragma once
#include "arch.h"
#include <atomic>
#include <windef.h>
#include <wil/com.h>
#include <wil/resource.h>
#include "common.hpp"
#include "undoc/explorer.hpp"
#include "wilx.hpp"
class TaskViewVisibilityMonitor {
private:
static void UnregisterClassFailFast(ATOM atom) noexcept;
using unique_class_atom_failfast = wilx::unique_any<UnregisterClassFailFast>;
static void DestroyWindowFailFast(HWND hwnd) noexcept;
using unique_window_failfast = wilx::unique_any<DestroyWindowFailFast>;
static void UnregisterSink(IMultitaskingViewVisibilityService* source, DWORD cookie) noexcept;
using unique_multitasking_view_visibility_token = wil::unique_com_token<IMultitaskingViewVisibilityService, DWORD, decltype(&UnregisterSink), UnregisterSink>;
static std::atomic<bool> s_ThreadRunning;
static unique_handle_failfast s_ThreadCleanupEvent;
static UINT s_TaskViewVisibilityChangeMessage;
static UINT s_IsTaskViewOpenedMessage;
static unique_class_atom_failfast s_WindowClassAtom;
static unique_handle_failfast s_hThread;
static wil::com_ptr_failfast<IMultitaskingViewVisibilityService> s_ViewService;
static void ResetViewService() noexcept;
using unique_view_service = wilx::unique_call<ResetViewService>;
static unique_view_service LoadViewService() noexcept;
static unique_multitasking_view_visibility_token RegisterSink() noexcept;
static void ThreadMain() noexcept;
static DWORD WINAPI ThreadProc(LPVOID lpParameter) noexcept;
static LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) noexcept;
static void EndWatcherThread() noexcept;
static void Install() noexcept;
static void Uninstall() noexcept;
friend BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID) noexcept;
};
| 1,756
|
C++
|
.h
| 36
| 46.805556
| 159
| 0.829725
|
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,935
|
common.hpp
|
TranslucentTB_TranslucentTB/ExplorerHooks/common.hpp
|
#pragma once
#include "arch.h"
#include <wil/resource.h>
#include <windef.h>
#include "wilx.hpp"
void CloseHandleFailFast(HANDLE handle) noexcept;
using unique_handle_failfast = wilx::unique_any<CloseHandleFailFast>;
| 219
|
C++
|
.h
| 7
| 30
| 69
| 0.804762
|
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,936
|
loadabledll.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/loadabledll.hpp
|
#pragma once
#include "arch.h"
#include <filesystem>
#include <libloaderapi.h>
#include <optional>
#include <string_view>
#include <wil/resource.h>
#include "util/null_terminated_string_view.hpp"
#include "../ProgramLog/error/win32.hpp"
class LoadableDll {
wil::unique_hmodule m_hMod;
static std::filesystem::path GetDllPath(const std::optional<std::filesystem::path>& storageFolder, std::wstring_view dll);
static wil::unique_hmodule LoadDll(const std::filesystem::path &location);
public:
LoadableDll(const std::optional<std::filesystem::path> &storagePath, std::wstring_view dll);
template<typename T>
T GetProc(Util::null_terminated_string_view proc)
{
if (const auto ptr = GetProcAddress(m_hMod.get(), proc.c_str()))
{
return reinterpret_cast<T>(ptr);
}
else
{
LastErrorHandle(spdlog::level::critical, L"Failed to get address of procedure");
}
}
};
| 885
|
C++
|
.h
| 28
| 29.5
| 123
| 0.753521
|
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,937
|
application.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/application.hpp
|
#pragma once
#include "arch.h"
#include <filesystem>
#include <memory>
#include <optional>
#include <windef.h>
#include "winrt.hpp"
#include "undefgetcurrenttime.h"
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.UI.Xaml.Hosting.h>
#include "redefgetcurrenttime.h"
#include <winrt/TranslucentTB.Xaml.h>
#include <wil/cppwinrt_helpers.h>
#include "dynamicloader.hpp"
#include "managers/configmanager.hpp"
#include "mainappwindow.hpp"
#include "managers/startupmanager.hpp"
#include "taskbar/taskbarattributeworker.hpp"
#include "uwp/dynamicdependency.hpp"
#include "uwp/xamlthreadpool.hpp"
class Application final {
static void ConfigurationChanged(void *context);
static winrt::TranslucentTB::Xaml::App CreateXamlApp();
ConfigManager m_Config;
DynamicLoader m_Loader;
winrt::Windows::System::DispatcherQueueController m_DispatcherController;
TaskbarAttributeWorker m_Worker;
StartupManager m_Startup;
// seemingly, dynamic deps are not transitive so add a dyn dep to the CRT that WinUI uses.
DynamicDependency m_UwpCRTDep, m_WinUIDep;
winrt::TranslucentTB::Xaml::App m_XamlApp;
wuxh::WindowsXamlManager m_XamlManager;
MainAppWindow m_AppWindow;
Window m_WelcomePage;
XamlThreadPool m_Xaml;
bool m_ShuttingDown;
void CreateWelcomePage();
Application(HINSTANCE hInst, std::optional<std::filesystem::path> storageFolder, bool fileExists);
public:
Application(HINSTANCE hInst, std::optional<std::filesystem::path> storageFolder) : Application(hInst, std::move(storageFolder), false) { }
static void OpenDonationPage();
static void OpenTipsPage();
static void OpenDiscordServer();
constexpr ConfigManager &GetConfigManager() noexcept { return m_Config; }
constexpr StartupManager &GetStartupManager() noexcept { return m_Startup; }
constexpr TaskbarAttributeWorker &GetWorker() noexcept { return m_Worker; }
int Run();
winrt::fire_and_forget Shutdown();
template<typename T, typename Callback, typename... Args>
void CreateXamlWindow(xaml_startup_position pos, Callback &&callback, Args&&... args)
{
m_Xaml.CreateXamlWindow<T>(pos, std::forward<Callback>(callback), std::forward<Args>(args)...);
}
winrt::fire_and_forget DispatchToMainThread(winrt::Windows::System::DispatcherQueueHandler callback,
winrt::Windows::System::DispatcherQueuePriority priority = winrt::Windows::System::DispatcherQueuePriority::Normal)
{
co_await wil::resume_foreground(m_DispatcherController.DispatcherQueue(), priority);
callback();
}
bool BringWelcomeToFront() noexcept;
};
| 2,522
|
C++
|
.h
| 61
| 39.409836
| 139
| 0.800491
|
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,938
|
localization.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/localization.hpp
|
#pragma once
#include "arch.h"
#include <cstdint>
#include <windef.h>
#include <wil/win32_helpers.h>
#include "constants.hpp"
#include "util/null_terminated_string_view.hpp"
#include "windows/window.hpp"
namespace Localization {
bool SetProcessLangOverride(std::wstring_view langOverride);
Util::null_terminated_wstring_view LoadLocalizedResourceString(uint16_t resource, HINSTANCE hInst = wil::GetModuleInstanceHandle(), WORD lang = MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL));
std::thread ShowLocalizedMessageBox(uint16_t resource, UINT type, HINSTANCE hInst = wil::GetModuleInstanceHandle(), WORD lang = MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL));
template<typename... Args>
std::thread ShowLocalizedMessageBoxWithFormat(uint16_t resource, UINT type, HINSTANCE hInst, Args&&... args)
{
const auto msg = LoadLocalizedResourceString(resource, hInst);
std::wstring formatted = std::vformat(msg, std::make_wformat_args(std::forward<Args>(args)...));
return std::thread([formatted_msg = std::move(formatted), type]() noexcept
{
MessageBoxEx(Window::NullWindow, formatted_msg.c_str(), APP_NAME, type, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL));
});
}
template<typename Callback>
std::thread ShowLocalizedMessageBoxWithCallback(uint16_t resource, UINT type, HINSTANCE hInst, Callback&& callback)
{
const auto msg = LoadLocalizedResourceString(resource, hInst);
return std::thread([msg, type, callback = std::forward<Callback>(callback)]() mutable noexcept(std::is_nothrow_invocable_v<Callback, int>)
{
const int ret = MessageBoxEx(Window::NullWindow, msg.c_str(), APP_NAME, type, MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL));
std::invoke(std::forward<Callback>(callback), ret);
});
}
}
| 1,725
|
C++
|
.h
| 33
| 49.878788
| 188
| 0.77019
|
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,939
|
mainappwindow.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/mainappwindow.hpp
|
#pragma once
#include "arch.h"
#include "tray/traycontextmenu.hpp"
#include <cstddef>
#include <spdlog/common.h>
#include <tuple>
#include <windef.h>
#include "winrt.hpp"
#include "undefgetcurrenttime.h"
#include <winrt/TranslucentTB.Xaml.Models.Primitives.h>
#include <winrt/TranslucentTB.Xaml.Pages.h>
#include "redefgetcurrenttime.h"
#include "config/config.hpp"
#include "dynamicloader.hpp"
#include "managers/startupmanager.hpp"
#include "util/thread_independent_mutex.hpp"
#include "uwp/basexamlpagehost.hpp"
class Application;
class MainAppWindow final : public TrayContextMenu<winrt::TranslucentTB::Xaml::Pages::TrayFlyoutPage> {
private:
using page_t = winrt::TranslucentTB::Xaml::Pages::TrayFlyoutPage;
Application &m_App;
bool m_HideIconOverride;
Util::thread_independent_mutex m_PickerMutex;
std::array<BaseXamlPageHost*, 7> m_ColorPickers{};
page_t::TaskbarSettingsChanged_revoker m_TaskbarSettingsChangedRevoker;
page_t::ColorRequested_revoker m_ColorRequestedRevoker;
page_t::OpenLogFileRequested_revoker m_OpenLogFileRequestedRevoker;
page_t::LogLevelChanged_revoker m_LogLevelChangedRevoker;
page_t::DumpDynamicStateRequested_revoker m_DumpDynamicStateRequestedRevoker;
page_t::EditSettingsRequested_revoker m_EditSettingsRequestedRevoker;
page_t::ResetSettingsRequested_revoker m_ResetSettingsRequestedRevoker;
page_t::DisableSavingSettingsChanged_revoker m_DisableSavingSettingsChangedRevoker;
page_t::HideTrayRequested_revoker m_HideTrayRequestedRevoker;
page_t::ResetDynamicStateRequested_revoker m_ResetDynamicStateRequestedRevoker;
page_t::CompactThunkHeapRequested_revoker m_CompactThunkHeapRequestedRevoker;
page_t::StartupStateChanged_revoker m_StartupStateChangedRevoker;
page_t::TipsAndTricksRequested_revoker m_TipsAndTricksRequestedRevoker;
page_t::AboutRequested_revoker m_AboutRequestedRevoker;
page_t::ExitRequested_revoker m_ExitRequestedRevoker;
std::optional<UINT> m_NewInstanceMessage;
LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam) override;
void RefreshMenu() override;
void RegisterMenuHandlers();
void TaskbarSettingsChanged(const txmp::TaskbarState &state, const txmp::TaskbarAppearance &appearance);
void ColorRequested(const txmp::TaskbarState &state);
void OpenLogFileRequested();
void LogLevelChanged(const txmp::LogLevel &level);
void DumpDynamicStateRequested();
void EditSettingsRequested();
void ResetSettingsRequested();
void DisableSavingSettingsChanged(bool disabled) noexcept;
void HideTrayRequested();
void ResetDynamicStateRequested();
static void CompactThunkHeapRequested();
winrt::fire_and_forget StartupStateChanged();
static void TipsAndTricksRequested();
void AboutRequested();
void Exit();
TaskbarAppearance &GetConfigForState(const txmp::TaskbarState &state);
void UpdateTrayVisibility(bool visible);
public:
MainAppWindow(Application &app, bool hideIconOverride, bool hasPackageIdentity, HINSTANCE hInstance, DynamicLoader &loader);
void ConfigurationChanged();
void RemoveHideTrayIconOverride();
static void PostNewInstanceNotification();
};
| 3,088
|
C++
|
.h
| 67
| 44.149254
| 125
| 0.842491
|
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,940
|
dynamicloader.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/dynamicloader.hpp
|
#pragma once
#include "arch.h"
#include <libloaderapi.h>
#include <windef.h>
#include <winuser.h>
#include <wil/resource.h>
#include "undoc/user32.hpp"
#include "undoc/uxtheme.hpp"
#include "../ProgramLog/error/win32.hpp"
class DynamicLoader {
wil::unique_hmodule m_User32, m_UxTheme;
PFN_SHOULD_SYSTEM_USE_DARK_MODE m_Ssudm = nullptr;
public:
inline DynamicLoader()
{
m_User32.reset(LoadLibraryEx(L"user32.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32));
if (!m_User32) [[unlikely]]
{
LastErrorHandle(spdlog::level::critical, L"Failed to load user32.dll");
}
m_UxTheme.reset(LoadLibraryEx(L"uxtheme.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32));
if (m_UxTheme)
{
m_Ssudm = reinterpret_cast<PFN_SHOULD_SYSTEM_USE_DARK_MODE>(GetProcAddress(m_UxTheme.get(), MAKEINTRESOURCEA(138)));
if (!m_Ssudm) [[unlikely]]
{
LastErrorHandle(spdlog::level::warn, L"Failed to get address of ShouldSystemUseDarkMode");
}
}
else
{
LastErrorHandle(spdlog::level::warn, L"Failed to load uxtheme.dll");
}
}
DynamicLoader(const DynamicLoader &) = delete;
DynamicLoader &operator =(const DynamicLoader &) = delete;
// Stored by TaskbarAttributeWorker, but only 1 instance
inline PFN_SET_WINDOW_COMPOSITION_ATTRIBUTE SetWindowCompositionAttribute() const
{
const auto fn = reinterpret_cast<PFN_SET_WINDOW_COMPOSITION_ATTRIBUTE>(GetProcAddress(m_User32.get(), UTIL_STRINGIFY_UTF8(SetWindowCompositionAttribute)));
if (!fn) [[unlikely]]
{
LastErrorHandle(spdlog::level::critical, L"Failed to get address of SetWindowCompositionAttribute");
}
return fn;
}
// Used in Application constructor
inline PFN_SET_PREFERRED_APP_MODE SetPreferredAppMode() const
{
if (m_UxTheme)
{
const auto fn = reinterpret_cast<PFN_SET_PREFERRED_APP_MODE>(GetProcAddress(m_UxTheme.get(), MAKEINTRESOURCEA(135)));
if (!fn) [[unlikely]]
{
LastErrorHandle(spdlog::level::warn, L"Failed to get address of SetPreferredAppMode");
}
return fn;
}
else
{
return nullptr;
}
}
// Used in TrayContextMenu constructor, but only 1 TrayContextMenu instance
inline PFN_ALLOW_DARK_MODE_FOR_WINDOW AllowDarkModeForWindow() const
{
if (m_UxTheme)
{
const auto fn = reinterpret_cast<PFN_ALLOW_DARK_MODE_FOR_WINDOW>(GetProcAddress(m_UxTheme.get(), MAKEINTRESOURCEA(133)));
if (!fn) [[unlikely]]
{
LastErrorHandle(spdlog::level::warn, L"Failed to get address of AllowDarkModeForWindow");
}
return fn;
}
else
{
return nullptr;
}
}
// Stored in TrayIcon and TaskbarAttributeWorker
constexpr PFN_SHOULD_SYSTEM_USE_DARK_MODE ShouldSystemUseDarkMode() const noexcept
{
return m_Ssudm;
}
};
| 2,673
|
C++
|
.h
| 86
| 28.186047
| 157
| 0.74359
|
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,941
|
folderwatcher.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/folderwatcher.hpp
|
#pragma once
#include "arch.h"
#include <fileapi.h>
#include <filesystem>
#include <string_view>
#include <type_traits>
#include <windef.h>
#include <wil/resource.h>
class FolderWatcher {
using callback_t = std::add_pointer_t<void(void *, DWORD, std::wstring_view)>;
// this needs to be first for our little casting trick to work
OVERLAPPED m_Overlapped;
wil::unique_virtualalloc_ptr<char[]> m_Buffer;
DWORD m_BufferSize;
bool m_Recursive;
DWORD m_Filter;
wil::unique_hfile m_FolderHandle;
callback_t m_Callback;
static void WINAPI OverlappedCallback(DWORD error, DWORD, OVERLAPPED *overlapped);
void rearm();
public:
FolderWatcher(const std::filesystem::path &path, bool recursive, DWORD filter, callback_t callback, void *context);
~FolderWatcher();
inline FolderWatcher(const FolderWatcher &) = delete;
inline FolderWatcher &operator =(const FolderWatcher &) = delete;
};
| 900
|
C++
|
.h
| 26
| 32.653846
| 116
| 0.771991
|
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,942
|
basecontextmenu.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/tray/basecontextmenu.hpp
|
#pragma once
#include "arch.h"
#include <unordered_set>
#include <windef.h>
#include <wil/resource.h>
#include "winrt.hpp"
#include "undefgetcurrenttime.h"
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.UI.Xaml.Controls.h>
#include <winrt/Windows.UI.Xaml.Hosting.h>
#include "redefgetcurrenttime.h"
#include "../windows/messagewindow.hpp"
class BaseContextMenu : public virtual MessageWindow {
private:
wuxh::DesktopWindowXamlSource m_Source;
Window m_InteropWnd;
std::optional<bool> m_UseXamlMenu;
wil::unique_hmenu m_ContextMenu;
std::unordered_set<wuxc::MenuFlyoutItem> m_Items;
UINT m_ContextMenuClickableId = 0;
static constexpr void ExtendIntoArea(RECT &toExtend, const RECT &area) noexcept
{
if (toExtend.left >= area.right)
{
toExtend.left = area.right - 1;
}
if (toExtend.right <= area.left)
{
toExtend.right = area.left + 1;
}
if (toExtend.top >= area.bottom)
{
toExtend.top = area.bottom - 1;
}
if (toExtend.bottom <= area.top)
{
toExtend.bottom = area.top + 1;
}
}
UINT GetNextClickableId() noexcept;
wil::unique_hmenu BuildContextMenuInner(const wfc::IVector<wuxc::MenuFlyoutItemBase> &items);
HMENU BuildClassicContextMenu(const wuxc::MenuFlyout &flyout);
void TriggerClassicContextMenuItem(UINT item);
void CleanupClassicContextMenu();
protected:
bool ShouldUseXamlMenu();
void ShowClassicContextMenu(const wuxc::MenuFlyout &flyout, POINT pt);
// pass by ref to update the caller's value to represent the new window rect
// if it needed adjustment
void MoveHiddenWindow(RECT &rect);
virtual void RefreshMenu() = 0;
BaseContextMenu();
~BaseContextMenu();
constexpr const wuxh::DesktopWindowXamlSource &source() noexcept
{
return m_Source;
}
public:
void SetXamlContextMenuOverride(const std::optional<bool> &menuOverride);
bool PreTranslateMessage(const MSG &msg);
};
| 1,888
|
C++
|
.h
| 61
| 28.655738
| 94
| 0.771649
|
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,943
|
contextmenu.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/tray/contextmenu.hpp
|
#pragma once
#include "basecontextmenu.hpp"
#include "arch.h"
#include <shellscalingapi.h>
#include <utility>
#include "winrt.hpp"
#include "undefgetcurrenttime.h"
#include <winrt/Windows.UI.Xaml.Controls.h>
#include "redefgetcurrenttime.h"
template<typename T>
class ContextMenu : public BaseContextMenu {
private:
T m_Page;
void ShowTooltip(bool visible)
{
if (const auto tooltip = wuxc::ToolTipService::GetToolTip(m_Page).try_as<wuxc::ToolTip>())
{
tooltip.IsOpen(visible);
}
}
protected:
constexpr const T &page() const noexcept
{
return m_Page;
}
template<typename... Args>
ContextMenu(Args&&... args) : m_Page(std::forward<Args>(args)...)
{
source().Content(m_Page);
}
void ShowAt(RECT rect, POINT pt)
{
if (const auto flyout = m_Page.ContextFlyout().try_as<wuxc::MenuFlyout>())
{
if (ShouldUseXamlMenu())
{
MoveHiddenWindow(rect);
const float scaleFactor = static_cast<float>(GetDpiForWindow(m_WindowHandle)) / USER_DEFAULT_SCREEN_DPI;
flyout.ShowAt(m_Page, {
(pt.x - rect.left) / scaleFactor,
(pt.y - rect.top) / scaleFactor
});
}
else
{
ShowClassicContextMenu(flyout, pt);
}
}
}
void ShowTooltip(RECT rect)
{
MoveHiddenWindow(rect);
ShowTooltip(true);
}
void HideTooltip()
{
ShowTooltip(false);
}
~ContextMenu()
{
source().Content(nullptr);
m_Page = nullptr;
}
};
| 1,382
|
C++
|
.h
| 64
| 18.890625
| 108
| 0.708174
|
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,944
|
traycontextmenu.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/tray/traycontextmenu.hpp
|
#pragma once
#include "contextmenu.hpp"
#include "trayicon.hpp"
#include <windowsx.h>
#include "../dynamicloader.hpp"
#include "../uwp/uwp.hpp"
template<typename T>
class TrayContextMenu : public TrayIcon, public ContextMenu<T> {
private:
static constexpr POINT PointFromParam(WPARAM wParam) noexcept
{
return {
.x = GET_X_LPARAM(wParam),
.y = GET_Y_LPARAM(wParam)
};
}
protected:
template<typename... Args>
inline TrayContextMenu(const GUID &iconId, const wchar_t *whiteIconResource, const wchar_t *darkIconResource, DynamicLoader &loader, Args&&... args) :
TrayIcon(iconId, whiteIconResource, darkIconResource, loader.ShouldSystemUseDarkMode()),
ContextMenu<T>(std::forward<Args>(args)...)
{
if (const auto admfw = loader.AllowDarkModeForWindow())
{
admfw(m_WindowHandle, true);
}
}
inline LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam) override
{
switch (uMsg)
{
case WM_SETTINGCHANGE:
case WM_THEMECHANGED:
if (const auto coreWin = UWP::GetCoreWindow())
{
// forward theme changes to the fake core window
// so that they propagate to our islands
coreWin.send_message(uMsg, wParam, lParam);
}
break;
case TRAY_CALLBACK:
switch (LOWORD(lParam))
{
case WM_CONTEXTMENU:
case WM_LBUTTONUP:
case NIN_KEYSELECT:
case NIN_SELECT:
SetForegroundWindow(m_WindowHandle);
if (const auto rect = GetTrayRect())
{
this->RefreshMenu();
this->ShowAt(*rect, PointFromParam(wParam));
post_message(WM_NULL);
}
return 0;
case NIN_POPUPOPEN:
if (const auto rect = GetTrayRect())
{
this->ShowTooltip(*rect);
}
return 0;
case NIN_POPUPCLOSE:
this->HideTooltip();
return 0;
}
break;
}
return TrayIcon::MessageHandler(uMsg, wParam, lParam);
}
};
| 1,815
|
C++
|
.h
| 70
| 22.428571
| 151
| 0.70951
|
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,945
|
trayicon.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/tray/trayicon.hpp
|
#pragma once
#include "../windows/messagewindow.hpp"
#include <optional>
#include <shellapi.h>
#include <windef.h>
#include <wil/resource.h>
#include "undoc/uxtheme.hpp"
class TrayIcon : public virtual MessageWindow {
private:
NOTIFYICONDATA m_IconData;
const wchar_t *m_whiteIconResource;
const wchar_t *m_darkIconResource;
wil::unique_hicon m_Icon;
// to know if we should restore the icon when explorer restarts,
// may have initially failed to show if TTB started before explorer.
bool m_ShowPreference;
// to avoid redundant or assured failure calls
bool m_CurrentlyShowing;
std::optional<UINT> m_TaskbarCreatedMessage;
PFN_SHOULD_SYSTEM_USE_DARK_MODE m_Ssudm;
const wchar_t *GetThemedIcon() const;
void LoadThemedIcon();
bool Notify(DWORD message, NOTIFYICONDATA *data = nullptr);
protected:
static constexpr UINT TRAY_CALLBACK = 0xBEEF;
LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam) override;
inline void ReturnFocus() noexcept
{
// Focus may have been automatically returned if the tray icon pops up a context menu.
// Ignore error in this case.
Shell_NotifyIcon(NIM_SETFOCUS, &m_IconData);
}
std::optional<RECT> GetTrayRect();
public:
TrayIcon(const GUID &iconId, const wchar_t *whiteIconResource,
const wchar_t *darkIconResource, PFN_SHOULD_SYSTEM_USE_DARK_MODE ssudm);
void Show();
void Hide();
void SendNotification(uint16_t textResource, DWORD infoFlags = NIIF_INFO);
virtual ~TrayIcon() noexcept(false) = 0;
};
| 1,491
|
C++
|
.h
| 41
| 34.195122
| 88
| 0.781882
|
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,946
|
uwp.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/uwp/uwp.hpp
|
#pragma once
#include <filesystem>
#include <optional>
#include <string>
#include "winrt.hpp"
#include <winrt/Windows.System.h>
#include "undefgetcurrenttime.h"
#include <winrt/Windows.UI.Xaml.Hosting.h>
#include "redefgetcurrenttime.h"
#include "../windows/window.hpp"
namespace UWP {
std::optional<std::wstring> GetPackageFamilyName();
std::optional<std::filesystem::path> GetAppStorageFolder();
winrt::fire_and_forget OpenUri(const wf::Uri &uri);
winrt::Windows::System::DispatcherQueueController CreateDispatcherController();
Window GetCoreWindow();
void HideCoreWindow();
wuxh::WindowsXamlManager CreateXamlManager();
};
| 635
|
C++
|
.h
| 19
| 31.947368
| 80
| 0.796417
|
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,947
|
dynamicdependency.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/uwp/dynamicdependency.hpp
|
#pragma once
#include "arch.h"
#include <windef.h>
#include <WinBase.h>
#include <appmodel.h>
#include <wil/resource.h>
#include "util/null_terminated_string_view.hpp"
class DynamicDependency {
wil::unique_process_heap_string m_dependencyId;
PACKAGEDEPENDENCY_CONTEXT m_Context;
public:
DynamicDependency(HMODULE hModule, Util::null_terminated_wstring_view packageFamilyName, const PACKAGE_VERSION &minVersion, bool hasPackageIdentity);
DynamicDependency(const DynamicDependency &) = delete;
DynamicDependency &operator =(const DynamicDependency &) = delete;
~DynamicDependency() noexcept(false);
};
| 611
|
C++
|
.h
| 16
| 36.5
| 150
| 0.811864
|
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,948
|
xamlpagehost.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/uwp/xamlpagehost.hpp
|
#pragma once
#include "basexamlpagehost.hpp"
#include <concepts>
#include <ShObjIdl_core.h>
#include <tuple>
#include <type_traits>
#include <windowsx.h>
#include "winrt.hpp"
#include "undefgetcurrenttime.h"
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.UI.Xaml.h>
#include <winrt/Windows.UI.Xaml.Controls.h>
#include <winrt/Windows.UI.Xaml.Hosting.h>
#include <winrt/Windows.UI.Xaml.Media.h>
#include <winrt/Windows.System.h>
#include <winrt/TranslucentTB.Xaml.Pages.h>
#include "redefgetcurrenttime.h"
#include <wil/cppwinrt_helpers.h>
#include "util/string_macros.hpp"
#include "../ProgramLog/error/win32.hpp"
template<typename T>
class XamlPageHost final : public BaseXamlPageHost {
private:
using callback_t = std::add_pointer_t<void(void*)>;
T m_content;
winrt::Windows::System::DispatcherQueue m_Dispatcher;
winrt::event_token m_AlwaysOnTopChangedToken, m_TitleChangedToken, m_ClosedToken, m_LayoutUpdatedToken;
bool m_PendingSizeUpdate = false;
bool m_EndDragLayoutUpdate = false;
callback_t m_Callback;
void *m_CallbackData;
inline LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam) override
{
switch (uMsg)
{
case WM_ACTIVATE:
if (m_content)
{
m_content.IsActive(wParam != WA_INACTIVE);
}
break;
case WM_SYSCOMMAND:
if (wParam == SC_CLOSE)
{
TryClose();
return 0;
}
break;
case WM_PAINT:
{
if (const auto brush = m_content.Background().try_as<wux::Media::AcrylicBrush>())
{
PAINTSTRUCT ps;
const auto paint = wil::BeginPaint(m_WindowHandle, &ps);
if (paint && PaintBackground(ps.hdc, ps.rcPaint, brush.FallbackColor()))
{
return 0;
}
}
break;
}
case WM_ERASEBKGND:
{
const auto rect = client_rect();
const auto brush = m_content.Background().try_as<wux::Media::AcrylicBrush>();
if (rect && brush && PaintBackground(reinterpret_cast<HDC>(wParam), *rect, brush.FallbackColor()))
{
return 1;
}
break;
}
case WM_CLOSE:
TryClose();
return 0;
case WM_EXITSIZEMOVE:
// some post-DPI change fixups if the size is not divisible by 4
m_EndDragLayoutUpdate = true;
m_content.InvalidateMeasure();
m_content.InvalidateArrange();
return 0;
case WM_SYSKEYDOWN:
if (wParam == VK_SPACE)
{
m_content.ShowSystemMenu({ 0, 0 });
return 0;
}
break;
case WM_NCLBUTTONDOWN:
m_content.HideSystemMenu();
if (wParam == HTCAPTION && !m_content.CanMove())
{
return 0;
}
break;
case WM_NCRBUTTONUP:
if (wParam == HTCAPTION)
{
if (const auto wndRect = rect())
{
const auto x = GET_X_LPARAM(lParam);
const auto y = GET_Y_LPARAM(lParam);
const auto scale = GetDpiScale(monitor());
m_content.ShowSystemMenu({
(x - wndRect->left) / scale,
(y - wndRect->top) / scale
});
return 0;
}
}
break;
case WM_MOUSEHOVER:
case WM_MOUSELEAVE:
m_content.TitleTooltipVisible(uMsg == WM_MOUSEHOVER);
return 0;
}
return BaseXamlPageHost::MessageHandler(uMsg, wParam, lParam);
}
inline winrt::fire_and_forget InitialXamlLayoutChanged(xaml_startup_position position)
{
m_content.LayoutUpdated(m_LayoutUpdatedToken);
m_LayoutUpdatedToken = { };
co_await wil::resume_foreground(m_Dispatcher, winrt::Windows::System::DispatcherQueuePriority::Low);
POINT cursor = { 0, 0 };
const HMONITOR mon = GetInitialMonitor(cursor, position);
MONITORINFO info = { sizeof(info) };
const auto [windowSize, dragRegion, buttonRegion] = GetXamlSize(mon, info);
int width = static_cast<int>(windowSize.Width),
height = static_cast<int>(windowSize.Height),
x = 0,
y = 0;
CalculateInitialPosition(x, y, width, height, cursor, info.rcWork, position);
ResizeWindow(x, y, width, height, true, SWP_SHOWWINDOW);
PositionDragRegion(dragRegion, buttonRegion, SWP_SHOWWINDOW);
SetForegroundWindow(m_WindowHandle);
m_LayoutUpdatedToken = m_content.LayoutUpdated({ this, &XamlPageHost::OnXamlLayoutChanged });
}
inline winrt::fire_and_forget OnXamlLayoutChanged(const wf::IInspectable &, const wf::IInspectable &)
{
if (!m_PendingSizeUpdate)
{
m_PendingSizeUpdate = true;
const auto guard = wil::scope_exit([this]() noexcept
{
m_EndDragLayoutUpdate = false;
m_PendingSizeUpdate = false;
});
co_await wil::resume_foreground(m_Dispatcher, winrt::Windows::System::DispatcherQueuePriority::Low);
if (m_content)
{
MONITORINFO info = { sizeof(info) };
const auto [windowSize, dragRegion, buttonRegion] = GetXamlSize(monitor(), info);
const auto newHeight = static_cast<int>(windowSize.Height);
const auto newWidth = static_cast<int>(windowSize.Width);
const auto wndRect = rect();
if (wndRect && (m_EndDragLayoutUpdate || wndRect->bottom - wndRect->top != newHeight || wndRect->right - wndRect->left != newWidth)) [[unlikely]]
{
bool move = true;
int x = wndRect->left, y = wndRect->top;
if (!m_EndDragLayoutUpdate)
{
move = AdjustWindowPosition(x, y, newWidth, newHeight, info.rcWork);
}
ResizeWindow(x, y, newWidth, newHeight, move);
}
PositionDragRegion(dragRegion, buttonRegion);
}
}
}
inline std::tuple<wf::Size, wf::Rect, wf::Rect> GetXamlSize(HMONITOR mon, MONITORINFO &info)
{
if (!GetMonitorInfo(mon, &info)) [[unlikely]]
{
LastErrorHandle(spdlog::level::warn, L"Failed to get monitor info");
return { };
}
const auto scale = GetDpiScale(mon);
wf::Size size = {
(info.rcWork.right - info.rcWork.left) / scale,
(info.rcWork.bottom - info.rcWork.top) / scale
};
m_content.Measure(size);
size = m_content.DesiredSize();
m_content.UpdateLayout(); // prevent the call to Measure from firing a LayoutUpdated event
return {
{
size.Width * scale,
size.Height * scale
},
ScaleRect(m_content.DragRegion(), scale),
ScaleRect(m_content.TitlebarButtonsRegion(), scale)
};
}
inline void UpdateTitle(const wux::DependencyObject &, const wux::DependencyProperty &)
{
if (!SetWindowText(m_WindowHandle, m_content.Title().c_str()))
{
LastErrorHandle(spdlog::level::warn, L"Failed to set window title");
}
}
inline void UpdateAlwaysOnTop(const wux::DependencyObject &, const wux::DependencyProperty &)
{
const auto wnd = m_content.AlwaysOnTop() ? Window::TopMostWindow : Window::NoTopMostWindow;
if (!SetWindowPos(m_WindowHandle, wnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE))
{
LastErrorHandle(spdlog::level::warn, L"Failed to change window topmost state");
}
}
winrt::fire_and_forget OnClose()
{
Cleanup();
// dispatch the deletion because cleaning up the XAML source here makes the XAML framework very angry
co_await wil::resume_foreground(m_Dispatcher, winrt::Windows::System::DispatcherQueuePriority::Low);
BaseXamlPageHost::Cleanup();
if (m_Callback)
{
m_Callback(m_CallbackData);
}
}
void Cleanup()
{
if (m_content)
{
show(SW_HIDE);
if (m_LayoutUpdatedToken)
{
m_content.LayoutUpdated(m_LayoutUpdatedToken);
m_LayoutUpdatedToken = { };
}
source().Content(nullptr);
m_content.Closed(m_ClosedToken);
using winrt::TranslucentTB::Xaml::Pages::FramelessPage;
m_content.UnregisterPropertyChangedCallback(FramelessPage::TitleProperty(), m_TitleChangedToken.value);
m_content.UnregisterPropertyChangedCallback(FramelessPage::AlwaysOnTopProperty(), m_AlwaysOnTopChangedToken.value);
m_content = nullptr;
}
}
public:
inline ~XamlPageHost()
{
Cleanup();
}
template<typename... Args>
inline XamlPageHost(WindowClass &classRef, WindowClass &dragRegionClass, xaml_startup_position position,
winrt::Windows::System::DispatcherQueue dispatcher, callback_t callback,
void *data, Args&&... args) :
BaseXamlPageHost(classRef, dragRegionClass),
m_content(std::forward<Args>(args)...),
m_Dispatcher(std::move(dispatcher)),
m_Callback(callback),
m_CallbackData(data)
{
UpdateTitle(nullptr, nullptr);
UpdateAlwaysOnTop(nullptr, nullptr);
using winrt::TranslucentTB::Xaml::Pages::FramelessPage;
m_AlwaysOnTopChangedToken.value = m_content.RegisterPropertyChangedCallback(FramelessPage::AlwaysOnTopProperty(), { this, &XamlPageHost::UpdateAlwaysOnTop });
m_TitleChangedToken.value = m_content.RegisterPropertyChangedCallback(FramelessPage::TitleProperty(), { this, &XamlPageHost::UpdateTitle });
m_ClosedToken = m_content.Closed({ this, &XamlPageHost::OnClose });
m_LayoutUpdatedToken = m_content.LayoutUpdated([this, position](const wf::IInspectable &, const wf::IInspectable &)
{
InitialXamlLayoutChanged(position);
});
source().Content(m_content);
if (const auto initWithWnd = m_content.try_as<IInitializeWithWindow>())
{
HresultVerify(initWithWnd->Initialize(m_WindowHandle), spdlog::level::warn, L"Failed to initialize with window");
}
// TODO: no animation when closing through alt-space menu with keyboard
}
inline winrt::TranslucentTB::Xaml::Pages::FramelessPage page() noexcept override
{
return m_content;
}
inline constexpr const T &content() noexcept
{
return m_content;
}
bool TryClose() override
{
if (!m_content || m_content.RequestClose())
{
return true;
}
else
{
SetForegroundWindow(m_WindowHandle);
return false;
}
}
};
| 9,291
|
C++
|
.h
| 289
| 28.653979
| 160
| 0.720863
|
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,949
|
xamlthread.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/uwp/xamlthread.hpp
|
#pragma once
#include "arch.h"
#include <cassert>
#include <functional>
#include <memory>
#include <mutex>
#include <utility>
#include <windef.h>
#include <WinBase.h>
#include <wil/resource.h>
#include <windows.ui.xaml.hosting.desktopwindowxamlsource.h>
#include "winrt.hpp"
#include <winrt/Windows.System.h>
#include "undefgetcurrenttime.h"
#include <winrt/Windows.UI.Xaml.Hosting.h>
#include "redefgetcurrenttime.h"
#include <wil/cppwinrt_helpers.h>
#include "xamlpagehost.hpp"
#include "../../ProgramLog/error/winrt.hpp"
#include "undoc/uxtheme.hpp"
#include "util/thread_independent_mutex.hpp"
#include "util/type_traits.hpp"
class XamlThread {
private:
wil::unique_handle m_Thread;
wil::slim_event_manual_reset m_Ready;
winrt::Windows::System::DispatcherQueueController m_Dispatcher;
wuxh::WindowsXamlManager m_Manager;
winrt::com_ptr<IDesktopWindowXamlSourceNative2> m_Source;
Util::thread_independent_mutex m_CurrentWindowLock;
std::unique_ptr<BaseXamlPageHost> m_CurrentWindow;
static DWORD WINAPI ThreadProc(LPVOID param);
static void DeletedCallback(void *data);
void ThreadInit();
bool PreTranslateMessage(const MSG &msg);
winrt::fire_and_forget ThreadDeinit();
public:
XamlThread();
XamlThread(const XamlThread &thread) = delete;
XamlThread &operator =(const XamlThread &thread) = delete;
std::unique_lock<Util::thread_independent_mutex> Lock() noexcept
{
return std::unique_lock { m_CurrentWindowLock };
}
bool IsAvailable() const noexcept
{
return m_CurrentWindow == nullptr;
}
const std::unique_ptr<BaseXamlPageHost> &GetCurrentWindow() const
{
return m_CurrentWindow;
}
template<typename T, typename Callback, typename... Args>
winrt::fire_and_forget CreateXamlWindow(std::unique_lock<Util::thread_independent_mutex> lock, WindowClass &classRef, WindowClass& dragRegionClass, xaml_startup_position pos, Callback callback, Args... args)
{
// more than one window per thread is technically doable but impractical,
// because XAML Islands has a ton of bugs when hosting more than 1 window per thread
assert(m_CurrentWindow == nullptr);
co_await wil::resume_foreground(GetDispatcher());
std::unique_ptr<XamlPageHost<T>> host;
try
{
host = std::make_unique<XamlPageHost<T>>(classRef, dragRegionClass, pos, m_Dispatcher.DispatcherQueue(), DeletedCallback, this, args...);
}
HresultErrorCatch(spdlog::level::critical, L"Failed to create XAML window");
m_Source = host->source().try_as<IDesktopWindowXamlSourceNative2>();
std::invoke(callback, host->content(), static_cast<BaseXamlPageHost *>(host.get()));
m_CurrentWindow = std::move(host);
}
wil::unique_handle Delete();
winrt::Windows::System::DispatcherQueue GetDispatcher() const
{
return m_Dispatcher.DispatcherQueue();
}
~XamlThread()
{
if (m_Manager)
{
m_Manager.Close();
m_Manager = nullptr;
}
// let the XAML framework cleanup
MSG msg{};
while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
};
| 3,033
|
C++
|
.h
| 90
| 31.377778
| 208
| 0.764203
|
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,950
|
xamlthreadpool.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/uwp/xamlthreadpool.hpp
|
#pragma once
#include "arch.h"
#include <memory>
#include <utility>
#include <vector>
#include <windef.h>
#include "../../ProgramLog/error/winrt.hpp"
#include "undoc/uxtheme.hpp"
#include "../windows/windowclass.hpp"
#include "xamlpagehost.hpp"
#include "xamlthread.hpp"
class XamlThreadPool {
WindowClass m_WndClass;
WindowClass m_DragRegionClass;
std::vector<std::unique_ptr<XamlThread>> m_Threads;
XamlThread &GetAvailableThread(std::unique_lock<Util::thread_independent_mutex> &lock);
public:
XamlThreadPool(const XamlThreadPool &) = delete;
XamlThreadPool &operator =(const XamlThreadPool &) = delete;
inline XamlThreadPool(HINSTANCE hInst) :
m_WndClass(MessageWindow::MakeWindowClass(L"XamlPageHost", hInst)),
m_DragRegionClass(MessageWindow::MakeWindowClass(L"XamlDragRegion", hInst))
{ }
template<typename T, typename Callback, typename... Args>
void CreateXamlWindow(xaml_startup_position pos, Callback &&callback, Args&&... args)
{
std::unique_lock<Util::thread_independent_mutex> guard;
XamlThread &thread = GetAvailableThread(guard);
thread.CreateXamlWindow<T>(std::move(guard), m_WndClass, m_DragRegionClass, pos, std::forward<Callback>(callback), std::forward<Args>(args)...);
}
~XamlThreadPool();
const std::vector<std::unique_ptr<XamlThread>> &GetThreads() const
{
return m_Threads;
}
};
| 1,340
|
C++
|
.h
| 36
| 35.222222
| 146
| 0.770833
|
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,951
|
basexamlpagehost.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/uwp/basexamlpagehost.hpp
|
#pragma once
#include "../windows/messagewindow.hpp"
#include "arch.h"
#include <windef.h>
#include "winrt.hpp"
#include "undefgetcurrenttime.h"
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.UI.Xaml.Hosting.h>
#include <winrt/TranslucentTB.Xaml.Pages.h>
#include "redefgetcurrenttime.h"
#include "../windows/windowclass.hpp"
#include "xamldragregion.hpp"
enum class xaml_startup_position {
center,
mouse
};
class BaseXamlPageHost : public MessageWindow {
private:
XamlDragRegion m_DragRegion;
Window m_interopWnd;
wuxh::DesktopWindowXamlSource m_source;
winrt::event_token m_focusToken;
wil::unique_hbrush m_BackgroundBrush;
winrt::Windows::UI::Color m_BackgroundColor = { };
void UpdateFrame();
protected:
static wf::Rect ScaleRect(wf::Rect rect, float scale);
static HMONITOR GetInitialMonitor(POINT &cursor, xaml_startup_position position);
static float GetDpiScale(HMONITOR mon);
static void CalculateInitialPosition(int &x, int &y, int width, int height, POINT cursor, const RECT &workArea, xaml_startup_position position) noexcept;
static bool AdjustWindowPosition(int &x, int &y, int width, int height, const RECT &workArea) noexcept;
LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam) override;
void ResizeWindow(int x, int y, int width, int height, bool move, UINT flags = 0);
void PositionDragRegion(wf::Rect position, wf::Rect buttonsRegion, UINT flags = 0);
bool PaintBackground(HDC dc, const RECT &target, winrt::Windows::UI::Color col);
BaseXamlPageHost(WindowClass &classRef, WindowClass &dragRegionClass);
void Cleanup()
{
if (m_source)
{
if (m_focusToken)
{
m_source.TakeFocusRequested(m_focusToken);
m_focusToken.value = 0;
}
m_source.Close();
m_source = nullptr;
}
m_BackgroundBrush.reset();
}
public:
virtual ~BaseXamlPageHost()
{
Cleanup();
}
constexpr const wuxh::DesktopWindowXamlSource &source() noexcept
{
return m_source;
}
virtual winrt::TranslucentTB::Xaml::Pages::FramelessPage page() noexcept = 0;
virtual bool TryClose() = 0;
};
| 2,071
|
C++
|
.h
| 62
| 31.080645
| 154
| 0.769076
|
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,952
|
xamldragregion.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/uwp/xamldragregion.hpp
|
#pragma once
#include "winrt.hpp"
#include <winrt/Windows.Foundation.h>
#include "../windows/messagewindow.hpp"
class XamlDragRegion final : public MessageWindow {
private:
wf::Rect m_ButtonsRegion = { };
bool m_Tracking = false;
void HandleClick(UINT msg, LPARAM lParam) noexcept;
LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam) override;
void SetRegion(int width, int height, wf::Rect buttonsRegion);
public:
XamlDragRegion(WindowClass &classRef, Window parent);
void Position(const RECT &parentRect, wf::Rect position, wf::Rect buttonsRegion, UINT flags);
};
| 590
|
C++
|
.h
| 15
| 37.533333
| 94
| 0.787719
|
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,953
|
ids.h
|
TranslucentTB_TranslucentTB/TranslucentTB/resources/ids.h
|
#pragma once
#define IDI_MAINICON 101
#define IDI_TRAYWHITEICON 102
#define IDI_TRAYBLACKICON 103
#define IDS_WELCOME_NOTIFICATION 60001
#define IDS_HIDE_TRAY 60002
#define IDS_ALREADY_RUNNING 60003
#define IDS_LANGUAGE_CHANGED 60004
#define IDS_RESTART_REQUIRED 60005
#define IDS_PORTABLE_UNSUPPORTED 60006
#define IDS_MISSING_DEPENDENCIES 60007
#define IDS_EXPLORER_RESTARTED_TOO_MUCH 60008
#define IDS_STARTUPTASK_BROKEN 60009
| 597
|
C++
|
.h
| 13
| 44.769231
| 48
| 0.611684
|
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,954
|
configmanager.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/managers/configmanager.hpp
|
#pragma once
#include "arch.h"
#include <filesystem>
#include <optional>
#include <string_view>
#include <synchapi.h>
#include <type_traits>
#include <wil/resource.h>
#include "config/config.hpp"
#include "../folderwatcher.hpp"
class ConfigManager {
// we use settings.json because it makes VS Code automatically recognize
// the file as JSON with comments
static constexpr std::wstring_view CONFIG_FILE = L"settings.json";
static constexpr std::wstring_view SCHEMA_KEY = L"$schema";
using callback_t = std::add_pointer_t<void(void *)>;
static std::filesystem::path DetermineConfigPath(const std::optional<std::filesystem::path> &storageFolder);
static void WatcherCallback(void *context, DWORD, std::wstring_view fileName);
static void APIENTRY TimerCallback(void *context, DWORD timerLow, DWORD timerHigh);
std::filesystem::path m_ConfigPath;
Config m_Config;
FolderWatcher m_Watcher;
wil::unique_handle m_ReloadTimer;
std::wstring m_StartupLanguage;
bool m_ShownChangeWarning;
callback_t m_Callback;
void *m_Context;
bool TryOpenConfigAsJson() noexcept;
void SaveToFile(FILE *f) const;
bool LoadFromFile(FILE *f);
bool Load(bool firstLoad = false);
void Reload();
bool ScheduleReload();
public:
ConfigManager(const std::optional<std::filesystem::path> &storageFolder, bool &fileExists, callback_t callback, void *context);
~ConfigManager();
void UpdateVerbosity();
void EditConfigFile();
void DeleteConfigFile();
void SaveConfig() const;
constexpr Config &GetConfig() noexcept
{
return m_Config;
}
};
| 1,549
|
C++
|
.h
| 45
| 32.422222
| 128
| 0.77882
|
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,955
|
startupmanager.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/managers/startupmanager.hpp
|
#pragma once
#include <optional>
#include "winrt.hpp"
#include <winrt/Windows.ApplicationModel.h>
#include <winrt/Windows.Foundation.h>
class StartupManager {
private:
winrt::Windows::ApplicationModel::StartupTask m_StartupTask;
public:
inline StartupManager() noexcept : m_StartupTask(nullptr) { }
winrt::fire_and_forget AcquireTask();
std::optional<winrt::Windows::ApplicationModel::StartupTaskState> GetState() const;
wf::IAsyncAction Enable();
void Disable();
static void OpenSettingsPage();
inline explicit operator bool() const noexcept
{
return m_StartupTask != nullptr;
}
};
| 600
|
C++
|
.h
| 20
| 28.15
| 84
| 0.789565
|
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,956
|
launchervisibilitysink.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/taskbar/launchervisibilitysink.hpp
|
#pragma once
#include "arch.h"
#include <ShObjIdl.h>
#include "winrt.hpp"
#include "../windows/window.hpp"
class LauncherVisibilitySink : public winrt::implements<LauncherVisibilitySink, IAppVisibilityEvents> {
Window m_Wnd;
UINT m_Msg;
IFACEMETHODIMP LauncherVisibilityChange(BOOL currentVisibleState) noexcept override
{
m_Wnd.post_message(m_Msg, currentVisibleState);
return S_OK;
}
IFACEMETHODIMP AppVisibilityOnMonitorChanged(HMONITOR, MONITOR_APP_VISIBILITY, MONITOR_APP_VISIBILITY) noexcept override
{
return S_OK;
}
public:
LauncherVisibilitySink(Window wnd, UINT msg) noexcept : m_Wnd(wnd), m_Msg(msg) { }
};
| 638
|
C++
|
.h
| 20
| 29.9
| 121
| 0.799347
|
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,957
|
taskbarattributeworker.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/taskbar/taskbarattributeworker.hpp
|
#pragma once
#include "arch.h"
#include <array>
#include <chrono>
#include <member_thunk/page.hpp>
#include <optional>
#include <ShObjIdl.h>
#include <string_view>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <wil/com.h>
#include <wil/resource.h>
#include "winrt.hpp"
#include <winrt/TranslucentTB.Xaml.Models.Primitives.h>
#include <winrt/Windows.Internal.Shell.Experience.h> // this is evil >:3
#include <winrt/WindowsUdk.UI.Shell.h> // this is less evil
#include "config/config.hpp"
#include "config/taskbarappearance.hpp"
#include "../dynamicloader.hpp"
#include "../ExplorerHooks/api.hpp"
#include "../ExplorerTAP/api.hpp"
#include "ITaskbarAppearanceService.h"
#include "launchervisibilitysink.hpp"
#include "../windows/messagewindow.hpp"
#include "undoc/user32.hpp"
#include "undoc/uxtheme.hpp"
#include "util/color.hpp"
#include "util/null_terminated_string_view.hpp"
#include "wilx.hpp"
#include "../ProgramLog/error/win32.hpp"
#include "../loadabledll.hpp"
class TaskbarAttributeWorker final : public MessageWindow {
private:
class AttributeRefresher;
friend AttributeRefresher;
struct TaskbarInfo {
Window TaskbarWindow;
Window PeekWindow;
Window InnerXamlContent;
Window WorkerWWindow;
};
struct MonitorInfo {
TaskbarInfo Taskbar;
std::unordered_set<Window> MaximisedWindows;
std::unordered_set<Window> NormalWindows;
};
struct MonitorEnumInfo {
Window window;
HMONITOR monitor;
};
// future improvements:
// - better aero peek support: detect current peeked to window and include in calculation
// - notification for owner changes
// - notification for extended style changes
// - notification for property changes: this is what is making the discord window not being correctly accounted for after restoring from tray
// for some reason it shows itself (which we do capture) and then unsets ITaskList_Deleted (which we don't capture)
// - handle cases where we dont get EVENT_SYSTEM_FOREGROUND when unminimizing a window
// - add an option for peek to consider main monitor only or all monitors
// if yes, should always refresh peek whenever anything changes
// and need some custom logic to check all monitors
// - make settings optional so that they stack on top of each other?
// The magic function that does the thing
const PFN_SET_WINDOW_COMPOSITION_ATTRIBUTE SetWindowCompositionAttribute;
const PFN_SHOULD_SYSTEM_USE_DARK_MODE ShouldSystemUseDarkMode;
// State
bool m_PowerSaver;
bool m_TaskViewActive;
bool m_PeekActive;
bool m_disableAttributeRefreshReply;
bool m_ResettingState;
bool m_ResetStateReentered;
HMONITOR m_CurrentStartMonitor;
HMONITOR m_CurrentSearchMonitor;
Window m_ForegroundWindow;
std::unordered_map<HMONITOR, MonitorInfo> m_Taskbars;
std::unordered_set<Window> m_NormalTaskbars;
const Config &m_Config;
// Hooks
member_thunk::page m_ThunkPage;
wil::unique_hwineventhook m_PeekUnpeekHook;
wil::unique_hwineventhook m_CloakUncloakHook;
wil::unique_hwineventhook m_MinimizeRestoreHook;
wil::unique_hwineventhook m_ResizeMoveHook;
wil::unique_hwineventhook m_ShowHideHook;
wil::unique_hwineventhook m_CreateDestroyHook;
wil::unique_hwineventhook m_ForegroundChangeHook;
wil::unique_hwineventhook m_TitleChangeHook;
wil::unique_hwineventhook m_ParentChangeHook;
wil::unique_hwineventhook m_OrderChangeHook;
wil::unique_hpowernotify m_PowerSaverHook;
// IAppVisibility
wil::com_ptr<IAppVisibility> m_IAV;
wilx::unique_com_token<&IAppVisibility::Unadvise> m_IAVECookie;
// ICortanaExperienceManager
winrt::Windows::Internal::Shell::Experience::ICortanaExperienceManager m_SearchManager;
winrt::event_token m_SuggestionsShownToken, m_SuggestionsHiddenToken;
// ShellViewCoordinator
winrt::WindowsUdk::UI::Shell::ShellViewCoordinator m_SearchViewCoordinator;
winrt::event_token m_SearchViewVisibilityChangedToken;
winrt::WindowsUdk::UI::Shell::ShellViewCoordinator m_FindInStartViewCoordinator;
winrt::event_token m_FindInStartVisibilityChangedToken;
LPARAM m_highestSeenSearchSource;
// Messages
std::optional<UINT> m_TaskbarCreatedMessage;
std::optional<UINT> m_RefreshRequestedMessage;
std::optional<UINT> m_TaskViewVisibilityChangeMessage;
std::optional<UINT> m_IsTaskViewOpenedMessage;
std::optional<UINT> m_StartVisibilityChangeMessage;
std::optional<UINT> m_SearchVisibilityChangeMessage;
std::optional<UINT> m_ForceRefreshTaskbar;
// Explorer crash detection
std::chrono::steady_clock::time_point m_LastExplorerRestart;
DWORD m_LastExplorerPid;
// Color previews
std::array<std::optional<Util::Color>, 7> m_ColorPreviews;
// Hook DLL
LoadableDll m_HookDll;
PFN_INJECT_EXPLORER_HOOK m_InjectExplorerHook;
std::vector<wil::unique_hhook> m_Hooks;
// TAP DLL
LoadableDll m_TAPDll;
PFN_INJECT_EXPLORER_TAP m_InjectExplorerTAP;
winrt::com_ptr<ITaskbarAppearanceService> m_TaskbarService;
// Other
bool m_IsWindows11;
// Type aliases
using taskbar_iterator = decltype(m_Taskbars)::iterator;
// Callbacks
template<DWORD insert, DWORD remove>
void CALLBACK WindowInsertRemove(DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD, DWORD);
void CALLBACK OnAeroPeekEnterExit(DWORD event, HWND, LONG, LONG, DWORD, DWORD);
void CALLBACK OnWindowStateChange(DWORD, HWND hwnd, LONG idObject, LONG idChild, DWORD, DWORD);
void CALLBACK OnWindowCreateDestroy(DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD, DWORD);
void CALLBACK OnForegroundWindowChange(DWORD, HWND hwnd, LONG idObject, LONG idChild, DWORD, DWORD);
void CALLBACK OnWindowOrderChange(DWORD, HWND hwnd, LONG idObject, LONG idChild, DWORD, DWORD);
void OnStartVisibilityChange(bool state);
void OnTaskViewVisibilityChange(bool state);
void OnSearchVisibilityChange(bool state);
void OnForceRefreshTaskbar(Window taskbar);
LRESULT OnSystemSettingsChange(UINT uiAction);
LRESULT OnPowerBroadcast(const POWERBROADCAST_SETTING *settings);
LRESULT OnRequestAttributeRefresh(LPARAM lParam);
LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam) override;
// Config
TaskbarAppearance GetConfig(taskbar_iterator taskbar) const;
// Attribute
void ShowAeroPeekButton(const TaskbarInfo &taskbar, bool show);
void ShowTaskbarLine(const TaskbarInfo &taskbar, bool show);
void SetAttribute(taskbar_iterator taskbar, TaskbarAppearance config);
void RefreshAttribute(taskbar_iterator taskbar);
void RefreshAllAttributes();
// Log
static void LogWindowInsertion(const std::pair<std::unordered_set<Window>::iterator, bool> &result, std::wstring_view state, HMONITOR mon);
static void LogWindowRemoval(std::wstring_view state, Window window, HMONITOR mon);
static void LogWindowRemovalDestroyed(std::wstring_view state, Window window, HMONITOR mon);
// State
void InsertWindow(Window window, bool refresh);
template<void(*logger)(std::wstring_view, Window, HMONITOR) = LogWindowRemoval>
void RemoveWindow(Window window, taskbar_iterator it, AttributeRefresher &refresher);
// Other
static bool SetNewWindowExStyle(Window wnd, LONG_PTR oldStyle, LONG_PTR newStyle);
static bool SetContainsValidWindows(std::unordered_set<Window> &set);
static void DumpWindowSet(std::wstring_view prefix, const std::unordered_set<Window> &set, bool showInfo = true);
static std::wstring DumpWindow(Window window);
void CreateAppVisibility();
void CreateSearchManager();
void UnregisterSearchCallbacks() noexcept;
WINEVENTPROC CreateThunk(void (CALLBACK TaskbarAttributeWorker:: *proc)(DWORD, HWND, LONG, LONG, DWORD, DWORD));
static wil::unique_hwineventhook CreateHook(DWORD eventMin, DWORD eventMax, WINEVENTPROC proc);
void ReturnToStock();
bool IsStartMenuOpened() const;
bool IsSearchOpened() const;
void InsertTaskbar(HMONITOR mon, Window window);
static BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData);
static HMONITOR GetTaskbarMonitor(Window taskbar);
inline TaskbarAppearance WithPreview(txmp::TaskbarState state, const TaskbarAppearance &appearance) const
{
const auto &preview = m_ColorPreviews.at(static_cast<std::size_t>(state));
if (preview)
{
return { appearance.Accent, *preview, appearance.ShowPeek, appearance.ShowLine };
}
else
{
return appearance;
}
}
inline static HMONITOR GetStartMenuMonitor() noexcept
{
// we assume that start is the current foreground window;
// haven't seen a case where that wasn't true yet.
// NOTE: this only stands *when* we get notified that
// start has opened (and as long as it is). when we get
// notified that it's closed another window may be the
// foreground window already (eg the user dismissed start
// by clicking on a window)
Sleep(5); // give it a bit of delay because sometimes it doesn't capture it right
return Window::ForegroundWindow().monitor();
}
inline static HMONITOR GetSearchMonitor() noexcept
{
// same assumption for search
Sleep(5);
return Window::ForegroundWindow().monitor();
}
inline static wil::unique_hwineventhook CreateHook(DWORD event, WINEVENTPROC proc)
{
return CreateHook(event, event, proc);
}
public:
TaskbarAttributeWorker(const Config &cfg, HINSTANCE hInstance, DynamicLoader &loader, const std::optional<std::filesystem::path> &storageFolder);
inline void ConfigurationChanged()
{
RefreshAllAttributes();
}
void ApplyColorPreview(txmp::TaskbarState state, Util::Color color)
{
m_ColorPreviews.at(static_cast<std::size_t>(state)) = color;
ConfigurationChanged();
}
inline void RemoveColorPreview(txmp::TaskbarState state)
{
m_ColorPreviews.at(static_cast<std::size_t>(state)).reset();
ConfigurationChanged();
}
void DumpState();
void ResetState(bool manual = false);
~TaskbarAttributeWorker() noexcept(false);
};
| 9,749
|
C++
|
.h
| 230
| 40.217391
| 146
| 0.798882
|
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,958
|
window.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/windows/window.hpp
|
#pragma once
#include "arch.h"
#include <dwmapi.h>
#include <errhandlingapi.h>
#include <filesystem>
#include <string>
#include <optional>
#include <utility>
#include <windef.h>
#include <winerror.h>
#include <winuser.h>
#include "../ProgramLog/error/win32.hpp"
#include "util/null_terminated_string_view.hpp"
#include "windowclass.hpp"
class Window {
template<DWMWINDOWATTRIBUTE attrib>
struct attrib_return_type;
template<>
struct attrib_return_type<DWMWA_NCRENDERING_ENABLED> {
using type = BOOL;
};
template<>
struct attrib_return_type<DWMWA_CAPTION_BUTTON_BOUNDS> {
using type = RECT;
};
template<>
struct attrib_return_type<DWMWA_EXTENDED_FRAME_BOUNDS> {
using type = RECT;
};
template<>
struct attrib_return_type<DWMWA_CLOAKED> {
using type = DWORD;
};
template<DWMWINDOWATTRIBUTE attrib>
inline std::optional<typename attrib_return_type<attrib>::type> get_attribute() const
{
typename attrib_return_type<attrib>::type val;
const HRESULT hr = DwmGetWindowAttribute(m_WindowHandle, attrib, &val, sizeof(val));
if (SUCCEEDED(hr))
{
return val;
}
else
{
HresultHandle(hr, spdlog::level::info, L"Failed to get window attribute.");
return std::nullopt;
}
}
static std::optional<std::filesystem::path> TryGetNtImageName(DWORD pid);
protected:
HWND m_WindowHandle;
public:
static constexpr HWND NullWindow = nullptr;
inline static const HWND BroadcastWindow = HWND_BROADCAST;
inline static const HWND MessageOnlyWindow = HWND_MESSAGE;
inline static const HWND TopMostWindow = HWND_TOPMOST;
inline static const HWND NoTopMostWindow = HWND_NOTOPMOST;
class FindEnum;
class OrderedEnum;
inline static Window Find(Util::null_terminated_wstring_view className = { }, Util::null_terminated_wstring_view windowName = { }, Window parent = Window::NullWindow, Window childAfter = Window::NullWindow) noexcept
{
return FindWindowEx(parent, childAfter, className.empty() ? nullptr : className.c_str(), windowName.empty() ? nullptr : windowName.c_str());
}
inline static Window Create(DWORD dwExStyle, const WindowClass &winClass,
Util::null_terminated_wstring_view windowName, DWORD dwStyle, int x = CW_USEDEFAULT, int y = CW_USEDEFAULT,
int nWidth = CW_USEDEFAULT, int nHeight = CW_USEDEFAULT, Window parent = Window::NullWindow,
HMENU hMenu = nullptr, void *lpParam = nullptr) noexcept
{
return CreateWindowEx(dwExStyle, winClass.atom(), windowName.c_str(), dwStyle, x, y, nWidth, nHeight,
parent, hMenu, winClass.hinstance(), lpParam);
}
inline static std::optional<UINT> RegisterMessage(Util::null_terminated_wstring_view message)
{
const UINT msg = RegisterWindowMessage(message.c_str());
if (msg)
{
return msg;
}
else
{
LastErrorHandle(spdlog::level::warn, L"Failed to register window message");
return std::nullopt;
}
}
inline static Window ForegroundWindow() noexcept
{
return GetForegroundWindow();
}
inline static Window DesktopWindow() noexcept
{
return GetDesktopWindow();
}
inline static Window ShellWindow() noexcept
{
return GetShellWindow();
}
constexpr Window(HWND handle = Window::NullWindow) noexcept : m_WindowHandle(handle) { }
std::optional<std::wstring> title() const;
std::optional<std::wstring> classname() const;
std::optional<std::filesystem::path> file() const;
std::optional<bool> on_current_desktop() const;
bool is_user_window() const;
inline bool valid() const noexcept
{
return IsWindow(m_WindowHandle);
}
inline bool maximised() const noexcept
{
return IsZoomed(m_WindowHandle);
}
inline bool minimised() const noexcept
{
return IsIconic(m_WindowHandle);
}
inline bool show(int state = SW_SHOW) noexcept
{
return ShowWindow(m_WindowHandle, state);
}
inline bool visible() const noexcept
{
return IsWindowVisible(m_WindowHandle);
}
inline bool active() const noexcept
{
return ForegroundWindow() == m_WindowHandle;
}
inline bool cloaked() const
{
const auto attr = get_attribute<DWMWA_CLOAKED>();
return attr && *attr;
}
inline HMONITOR monitor() const noexcept
{
return MonitorFromWindow(m_WindowHandle, MONITOR_DEFAULTTONULL);
}
inline Window get(UINT cmd) const noexcept
{
return GetWindow(m_WindowHandle, cmd);
}
inline Window ancestor(UINT flags) const noexcept
{
return GetAncestor(m_WindowHandle, flags);
}
inline HANDLE prop(Util::null_terminated_wstring_view name) const noexcept
{
return GetProp(m_WindowHandle, name.c_str());
}
inline std::optional<LONG_PTR> get_long_ptr(int index) const
{
SetLastError(NO_ERROR);
const LONG_PTR val = GetWindowLongPtr(m_WindowHandle, index);
if (!val)
{
if (const DWORD lastErr = GetLastError(); lastErr != NO_ERROR)
{
HresultHandle(HRESULT_FROM_WIN32(lastErr), spdlog::level::info, L"Failed to get window pointer");
return std::nullopt;
}
}
return val;
}
template<spdlog::level::level_enum level = spdlog::level::info>
inline std::optional<LONG_PTR> set_long_ptr(int index, LONG_PTR value) const
{
SetLastError(NO_ERROR);
const LONG_PTR val = SetWindowLongPtr(m_WindowHandle, index, value);
if (!val)
{
if (const DWORD lastErr = GetLastError(); lastErr != NO_ERROR)
{
HresultHandle(HRESULT_FROM_WIN32(lastErr), level, L"Failed to set window pointer");
// HresultHandle is [[noreturn]] with spdlog::level::critical
if constexpr (level != spdlog::level::critical)
{
return std::nullopt;
}
}
}
return val;
}
inline DWORD thread_id() const noexcept
{
return GetWindowThreadProcessId(m_WindowHandle, nullptr);
}
inline DWORD process_id() const noexcept
{
DWORD pid { };
GetWindowThreadProcessId(m_WindowHandle, &pid);
return pid;
}
inline std::pair<DWORD, DWORD> thread_process_id() const noexcept
{
std::pair<DWORD, DWORD> pair { };
pair.first = GetWindowThreadProcessId(m_WindowHandle, &pair.second);
return pair;
}
inline std::optional<RECT> rect() const
{
RECT result { };
if (GetWindowRect(m_WindowHandle, &result))
{
return result;
}
else
{
LastErrorHandle(spdlog::level::info, L"Failed to get window region.");
return std::nullopt;
}
}
inline std::optional<RECT> client_rect() const
{
RECT result { };
if (GetClientRect(m_WindowHandle, &result))
{
return result;
}
else
{
LastErrorHandle(spdlog::level::info, L"Failed to get client region.");
return std::nullopt;
}
}
inline std::optional<TITLEBARINFO> titlebar_info() const
{
TITLEBARINFO info = { sizeof(info) };
if (GetTitleBarInfo(m_WindowHandle, &info))
{
return info;
}
else
{
LastErrorHandle(spdlog::level::info, L"Failed to get titlebar info.");
return std::nullopt;
}
}
inline LRESULT send_message(unsigned int message, WPARAM wparam = 0, LPARAM lparam = 0) const noexcept
{
return SendMessage(m_WindowHandle, message, wparam, lparam);
}
inline bool post_message(unsigned int message, WPARAM wparam = 0, LPARAM lparam = 0) const noexcept
{
return PostMessage(m_WindowHandle, message, wparam, lparam);
}
inline Window find_child(Util::null_terminated_wstring_view className = { }, Util::null_terminated_wstring_view windowName = { }, Window childAfter = Window::NullWindow) const noexcept
{
return Find(className, windowName, m_WindowHandle, childAfter);
}
constexpr FindEnum find_childs(Util::null_terminated_wstring_view className = { }, Util::null_terminated_wstring_view windowName = { }) const noexcept;
inline Window get_top_children() const noexcept
{
return GetTopWindow(m_WindowHandle);
}
inline Window get_sibling(int direction) const noexcept
{
return GetNextWindow(m_WindowHandle, direction);
}
constexpr OrderedEnum get_ordered_childrens() const noexcept;
constexpr HWND handle() const noexcept
{
return m_WindowHandle;
}
constexpr HWND *put() noexcept
{
return &m_WindowHandle;
}
constexpr operator HWND() const noexcept
{
return m_WindowHandle;
}
inline explicit operator bool() const noexcept
{
return valid();
}
constexpr bool operator ==(Window right) const noexcept
{
return m_WindowHandle == right.m_WindowHandle;
}
constexpr bool operator ==(HWND right) const noexcept
{
return m_WindowHandle == right;
}
friend struct std::hash<Window>;
};
// Specialize std::hash to allow the use of Window as unordered_map and unordered_set key.
template<>
struct std::hash<Window> {
inline std::size_t operator()(Window k) const noexcept
{
static constexpr std::hash<HWND> hasher;
return hasher(k.m_WindowHandle);
}
};
// Iterator class for FindEnum
class FindWindowIterator {
private:
Util::null_terminated_wstring_view m_class, m_name;
Window m_parent, m_currentWindow;
constexpr FindWindowIterator() noexcept { }
inline FindWindowIterator(Util::null_terminated_wstring_view className, Util::null_terminated_wstring_view windowName, Window parent) noexcept :
m_class(className),
m_name(windowName),
m_parent(parent)
{
++(*this);
}
friend class Window::FindEnum;
public:
inline FindWindowIterator &operator ++() noexcept
{
m_currentWindow = m_parent.find_child(m_class, m_name, m_currentWindow);
return *this;
}
constexpr bool operator ==(const FindWindowIterator &right) const noexcept
{
return m_currentWindow == right.m_currentWindow;
}
constexpr Window operator *() const noexcept
{
return m_currentWindow;
}
};
// Iterator class for OrderedEnum
class SiblingWindowIterator {
private:
Window m_currentWindow;
int m_direction;
constexpr SiblingWindowIterator() noexcept : m_direction(0) { }
constexpr SiblingWindowIterator(Window start, int direction) noexcept :
m_currentWindow(start),
m_direction(direction)
{ }
friend class Window::OrderedEnum;
public:
inline SiblingWindowIterator &operator ++() noexcept
{
m_currentWindow = m_currentWindow.get_sibling(m_direction);
return *this;
}
constexpr bool operator ==(const SiblingWindowIterator &right) const noexcept
{
return m_currentWindow == right.m_currentWindow;
}
constexpr Window operator *() const noexcept
{
return m_currentWindow;
}
};
class Window::FindEnum {
private:
Util::null_terminated_wstring_view m_class, m_name;
Window m_parent;
public:
constexpr FindEnum(Util::null_terminated_wstring_view className = { }, Util::null_terminated_wstring_view windowName = { }, Window parent = Window::NullWindow) noexcept :
m_class(className),
m_name(windowName),
m_parent(parent)
{ }
inline FindWindowIterator begin() const noexcept
{
return { m_class, m_name, m_parent };
}
constexpr FindWindowIterator end() const noexcept
{
return { };
}
};
class Window::OrderedEnum {
private:
Window m_parent;
public:
constexpr OrderedEnum(Window parent = Window::NullWindow) noexcept :
m_parent(parent)
{ }
inline SiblingWindowIterator begin() const noexcept
{
return { m_parent.get_top_children(), GW_HWNDNEXT };
}
constexpr SiblingWindowIterator end() const noexcept
{
return { };
}
};
constexpr Window::FindEnum Window::find_childs(Util::null_terminated_wstring_view className, Util::null_terminated_wstring_view windowName) const noexcept
{
return FindEnum(className, windowName, m_WindowHandle);
}
constexpr Window::OrderedEnum Window::get_ordered_childrens() const noexcept
{
return OrderedEnum(m_WindowHandle);
}
| 11,311
|
C++
|
.h
| 390
| 26.44359
| 216
| 0.752122
|
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,959
|
messagewindow.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/windows/messagewindow.hpp
|
#pragma once
#include "arch.h"
#include <member_thunk/page.hpp>
#include <memory>
#include <windef.h>
#include "../resources/ids.h"
#include "util/maybe_delete.hpp"
#include "util/null_terminated_string_view.hpp"
#include "window.hpp"
#include "windowclass.hpp"
class MessageWindow : public Window {
private:
std::unique_ptr<WindowClass, Util::maybe_delete> m_WindowClass;
const wchar_t *m_IconResource;
member_thunk::page m_ProcPage;
void init(Util::null_terminated_wstring_view windowName, DWORD style, DWORD extended_style, Window parent);
inline static const wchar_t *const DEFAULT_ICON = MAKEINTRESOURCE(IDI_MAINICON);
protected:
inline HINSTANCE hinstance() const noexcept
{
return m_WindowClass->hinstance();
}
inline virtual LRESULT MessageHandler(UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_DPICHANGED:
m_WindowClass->ChangeIcon(m_WindowHandle, m_IconResource);
break;
}
return DefWindowProc(m_WindowHandle, uMsg, wParam, lParam);
}
MessageWindow(WindowClass &classRef, Util::null_terminated_wstring_view windowName, DWORD style = 0, DWORD extended_style = 0, Window parent = Window::NullWindow, const wchar_t *iconResource = DEFAULT_ICON);
MessageWindow(Util::null_terminated_wstring_view className, Util::null_terminated_wstring_view windowName, HINSTANCE hInstance, DWORD style = 0, DWORD extended_style = 0, Window parent = Window::NullWindow, const wchar_t *iconResource = DEFAULT_ICON);
~MessageWindow();
inline MessageWindow(const MessageWindow &) = delete;
inline MessageWindow &operator =(const MessageWindow &) = delete;
public:
inline static WindowClass MakeWindowClass(Util::null_terminated_wstring_view className, HINSTANCE hInstance, const wchar_t *iconResource = DEFAULT_ICON)
{
return { DefWindowProc, className, iconResource, hInstance };
}
};
| 1,843
|
C++
|
.h
| 43
| 40.697674
| 252
| 0.78256
|
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,960
|
windowclass.hpp
|
TranslucentTB_TranslucentTB/TranslucentTB/windows/windowclass.hpp
|
#pragma once
#include "arch.h"
#include <functional>
#include <string>
#include <windef.h>
#include <WinUser.h>
#include <wil/resource.h>
#include "util/null_terminated_string_view.hpp"
class Window;
class WindowClass {
private:
ATOM m_Atom;
HINSTANCE m_hInstance;
wil::unique_hicon m_hIconSmall, m_hIcon;
wil::srwlock m_Lock;
void LoadIcons(const wchar_t *iconResource);
void Unregister();
public:
WindowClass(WNDPROC procedure, Util::null_terminated_wstring_view className, const wchar_t *iconResource, HINSTANCE hInstance, unsigned int style = 0, HBRUSH brush = nullptr, HCURSOR cursor = LoadCursor(nullptr, IDC_ARROW));
inline LPCWSTR atom() const noexcept { return reinterpret_cast<LPCWSTR>(static_cast<INT_PTR>(m_Atom)); }
inline HINSTANCE hinstance() const noexcept { return m_hInstance; }
void ChangeIcon(Window window, const wchar_t *iconResource);
inline WindowClass(const WindowClass &) = delete;
inline WindowClass &operator =(const WindowClass &) = delete;
// NOTE: these operators can only be used BEFORE making a window.
// once a window is made, and as long as it's alive, the WindowClass
// can't move.
inline WindowClass(WindowClass &&other) noexcept :
m_Atom(std::exchange(other.m_Atom, static_cast<ATOM>(0))),
m_hInstance(std::exchange(other.m_hInstance, nullptr)),
m_hIconSmall(std::move(other.m_hIconSmall)),
m_hIcon(std::move(other.m_hIcon))
{ }
inline WindowClass& operator =(WindowClass&& other) noexcept
{
if (this != &other)
{
std::swap(m_Atom, other.m_Atom);
std::swap(m_hInstance, other.m_hInstance);
std::swap(m_hIconSmall, other.m_hIconSmall);
std::swap(m_hIcon, other.m_hIcon);
}
return *this;
}
inline ~WindowClass()
{
if (m_Atom != 0)
{
Unregister();
}
}
};
| 1,764
|
C++
|
.h
| 52
| 31.538462
| 225
| 0.738824
|
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,961
|
dependencyproperty.h
|
TranslucentTB_TranslucentTB/Xaml/dependencyproperty.h
|
#pragma once
#ifndef __midl
# include "winrt.hpp"
# include <winrt/Windows.UI.Xaml.h>
# include "util/string_macros.hpp"
# define DEPENDENCY_PROPERTY_FIELD(NAME) s_ ## NAME ## Property_
# define DECL_DEPENDENCY_PROPERTY_FUNCS(TYPE, NAME, FIELD) \
static wux::DependencyProperty NAME ## Property() noexcept \
{ \
return FIELD; \
} \
\
TYPE NAME() \
{ \
return winrt::unbox_value<TYPE>(GetValue(FIELD)); \
} \
\
void NAME(const TYPE &value_) \
{ \
SetValue(FIELD, winrt::box_value(value_)); \
}
# define DECL_DEPENDENCY_PROPERTY_FIELD(TYPE, NAME, METADATA) \
inline static wux::DependencyProperty DEPENDENCY_PROPERTY_FIELD(NAME) = \
wux::DependencyProperty::Register( \
UTIL_STRINGIFY(NAME), \
winrt::xaml_typename<TYPE>(), \
winrt::xaml_typename<class_type>(), \
METADATA);
# define DECL_DEPENDENCY_PROPERTY(TYPE, NAME) \
private: \
DECL_DEPENDENCY_PROPERTY_FIELD(TYPE, NAME, nullptr) \
\
public: \
DECL_DEPENDENCY_PROPERTY_FUNCS(TYPE, NAME, DEPENDENCY_PROPERTY_FIELD(NAME))
# define DECL_DEPENDENCY_PROPERTY_WITH_DEFAULT(TYPE, NAME, DEFAULT) \
private: \
DECL_DEPENDENCY_PROPERTY_FIELD(TYPE, NAME, wux::PropertyMetadata(DEFAULT)) \
\
public: \
DECL_DEPENDENCY_PROPERTY_FUNCS(TYPE, NAME, DEPENDENCY_PROPERTY_FIELD(NAME))
# define DECL_DEPENDENCY_PROPERTY_WITH_METADATA(TYPE, NAME, METADATA) \
private: \
DECL_DEPENDENCY_PROPERTY_FIELD(TYPE, NAME, METADATA) \
\
public: \
DECL_DEPENDENCY_PROPERTY_FUNCS(TYPE, NAME, DEPENDENCY_PROPERTY_FIELD(NAME))
#else
# define DECL_DEPENDENCY_PROPERTY(TYPE, NAME) \
TYPE NAME; \
\
[noexcept] \
static Windows.UI.Xaml.DependencyProperty NAME ## Property { get; }
#endif
| 1,648
|
C++
|
.h
| 53
| 29.245283
| 77
| 0.737304
|
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,962
|
pch.h
|
TranslucentTB_TranslucentTB/Xaml/pch.h
|
#pragma once
#include "winrt.hpp"
// Remove intrusive macro from Windows headers
#include "undefgetcurrenttime.h"
#include <winrt/Microsoft.UI.Xaml.Controls.h>
#include <winrt/Microsoft.UI.Xaml.Controls.Primitives.h>
#include <winrt/Microsoft.UI.Xaml.XamlTypeInfo.h>
#include <winrt/Windows.ApplicationModel.Resources.h>
#include <winrt/Windows.Foundation.h>
#include <winrt/Windows.Foundation.Collections.h>
#include <winrt/Windows.Foundation.Metadata.h>
#include <winrt/Windows.Globalization.NumberFormatting.h>
#include <winrt/Windows.System.h>
#include <winrt/Windows.System.Threading.h>
#include <winrt/Windows.UI.h>
#include <winrt/Windows.UI.Core.h>
#include <winrt/Windows.UI.Popups.h>
#include <winrt/Windows.UI.Xaml.h>
#include <winrt/Windows.UI.Xaml.Controls.h>
#include <winrt/Windows.UI.Xaml.Controls.Primitives.h>
#include <winrt/Windows.UI.Xaml.Data.h>
#include <winrt/Windows.UI.Xaml.Documents.h>
#include <winrt/Windows.UI.Xaml.Input.h>
#include <winrt/Windows.UI.Xaml.Interop.h>
#include <winrt/Windows.UI.Xaml.Markup.h>
#include <winrt/Windows.UI.Xaml.Media.h>
#include <winrt/Windows.UI.Xaml.Media.Animation.h>
#include <winrt/Windows.UI.Xaml.Media.Imaging.h>
#include <winrt/Windows.UI.Xaml.Navigation.h>
#include <winrt/Windows.UI.Xaml.Shapes.h>
#include <winrt/TranslucentTB.Xaml.h>
#include <winrt/TranslucentTB.Xaml.Controls.h>
#include <winrt/TranslucentTB.Xaml.Models.h>
#include <winrt/TranslucentTB.Xaml.Pages.h>
#include "redefgetcurrenttime.h"
#include <wil/cppwinrt_helpers.h>
| 1,513
|
C++
|
.h
| 36
| 40.916667
| 57
| 0.80516
|
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,963
|
FunctionalConverters.h
|
TranslucentTB_TranslucentTB/Xaml/FunctionalConverters.h
|
#pragma once
#include "factory.h"
#include "winrt.hpp"
#include "winrt/TranslucentTB.Xaml.Models.Primitives.h"
#include "FunctionalConverters.g.h"
namespace winrt::TranslucentTB::Xaml::implementation
{
struct FunctionalConverters
{
static bool InvertedBool(bool value) noexcept;
static wux::Visibility InvertedBoolToVisibility(bool value) noexcept;
static bool IsSameLogSinkState(txmp::LogSinkState a, txmp::LogSinkState b) noexcept;
static bool IsDifferentLogSinkState(txmp::LogSinkState a, txmp::LogSinkState b) noexcept;
};
}
FACTORY(winrt::TranslucentTB::Xaml, FunctionalConverters);
| 602
|
C++
|
.h
| 16
| 35.75
| 91
| 0.821612
|
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,964
|
StyleResources.h
|
TranslucentTB_TranslucentTB/Xaml/StyleResources.h
|
#pragma once
#include "factory.h"
#include "winrt.hpp"
#include "StyleResources.g.h"
namespace winrt::TranslucentTB::Xaml::implementation
{
// ResourceDictionary with marker interface to be able to find out the MergedDictionary we inserted
MIDL_INTERFACE("A240AC45-8961-4B2F-9259-7F9C8740BFFC") IStyleResourceDictionary : IUnknown
{
};
struct StyleResourceDictionary : wux::ResourceDictionaryT<StyleResourceDictionary, IStyleResourceDictionary>
{
};
struct StyleResources
{
static wux::DependencyProperty ResourcesProperty() noexcept
{
return m_ResourcesProperty;
}
static wux::ResourceDictionary GetResources(const wux::DependencyObject &obj)
{
if (obj)
{
return obj.GetValue(m_ResourcesProperty).as<wux::ResourceDictionary>();
}
else
{
return nullptr;
}
}
static void SetResources(const wux::DependencyObject &obj, const wux::ResourceDictionary &value)
{
if (obj)
{
obj.SetValue(m_ResourcesProperty, value);
}
}
private:
static void OnResourcesChanged(const wux::DependencyObject &d, const wux::DependencyPropertyChangedEventArgs &e);
static wux::ResourceDictionary CloneResourceDictionary(const wux::ResourceDictionary &resource, const wux::ResourceDictionary &destination);
static wux::DependencyProperty m_ResourcesProperty;
};
}
FACTORY(winrt::TranslucentTB::Xaml, StyleResources);
| 1,374
|
C++
|
.h
| 44
| 28.272727
| 142
| 0.786525
|
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,965
|
App.h
|
TranslucentTB_TranslucentTB/Xaml/App.h
|
#pragma once
#include "factory.h"
#include "App.g.h"
#include "App.base.hpp"
namespace winrt::TranslucentTB::Xaml::implementation
{
struct App : AppT2<App>
{
App();
};
}
FACTORY(winrt::TranslucentTB::Xaml, App);
| 220
|
C++
|
.h
| 12
| 16.666667
| 52
| 0.736585
|
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,966
|
factory.h
|
TranslucentTB_TranslucentTB/Xaml/factory.h
|
#pragma once
#define FACTORY(NAMESPACE, CLASS) \
namespace NAMESPACE::factory_implementation \
{ \
struct CLASS : CLASS ## T<CLASS, implementation::CLASS> \
{ \
}; \
}
| 171
|
C++
|
.h
| 8
| 20
| 58
| 0.717791
|
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,967
|
property.h
|
TranslucentTB_TranslucentTB/Xaml/property.h
|
#pragma once
#include <utility>
#include <type_traits>
#define PROPERTY_FIELD(NAME) m_ ## NAME ## Property_
#define DECL_PROPERTY_FUNCS(TYPE, NAME, FIELD) \
TYPE NAME() const noexcept(std::is_nothrow_copy_constructible_v<TYPE>) \
{ \
return FIELD; \
}\
\
void NAME(TYPE value) noexcept(std::is_nothrow_move_assignable_v<TYPE>) \
{ \
FIELD = std::move(value); \
}
#define DECL_PROPERTY_PROP(TYPE, NAME) \
private: \
TYPE PROPERTY_FIELD(NAME); \
\
public: \
DECL_PROPERTY_FUNCS(TYPE, NAME, PROPERTY_FIELD(NAME))
| 526
|
C++
|
.h
| 20
| 24.5
| 74
| 0.710317
|
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,968
|
PropertyChangedBase.hpp
|
TranslucentTB_TranslucentTB/Xaml/PropertyChangedBase.hpp
|
#pragma once
#include <type_traits>
#include "winrt.hpp"
#include <winrt/Windows.UI.Xaml.Data.h>
#include "event.h"
#include "util/string_macros.hpp"
#define PROPERTY_CHANGED_FIELD(NAME) m_ ## NAME ## Property_
#define DECL_PROPERTY_CHANGED_FUNCS(TYPE, NAME, FIELD) \
TYPE NAME() const noexcept(std::is_nothrow_copy_constructible_v<TYPE>) \
{ \
return FIELD; \
}\
\
void NAME(const TYPE &value) \
{ \
compare_assign(FIELD, value, UTIL_STRINGIFY(NAME)); \
}
#define DECL_PROPERTY_CHANGED_PROP(TYPE, NAME) \
private: \
TYPE PROPERTY_CHANGED_FIELD(NAME); \
\
public: \
DECL_PROPERTY_CHANGED_FUNCS(TYPE, NAME, PROPERTY_CHANGED_FIELD(NAME))
class PropertyChangedBase {
public:
DECL_EVENT(wux::Data::PropertyChangedEventHandler, PropertyChanged, m_propertyChanged);
protected:
template<typename Self, typename U>
void compare_assign(this Self &&self, U &value, const U &new_value, std::wstring_view name)
{
if (value != new_value)
{
value = new_value;
self.m_propertyChanged(self, wux::Data::PropertyChangedEventArgs(name));
}
}
};
| 1,062
|
C++
|
.h
| 37
| 26.72973
| 92
| 0.740196
|
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,969
|
BindableObjectReference.h
|
TranslucentTB_TranslucentTB/Xaml/BindableObjectReference.h
|
#pragma once
#include "dependencyproperty.h"
#include "factory.h"
#include "winrt.hpp"
#include "BindableObjectReference.g.h"
namespace winrt::TranslucentTB::Xaml::implementation
{
struct BindableObjectReference : BindableObjectReferenceT<BindableObjectReference>
{
BindableObjectReference() = default;
DECL_DEPENDENCY_PROPERTY(IInspectable, Object);
};
}
FACTORY(winrt::TranslucentTB::Xaml, BindableObjectReference);
| 444
|
C++
|
.h
| 14
| 28.857143
| 86
| 0.800469
|
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,970
|
event.h
|
TranslucentTB_TranslucentTB/Xaml/event.h
|
#pragma once
#include "winrt.hpp"
#define DECL_EVENT(TYPE, NAME, FIELD) \
private: \
winrt::event<TYPE> FIELD; \
\
public: \
winrt::event_token NAME(const TYPE &handler_) \
{ \
return FIELD.add(handler_); \
}\
\
void NAME(const winrt::event_token &token_) \
{ \
FIELD.remove(token_); \
}
| 301
|
C++
|
.h
| 16
| 17
| 48
| 0.669014
|
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,971
|
App.base.hpp
|
TranslucentTB_TranslucentTB/Xaml/App.base.hpp
|
#pragma once
#include "winrt.hpp"
#include <winrt/Windows.UI.Xaml.Interop.h>
#include <winrt/Windows.UI.Xaml.Markup.h>
namespace winrt::TranslucentTB::Xaml::implementation {
template<typename D, typename... I>
struct App_baseWithProvider : public App_base<D, wux::Markup::IXamlMetadataProvider> {
using IXamlType = wux::Markup::IXamlType;
IXamlType GetXamlType(const wux::Interop::TypeName &type)
{
return AppProvider()->GetXamlType(type);
}
IXamlType GetXamlType(const hstring &fullName)
{
return AppProvider()->GetXamlType(fullName);
}
com_array<wux::Markup::XmlnsDefinition> GetXmlnsDefinitions()
{
return AppProvider()->GetXmlnsDefinitions();
}
private:
bool _contentLoaded { false };
com_ptr<XamlMetaDataProvider> _appProvider;
com_ptr<XamlMetaDataProvider> AppProvider()
{
if (!_appProvider)
{
_appProvider = make_self<XamlMetaDataProvider>();
}
return _appProvider;
}
};
template<typename D, typename... I>
using AppT2 = App_baseWithProvider<D, I...>;
}
| 1,028
|
C++
|
.h
| 35
| 26.457143
| 87
| 0.742655
|
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,972
|
RelativeAncestor.h
|
TranslucentTB_TranslucentTB/Xaml/RelativeAncestor.h
|
#pragma once
#include "factory.h"
#include "winrt.hpp"
#include <utility>
#include <vector>
#include "RelativeAncestor.g.h"
namespace winrt::TranslucentTB::Xaml::implementation
{
struct RelativeAncestor
{
static wux::DependencyProperty AncestorProperty() noexcept
{
return m_AncestorProperty;
}
static wf::IInspectable GetAncestor(const wux::FrameworkElement &obj)
{
if (obj)
{
return obj.GetValue(m_AncestorProperty);
}
else
{
return nullptr;
}
}
static void SetAncestor(const wux::FrameworkElement &obj, const wf::IInspectable &value)
{
if (obj)
{
obj.SetValue(m_AncestorProperty, value);
}
}
static wux::DependencyProperty AncestorTypeProperty() noexcept
{
return m_AncestorTypeProperty;
}
static wux::Interop::TypeName GetAncestorType(const wux::FrameworkElement &obj)
{
return obj.GetValue(m_AncestorTypeProperty).as<wux::Interop::TypeName>();
}
static void SetAncestorType(const wux::FrameworkElement &obj, const wux::Interop::TypeName &value)
{
if (obj)
{
obj.SetValue(m_AncestorTypeProperty, box_value(value));
}
}
private:
static void OnAncestorTypeChanged(const wux::DependencyObject &d, const wux::DependencyPropertyChangedEventArgs &e);
static void OnFrameworkElementLoaded(const wf::IInspectable &sender, const wux::RoutedEventArgs &args);
static void OnFrameworkElementUnloaded(const wf::IInspectable &sender, const wux::RoutedEventArgs &args);
static wux::DependencyObject FindAscendant(const wux::DependencyObject &element, const wux::Interop::TypeName &type);
static void RemoveHandlers(const wux::FrameworkElement &element) noexcept;
static wux::DependencyProperty m_AncestorProperty;
static wux::DependencyProperty m_AncestorTypeProperty;
static thread_local std::vector<std::pair<weak_ref<wux::FrameworkElement>, event_token>> s_UnloadedTokenList;
static thread_local std::vector<std::pair<weak_ref<wux::FrameworkElement>, event_token>> s_LoadedTokenList;
};
}
FACTORY(winrt::TranslucentTB::Xaml, RelativeAncestor);
| 2,067
|
C++
|
.h
| 60
| 31.266667
| 119
| 0.772431
|
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,973
|
FluentColorPalette.h
|
TranslucentTB_TranslucentTB/Xaml/Models/FluentColorPalette.h
|
#pragma once
#include "../factory.h"
#include "winrt.hpp"
#include <array>
#include "Models/FluentColorPalette.g.h"
namespace winrt::TranslucentTB::Xaml::Models::implementation
{
struct FluentColorPalette : FluentColorPaletteT<FluentColorPalette>
{
private:
/* Values were taken from the Settings App, Personalization > Colors which match with
* https://docs.microsoft.com/en-us/windows/uwp/whats-new/windows-docs-december-2017
*
* The default ordering and grouping of colors was undesirable so was modified.
* Colors were transposed: the colors in rows within the Settings app became columns here.
* This is because columns in an IColorPalette generally should contain different shades of
* the same color. In the settings app this concept is somewhat loosely reversed.
* The first 'column' ordering, after being transposed, was then reversed so 'red' colors
* were near to each other.
*
* This new ordering most closely follows the Windows standard while:
*
* 1. Keeping colors in a 'spectrum' order
* 2. Keeping like colors next to each both in rows and columns
* (which is unique for the windows palette).
* For example, similar red colors are next to each other in both
* rows within the same column and rows within the column next to it.
* This follows a 'snake-like' pattern as illustrated below.
* 3. A downside of this ordering is colors don't follow strict 'shades'
* as in other palettes.
*
* The colors will be displayed in the below pattern.
* This pattern follows a spectrum while keeping like-colors near to one
* another across both rows and columns.
*
* ┌Red───┐ ┌Blue──┐ ┌Gray──┐
* │ │ │ │ │ |
* │ │ │ │ │ |
* Yellow └Violet┘ └Green─┘ Brown
*/
static constexpr std::array<std::array<Windows::UI::Color, 8>, 6> COLOR_CHART = {{
{{
// Ordering reversed for this section only
{ 255, 255, 67, 67 }, // #FF4343
{ 255, 209, 52, 56 }, // #D13438
{ 255, 239, 105, 80 }, // #EF6950
{ 255, 218, 59, 1 }, // #DA3B01
{ 255, 202, 80, 16 }, // #CA5010
{ 255, 247, 99, 12 }, // #F7630C
{ 255, 255, 140, 0 }, // #FF8C00
{ 255, 255, 185, 0 } // #FFB900
}},
{{
{ 255, 231, 72, 86 }, // #E74856
{ 255, 232, 17, 35 }, // #E81123
{ 255, 234, 0, 94 }, // #EA005E
{ 255, 195, 0, 82 }, // #C30052
{ 255, 227, 0, 140 }, // #E3008C
{ 255, 191, 0, 119 }, // #BF0077
{ 255, 194, 57, 179 }, // #C239B3
{ 255, 154, 0, 137 }, // #9A0089
}},
{{
{ 255, 0, 120, 215 }, // #0078D7
{ 255, 0, 99, 177 }, // #0063B1
{ 255, 142, 140, 216 }, // #8E8CD8
{ 255, 107, 105, 214 }, // #6B69D6
{ 255, 135, 100, 184 }, // #8764B8
{ 255, 116, 77, 169 }, // #744DA9
{ 255, 177, 70, 194 }, // #B146C2
{ 255, 136, 23, 152 }, // #881798
}},
{{
{ 255, 0, 153, 188 }, // #0099BC
{ 255, 45, 125, 154 }, // #2D7D9A
{ 255, 0, 183, 195 }, // #00B7C3
{ 255, 3, 131, 135 }, // #038387
{ 255, 0, 178, 148 }, // #00B294
{ 255, 1, 133, 116 }, // #018574
{ 255, 0, 204, 106 }, // #00CC6A
{ 255, 16, 137, 62 }, // #10893E
}},
{{
{ 255, 122, 117, 116 }, // #7A7574
{ 255, 93, 90, 80 }, // #5D5A58
{ 255, 104, 118, 138 }, // #68768A
{ 255, 81, 92, 107 }, // #515C6B
{ 255, 86, 124, 115 }, // #567C73
{ 255, 72, 104, 96 }, // #486860
{ 255, 73, 130, 5 }, // #498205
{ 255, 16, 124, 16 }, // #107C10
}},
{{
{ 255, 118, 118, 118 }, // #767676
{ 255, 76, 74, 72 }, // #4C4A48
{ 255, 105, 121, 126 }, // #69797E
{ 255, 74, 84, 89 }, // #4A5459
{ 255, 100, 124, 100 }, // #647C64
{ 255, 82, 94, 84 }, // #525E54
{ 255, 132, 117, 69 }, // #847545
{ 255, 126, 115, 95 }, // #7E735F
}}
}};
public:
FluentColorPalette() = default;
uint32_t ColorCount() noexcept;
uint32_t ShadeCount() noexcept;
Windows::UI::Color GetColor(uint32_t colorIndex, uint32_t shadeIndex);
};
}
FACTORY(winrt::TranslucentTB::Xaml::Models, FluentColorPalette);
| 4,255
|
C++
|
.h
| 111
| 33.72973
| 93
| 0.567369
|
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,974
|
Action.h
|
TranslucentTB_TranslucentTB/Xaml/Models/Action.h
|
#pragma once
#include "../event.h"
#include "../factory.h"
#include "../PropertyChangedBase.hpp"
#include "winrt.hpp"
#include "Models/Action.g.h"
namespace winrt::TranslucentTB::Xaml::Models::implementation
{
struct Action : ActionT<Action>, PropertyChangedBase
{
Action() = default;
DECL_PROPERTY_CHANGED_PROP(hstring, Name);
DECL_PROPERTY_CHANGED_PROP(hstring, Description);
DECL_PROPERTY_CHANGED_FUNCS(wuxc::IconElement, Icon, m_icon);
DECL_EVENT(wux::RoutedEventHandler, Click, m_click);
void ForwardClick(const IInspectable &sender, const wux::RoutedEventArgs &args);
private:
wuxc::IconElement m_icon = nullptr;
};
}
FACTORY(winrt::TranslucentTB::Xaml::Models, Action);
| 702
|
C++
|
.h
| 21
| 31.238095
| 82
| 0.765579
|
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,975
|
TaskbarAppearance.h
|
TranslucentTB_TranslucentTB/Xaml/Models/Primitives/TaskbarAppearance.h
|
#pragma once
#include "../../factory.h"
#include "../../property.h"
#include "Models/Primitives/TaskbarAppearance.g.h"
namespace winrt::TranslucentTB::Xaml::Models::Primitives::implementation
{
struct TaskbarAppearance : TaskbarAppearanceT<TaskbarAppearance>
{
TaskbarAppearance() noexcept = default;
TaskbarAppearance(AccentState accent, Windows::UI::Color color, bool showPeek, bool showLine) noexcept :
m_Accent(accent),
m_Color(color),
m_ShowPeek(showPeek),
m_ShowLine(showLine)
{ }
DECL_PROPERTY_FUNCS(AccentState, Accent, m_Accent);
DECL_PROPERTY_FUNCS(Windows::UI::Color, Color, m_Color);
DECL_PROPERTY_FUNCS(bool, ShowPeek, m_ShowPeek);
DECL_PROPERTY_FUNCS(bool, ShowLine, m_ShowLine);
private:
AccentState m_Accent = AccentState::Normal;
Windows::UI::Color m_Color = { 0, 0, 0, 0 };
bool m_ShowPeek = true;
bool m_ShowLine = true;
};
}
FACTORY(winrt::TranslucentTB::Xaml::Models::Primitives, TaskbarAppearance);
| 964
|
C++
|
.h
| 27
| 33.111111
| 106
| 0.748927
|
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,976
|
OptionalTaskbarAppearance.h
|
TranslucentTB_TranslucentTB/Xaml/Models/Primitives/OptionalTaskbarAppearance.h
|
#pragma once
#include "../../factory.h"
#include "../../property.h"
#include "TaskbarAppearance.h"
#include "Models/Primitives/OptionalTaskbarAppearance.g.h"
namespace winrt::TranslucentTB::Xaml::Models::Primitives::implementation
{
struct OptionalTaskbarAppearance : OptionalTaskbarAppearanceT<OptionalTaskbarAppearance, TaskbarAppearance>
{
OptionalTaskbarAppearance() noexcept = default;
OptionalTaskbarAppearance(bool enabled, AccentState accent, Windows::UI::Color color, bool showPeek, bool showLine) noexcept :
base_type(accent, color, showPeek, showLine),
m_Enabled(enabled)
{ }
DECL_PROPERTY_FUNCS(bool, Enabled, m_Enabled);
private:
bool m_Enabled = false;
};
}
FACTORY(winrt::TranslucentTB::Xaml::Models::Primitives, OptionalTaskbarAppearance);
| 781
|
C++
|
.h
| 20
| 36.8
| 128
| 0.793651
|
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,977
|
WelcomePage.h
|
TranslucentTB_TranslucentTB/Xaml/Pages/WelcomePage.h
|
#pragma once
#include "../event.h"
#include "../factory.h"
#include "winrt.hpp"
#include "FramelessPage.h"
#include "Pages/WelcomePage.g.h"
namespace winrt::TranslucentTB::Xaml::Pages::implementation
{
struct WelcomePage : wux::Markup::ComponentConnectorT<WelcomePageT<WelcomePage>>
{
wf::Rect ExpandedDragRegion() override;
void OpenLiberapayLink(const IInspectable &sender, const wux::RoutedEventArgs &args);
void OpenDiscordLink(const IInspectable &sender, const wux::RoutedEventArgs &args);
void EditConfigFile(const IInspectable &sender, const wux::RoutedEventArgs &args);
void AgreeButtonClicked(const IInspectable &sender, const wux::RoutedEventArgs &args);
void DisagreeButtonClicked(const IInspectable &sender, const wux::RoutedEventArgs &args);
DECL_EVENT(LiberapayOpenDelegate, LiberapayOpenRequested, m_LiberapayOpenRequestedHandler);
DECL_EVENT(DiscordJoinDelegate, DiscordJoinRequested, m_DiscordJoinRequestedHandler);
DECL_EVENT(ConfigEditDelegate, ConfigEditRequested, m_ConfigEditRequestedHandler);
DECL_EVENT(LicenseApprovedDelegate, LicenseApproved, m_LicenseApprovedHandler);
};
}
FACTORY(winrt::TranslucentTB::Xaml::Pages, WelcomePage);
| 1,187
|
C++
|
.h
| 23
| 49.347826
| 93
| 0.82038
|
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,978
|
TrayFlyoutPage.h
|
TranslucentTB_TranslucentTB/Xaml/Pages/TrayFlyoutPage.h
|
#pragma once
#include "../event.h"
#include "../factory.h"
#include "../PropertyChangedBase.hpp"
#include "winrt.hpp"
#include "Models/Primitives/TaskbarAppearance.h"
#include "Pages/TrayFlyoutPage.g.h"
namespace winrt::TranslucentTB::Xaml::Pages::implementation
{
struct TrayFlyoutPage : TrayFlyoutPageT<TrayFlyoutPage>, PropertyChangedBase
{
TrayFlyoutPage(bool hasPackageIdentity);
bool IsBlurSupported() noexcept
{
return m_BlurSupported;
}
bool HasPackageIdentity() noexcept
{
return m_HasPackageIdentity;
}
bool SystemHasBattery() noexcept
{
return m_SystemHasBattery;
}
DECL_EVENT(TaskbarSettingsChangedDelegate, TaskbarSettingsChanged, m_TaskbarSettingsChangedDelegate);
DECL_EVENT(ColorRequestedDelegate, ColorRequested, m_ColorRequestedDelegate);
DECL_EVENT(OpenLogFileRequestedDelegate, OpenLogFileRequested, m_OpenLogFileRequestedDelegate);
DECL_EVENT(LogLevelChangedDelegate, LogLevelChanged, m_LogLevelChangedDelegate);
DECL_EVENT(DumpDynamicStateRequestedDelegate, DumpDynamicStateRequested, m_DumpDynamicStateRequestedDelegate);
DECL_EVENT(EditSettingsRequestedDelegate, EditSettingsRequested, m_EditSettingsRequestedDelegate);
DECL_EVENT(ResetSettingsRequestedDelegate, ResetSettingsRequested, m_ResetSettingsRequestedDelegate);
DECL_EVENT(DisableSavingSettingsChangedDelegate, DisableSavingSettingsChanged, m_DisableSavingSettingsChangedDelegate);
DECL_EVENT(HideTrayRequestedDelegate, HideTrayRequested, m_HideTrayRequestedDelegate);
DECL_EVENT(ResetDynamicStateRequestedDelegate, ResetDynamicStateRequested, m_ResetDynamicStateRequestedDelegate);
DECL_EVENT(CompactThunkHeapRequestedDelegate, CompactThunkHeapRequested, m_CompactThunkHeapRequestedDelegate);
DECL_EVENT(StartupStateChangedDelegate, StartupStateChanged, m_StartupStateChangedDelegate);
DECL_EVENT(TipsAndTricksRequestedDelegate, TipsAndTricksRequested, m_TipsAndTricksRequestedDelegate);
DECL_EVENT(AboutRequestedDelegate, AboutRequested, m_AboutRequestedDelegate);
DECL_EVENT(ExitRequestedDelegate, ExitRequested, m_ExitRequestedDelegate);
void SetTaskbarSettings(const txmp::TaskbarState &state, const txmp::TaskbarAppearance &appearance);
void SetLogLevel(const txmp::LogLevel &level);
void SetDisableSavingSettings(const bool &disabled);
void SetStartupState(const wf::IReference<Windows::ApplicationModel::StartupTaskState> &state);
DECL_PROPERTY_CHANGED_FUNCS(txmp::LogSinkState, SinkState, m_SinkState);
void AppearanceClicked(const IInspectable &sender, const wux::RoutedEventArgs &args);
void ColorClicked(const IInspectable &sender, const wux::RoutedEventArgs &args);
void OpenLogFileClicked(const IInspectable &sender, const wux::RoutedEventArgs &args);
void LogLevelClicked(const IInspectable &sender, const wux::RoutedEventArgs &args);
void DumpDynamicStateClicked(const IInspectable &sender, const wux::RoutedEventArgs &args);
void EditSettingsClicked(const IInspectable &sender, const wux::RoutedEventArgs &args);
void ResetSettingsClicked(const IInspectable &sender, const wux::RoutedEventArgs &args);
void DisableSavingSettingsClicked(const IInspectable &sender, const wux::RoutedEventArgs &args);
void HideTrayClicked(const IInspectable &sender, const wux::RoutedEventArgs &args);
void ResetDynamicStateClicked(const IInspectable &sender, const wux::RoutedEventArgs &args);
void CompactThunkHeapClicked(const IInspectable &sender, const wux::RoutedEventArgs &args);
void StartupClicked(const IInspectable &sender, const wux::RoutedEventArgs &args);
void TipsAndTricksClicked(const IInspectable &sender, const wux::RoutedEventArgs &args);
void AboutClicked(const IInspectable &sender, const wux::RoutedEventArgs &args);
void ExitClicked(const IInspectable &sender, const wux::RoutedEventArgs &args);
private:
static wuxc::MenuFlyoutSubItem GetContainingSubMenu(const wuxc::MenuFlyoutItemBase &item, const wuxc::MenuFlyoutSubItem &subItem);
wuxc::MenuFlyoutSubItem GetItemParent(const wuxc::MenuFlyoutItemBase &item);
static txmp::TaskbarAppearance BuildAppearanceFromSubMenu(const wuxc::MenuFlyoutSubItem &menu);
wuxc::MenuFlyoutSubItem GetSubMenuForState(txmp::TaskbarState state);
txmp::LogSinkState m_SinkState = txmp::LogSinkState::Failed;
bool m_BlurSupported, m_HasPackageIdentity, m_SystemHasBattery;
};
}
FACTORY(winrt::TranslucentTB::Xaml::Pages, TrayFlyoutPage);
| 4,407
|
C++
|
.h
| 69
| 60.956522
| 132
| 0.837538
|
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,979
|
FramelessPage.h
|
TranslucentTB_TranslucentTB/Xaml/Pages/FramelessPage.h
|
#pragma once
#include "../dependencyproperty.h"
#include "../event.h"
#include "../factory.h"
#include "winrt.hpp"
#include "Pages/FramelessPage.g.h"
#include "Controls/ChromeButton.h"
namespace winrt::TranslucentTB::Xaml::Pages::implementation
{
struct FramelessPage : FramelessPageT<FramelessPage>
{
void InitializeComponent();
bool CanMove() noexcept;
virtual bool CanMoveCore() noexcept;
void ShowSystemMenu(const wf::Point &position);
void HideSystemMenu();
wf::Rect DragRegion();
virtual wf::Rect ExpandedDragRegion();
wf::Rect TitlebarButtonsRegion();
bool RequestClose();
virtual bool Close();
DECL_EVENT(ClosedDelegate, Closed, m_ClosedHandler);
void CloseClicked(const IInspectable &sender, const wux::RoutedEventArgs &args);
void SystemMenuOpening(const IInspectable &sender, const IInspectable &args);
DECL_DEPENDENCY_PROPERTY_WITH_DEFAULT(hstring, Title, box_value(L""));
DECL_DEPENDENCY_PROPERTY(wux::UIElement, UserContent);
DECL_DEPENDENCY_PROPERTY_WITH_DEFAULT(bool, ExpandIntoTitlebar, box_value(false));
DECL_DEPENDENCY_PROPERTY_WITH_DEFAULT(bool, IsClosable, box_value(true));
DECL_DEPENDENCY_PROPERTY_WITH_DEFAULT(bool, AlwaysOnTop, box_value(false));
DECL_DEPENDENCY_PROPERTY_WITH_DEFAULT(bool, IsActive, box_value(false));
DECL_DEPENDENCY_PROPERTY_WITH_DEFAULT(bool, TitleTooltipVisible, box_value(false));
wfc::IObservableVector<Controls::ChromeButton> TitlebarContent() noexcept
{
return m_TitlebarContent;
}
wfc::IObservableVector<wuxc::MenuFlyoutItemBase> SystemMenuContent() noexcept
{
return m_SystemMenuContent;
}
~FramelessPage();
private:
void SystemMenuChanged(const wfc::IObservableVector<wuxc::MenuFlyoutItemBase> &sender, const wfc::IVectorChangedEventArgs &event);
wfc::IObservableVector<Controls::ChromeButton> m_TitlebarContent = single_threaded_observable_vector<Controls::ChromeButton>();
bool m_NeedsSystemMenuRefresh = false;
event_token m_SystemMenuChangedToken;
wfc::IObservableVector<wuxc::MenuFlyoutItemBase> m_SystemMenuContent = single_threaded_observable_vector<wuxc::MenuFlyoutItemBase>();
static wux::Style LookupStyle(const IInspectable &key);
};
}
FACTORY(winrt::TranslucentTB::Xaml::Pages, FramelessPage);
| 2,253
|
C++
|
.h
| 50
| 42.22
| 135
| 0.79241
|
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,980
|
ColorPickerPage.h
|
TranslucentTB_TranslucentTB/Xaml/Pages/ColorPickerPage.h
|
#pragma once
#include "../event.h"
#include "../factory.h"
#include "../PropertyChangedBase.hpp"
#include "winrt.hpp"
#include "FramelessPage.h"
#include "Pages/ColorPickerPage.g.h"
namespace winrt::TranslucentTB::Xaml::Pages::implementation
{
struct ColorPickerPage : wux::Markup::ComponentConnectorT<ColorPickerPageT<ColorPickerPage>>
{
ColorPickerPage(txmp::TaskbarState state, Windows::UI::Color originalColor);
void InitializeComponent();
bool CanMoveCore() noexcept override;
bool Close() override;
DECL_EVENT(ColorChangedDelegate, ColorChanged, m_ColorChangedHandler);
DECL_EVENT(ChangesCommittedDelegate, ChangesCommitted, m_ChangesCommittedHandler);
void OkButtonClicked(const IInspectable &sender, const wux::RoutedEventArgs &args);
void CancelButtonClicked(const IInspectable &sender, const wux::RoutedEventArgs &args);
void DialogOpened(const IInspectable &sender, const wuxc::ContentDialogOpenedEventArgs &args) noexcept;
void DialogClosed(const IInspectable &sender, const wuxc::ContentDialogClosedEventArgs &args) noexcept;
Windows::UI::Color OriginalColor() noexcept;
void PickerColorChanged(const muxc::ColorPicker &sender, const muxc::ColorChangedEventArgs &args);
private:
static std::wstring_view GetResourceForState(txmp::TaskbarState state);
fire_and_forget OpenConfirmDialog();
bool m_DialogOpened = false;
txmp::TaskbarState m_State;
Windows::UI::Color m_OriginalColor;
};
}
FACTORY(winrt::TranslucentTB::Xaml::Pages, ColorPickerPage);
| 1,509
|
C++
|
.h
| 32
| 44.625
| 105
| 0.806958
|
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,981
|
ActionList.h
|
TranslucentTB_TranslucentTB/Xaml/Controls/ActionList.h
|
#pragma once
#include "../factory.h"
#include "winrt.hpp"
#include "Controls/ActionList.g.h"
namespace winrt::TranslucentTB::Xaml::Controls::implementation
{
struct ActionList : ActionListT<ActionList>
{
void ForwardActionKey(const IInspectable &sender, const wux::Input::KeyRoutedEventArgs &args);
void ForwardAction(const IInspectable &sender, const wux::RoutedEventArgs &args);
};
}
FACTORY(winrt::TranslucentTB::Xaml::Controls, ActionList);
| 455
|
C++
|
.h
| 13
| 33.230769
| 96
| 0.794989
|
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,982
|
ColorPicker.h
|
TranslucentTB_TranslucentTB/Xaml/Controls/ColorPicker.h
|
#pragma once
#include "../dependencyproperty.h"
#include "../factory.h"
#include "winrt.hpp"
#include "Controls/ColorPicker.g.h"
namespace winrt::TranslucentTB::Xaml::Controls::implementation
{
// Explicitly use ColorPicker_base because the XAML compiler generates an empty .xaml.g.h
struct ColorPicker : ColorPicker_base<ColorPicker>
{
private:
// make DECL_DEPENDENCY_PROPERTY_WITH_METADATA below work
static void OnDependencyPropertyChanged(const IInspectable &sender, const wux::DependencyPropertyChangedEventArgs &args);
// This one manually implemented to not expose the setter
DECL_DEPENDENCY_PROPERTY_FIELD(wfc::IObservableVector<Windows::UI::Color>, CustomPaletteColors, nullptr);
public:
ColorPicker();
~ColorPicker();
void OnApplyTemplate();
static wux::DependencyProperty CustomPaletteColorsProperty() noexcept
{
return DEPENDENCY_PROPERTY_FIELD(CustomPaletteColors);
}
wfc::IObservableVector<Windows::UI::Color> CustomPaletteColors()
{
return GetValue(DEPENDENCY_PROPERTY_FIELD(CustomPaletteColors)).as<wfc::IObservableVector<Windows::UI::Color>>();
}
DECL_DEPENDENCY_PROPERTY_WITH_DEFAULT(int32_t, CustomPaletteColumnCount, box_value(4));
DECL_DEPENDENCY_PROPERTY_WITH_METADATA(txmp::IColorPalette, CustomPalette,
wux::PropertyMetadata(Models::FluentColorPalette(), OnDependencyPropertyChanged));
DECL_DEPENDENCY_PROPERTY_WITH_METADATA(bool, IsColorPaletteVisible,
wux::PropertyMetadata(box_value(true), OnDependencyPropertyChanged));
// Gray-ish?
// Doesn't really matter, overriden in the template for SystemListLowColor
DECL_DEPENDENCY_PROPERTY_WITH_METADATA(Windows::UI::Color, CheckerBackgroundColor,
wux::PropertyMetadata(box_value(Windows::UI::Color { 0x19, 0x80, 0x80, 0x80 }), OnDependencyPropertyChanged));
DECL_DEPENDENCY_PROPERTY(wux::Media::Brush, HeaderBackground);
DECL_DEPENDENCY_PROPERTY_WITH_DEFAULT(wux::CornerRadius, HeaderCornerRadius, box_value(wux::CornerRadius { }));
static wux::DependencyProperty InvertedCheckerboardProperty() noexcept
{
return m_InvertedCheckerboardProperty;
}
static bool GetInvertedCheckerboard(const wuxc::Border &obj)
{
return obj.GetValue(m_InvertedCheckerboardProperty).as<bool>();
}
static void SetInvertedCheckerboard(const wuxc::Border &obj, bool value)
{
if (obj)
{
obj.SetValue(m_InvertedCheckerboardProperty, box_value(value));
}
}
private:
Windows::System::DispatcherQueueTimer m_DispatcherQueueTimer = Windows::System::DispatcherQueue::GetForCurrentThread().CreateTimer();
Windows::Globalization::NumberFormatting::DecimalFormatter m_DecimalFormatter;
std::optional<txmp::HsvColor> m_SavedHsvColor;
std::optional<Windows::UI::Color> m_SavedHsvColorRgbEquivalent, m_UpdatedRgbColor;
bool m_UpdateFromSpectrum = false;
// template parts and event handlers
#define TEMPLATE_PART_1_EVENT(TYPE, NAME, EVENT) \
TYPE m_ ## NAME = nullptr; \
event_token m_ ## NAME ## EVENT ## Token;
#define TEMPLATE_PART_2_EVENTS(TYPE, NAME, EVENT1, EVENT2) \
TYPE m_ ## NAME = nullptr; \
event_token m_ ## NAME ## EVENT1 ## Token, m_ ## NAME ## EVENT2 ## Token;
TEMPLATE_PART_2_EVENTS(Controls::ColorPickerSlider, Channel1Slider, ValueChanged, Loaded);
TEMPLATE_PART_2_EVENTS(Controls::ColorPickerSlider, Channel2Slider, ValueChanged, Loaded);
TEMPLATE_PART_2_EVENTS(Controls::ColorPickerSlider, Channel3Slider, ValueChanged, Loaded);
TEMPLATE_PART_2_EVENTS(Controls::ColorPickerSlider, AlphaChannelSlider, ValueChanged, Loaded);
TEMPLATE_PART_2_EVENTS(Controls::ColorPickerSlider, ColorSpectrumAlphaSlider, ValueChanged, Loaded);
TEMPLATE_PART_2_EVENTS(Controls::ColorPickerSlider, ColorSpectrumThirdDimensionSlider, ValueChanged, Loaded);
TEMPLATE_PART_2_EVENTS(wuxc::TextBox, Channel1TextBox, KeyDown, LostFocus);
TEMPLATE_PART_2_EVENTS(wuxc::TextBox, Channel2TextBox, KeyDown, LostFocus);
TEMPLATE_PART_2_EVENTS(wuxc::TextBox, Channel3TextBox, KeyDown, LostFocus);
TEMPLATE_PART_2_EVENTS(wuxc::TextBox, AlphaChannelTextBox, KeyDown, LostFocus);
TEMPLATE_PART_2_EVENTS(wuxc::TextBox, HexInputTextBox, KeyDown, LostFocus);
TEMPLATE_PART_2_EVENTS(wuxc::Border, CheckeredBackground1Border, Loaded, InvertedPropertyChanged);
TEMPLATE_PART_2_EVENTS(wuxc::Border, CheckeredBackground2Border, Loaded, InvertedPropertyChanged);
TEMPLATE_PART_2_EVENTS(wuxc::Border, CheckeredBackground3Border, Loaded, InvertedPropertyChanged);
TEMPLATE_PART_2_EVENTS(wuxc::Border, CheckeredBackground4Border, Loaded, InvertedPropertyChanged);
TEMPLATE_PART_2_EVENTS(wuxc::Border, CheckeredBackground5Border, Loaded, InvertedPropertyChanged);
TEMPLATE_PART_2_EVENTS(wuxc::Border, CheckeredBackground6Border, Loaded, InvertedPropertyChanged);
TEMPLATE_PART_2_EVENTS(wuxc::Border, CheckeredBackground7Border, Loaded, InvertedPropertyChanged);
TEMPLATE_PART_2_EVENTS(wuxc::Border, CheckeredBackground8Border, Loaded, InvertedPropertyChanged);
TEMPLATE_PART_2_EVENTS(wuxc::Border, CheckeredBackground9Border, Loaded, InvertedPropertyChanged);
TEMPLATE_PART_2_EVENTS(wuxc::Border, CheckeredBackground10Border, Loaded, InvertedPropertyChanged);
TEMPLATE_PART_2_EVENTS(muxc::Primitives::ColorSpectrum, ColorSpectrumControl, ColorChanged, GotFocus);
TEMPLATE_PART_2_EVENTS(wuxc::Primitives::ToggleButton, HsvToggleButton, Checked, Unchecked);
TEMPLATE_PART_2_EVENTS(wuxc::Primitives::ToggleButton, RgbToggleButton, Checked, Unchecked);
TEMPLATE_PART_1_EVENT(wuxc::Border, P1PreviewBorder, PointerPressed);
TEMPLATE_PART_1_EVENT(wuxc::Border, P2PreviewBorder, PointerPressed);
TEMPLATE_PART_1_EVENT(wuxc::Border, N1PreviewBorder, PointerPressed);
TEMPLATE_PART_1_EVENT(wuxc::Border, N2PreviewBorder, PointerPressed);
#undef TEMPLATE_PART_2_EVENTS
#undef TEMPLATE_PART_1_EVENT
bool m_IsInitialized = false;
bool m_EventsConnected = false;
void ConnectEvents(bool connected);
event_token m_LoadedToken, m_UnloadedToken;
void OnLoaded(const IInspectable &sender, const wux::RoutedEventArgs &args);
void OnUnloaded(const IInspectable &sender, const wux::RoutedEventArgs &args);
template<txmp::ColorChannel channel>
void OnChannelSliderValueChanged(const IInspectable &sender, const wuxc::Primitives::RangeBaseValueChangedEventArgs &args);
void OnSpectrumAlphaChannelSliderValueChanged(const IInspectable &sender, const wuxc::Primitives::RangeBaseValueChangedEventArgs &args);
void OnThirdDimensionChannelSliderValueChanged(const IInspectable &sender, const wuxc::Primitives::RangeBaseValueChangedEventArgs &args);
template<txmp::ColorChannel channel>
void OnChannelSliderLoaded(const IInspectable &sender, const wux::RoutedEventArgs &args);
void OnSpectrumAlphaChannelSliderLoaded(const IInspectable &sender, const wux::RoutedEventArgs &args);
void OnThirdDimensionChannelSliderLoaded(const IInspectable &sender, const wux::RoutedEventArgs &args);
template<txmp::ColorChannel channel>
void OnChannelTextBoxKeyDown(const IInspectable &sender, const wux::Input::KeyRoutedEventArgs &args);
template<txmp::ColorChannel channel>
void OnChannelTextBoxLostFocus(const IInspectable &sender, const wux::RoutedEventArgs &args);
void OnHexInputTextBoxKeyDown(const IInspectable &sender, const wux::Input::KeyRoutedEventArgs &args);
void OnHexInputTextBoxLostFocus(const IInspectable &sender, const wux::RoutedEventArgs &args);
fire_and_forget OnCheckeredBackgroundBorderLoaded(const IInspectable &sender, const wux::RoutedEventArgs &args);
void OnCheckeredBackgroundInvertedPropertyChanged(const wux::DependencyObject &sender, const wux::DependencyProperty &prop);
void OnColorSpectrumControlColorChanged(const IInspectable &sender, const muxc::ColorChangedEventArgs &args);
void OnColorSpectrumControlGotFocus(const IInspectable &sender, const wux::RoutedEventArgs &args);
template<txmp::ColorRepresentation representation>
void OnColorRepresentationToggleButtonCheckedChanged(const IInspectable &sender, const wux::RoutedEventArgs &args);
void OnPreviewBorderPointerPressed(const IInspectable &sender, const wux::Input::IPointerRoutedEventArgs &args);
event_token m_ColorPropertyChangedToken;
static void OnColorPropertyChanged(const wux::DependencyObject &sender, const wux::DependencyProperty &prop);
event_token m_DispatcherQueueTimerTickToken;
void OnDispatcherQueueTimerTick(const IInspectable &sender, const IInspectable &args);
// revoker is OK here because we don't need to hold a strong ref
wux::XamlRoot::Changed_revoker m_XamlRootChangedRevoker;
void OnXamlRootChanged(const wux::XamlRoot &sender, const wux::XamlRootChangedEventArgs &args);
// store ready to use event handlers to avoid needing to reallocate those all the time.
#define EVENT_HANDLER(TYPE, NAME, FUNCTION) \
TYPE NAME = { get_weak(), &ColorPicker::FUNCTION };
EVENT_HANDLER(wuxc::Primitives::RangeBaseValueChangedEventHandler, m_Channel1SliderValueChangedHandler, OnChannelSliderValueChanged<txmp::ColorChannel::Channel1>);
EVENT_HANDLER(wuxc::Primitives::RangeBaseValueChangedEventHandler, m_Channel2SliderValueChangedHandler, OnChannelSliderValueChanged<txmp::ColorChannel::Channel2>);
EVENT_HANDLER(wuxc::Primitives::RangeBaseValueChangedEventHandler, m_Channel3SliderValueChangedHandler, OnChannelSliderValueChanged<txmp::ColorChannel::Channel3>);
EVENT_HANDLER(wuxc::Primitives::RangeBaseValueChangedEventHandler, m_AlphaChannelSliderValueChangedHandler, OnChannelSliderValueChanged<txmp::ColorChannel::Alpha>);
EVENT_HANDLER(wuxc::Primitives::RangeBaseValueChangedEventHandler, m_SpectrumAlphaChannelSliderValueChangedHandler, OnSpectrumAlphaChannelSliderValueChanged);
EVENT_HANDLER(wuxc::Primitives::RangeBaseValueChangedEventHandler, m_ThirdDimensionSliderValueChangedHandler, OnThirdDimensionChannelSliderValueChanged);
EVENT_HANDLER(wux::RoutedEventHandler, m_Channel1SliderLoadedHandler, OnChannelSliderLoaded<txmp::ColorChannel::Channel1>);
EVENT_HANDLER(wux::RoutedEventHandler, m_Channel2SliderLoadedHandler, OnChannelSliderLoaded<txmp::ColorChannel::Channel2>);
EVENT_HANDLER(wux::RoutedEventHandler, m_Channel3SliderLoadedHandler, OnChannelSliderLoaded<txmp::ColorChannel::Channel3>);
EVENT_HANDLER(wux::RoutedEventHandler, m_AlphaChannelSliderLoadedHandler, OnChannelSliderLoaded<txmp::ColorChannel::Alpha>);
EVENT_HANDLER(wux::RoutedEventHandler, m_SpectrumAlphaChannelSliderLoadedHandler, OnSpectrumAlphaChannelSliderLoaded);
EVENT_HANDLER(wux::RoutedEventHandler, m_ThirdDimensionSliderLoadedHandler, OnThirdDimensionChannelSliderLoaded);
EVENT_HANDLER(wux::Input::KeyEventHandler, m_Channel1TextBoxKeyDownHandler, OnChannelTextBoxKeyDown<txmp::ColorChannel::Channel1>);
EVENT_HANDLER(wux::Input::KeyEventHandler, m_Channel2TextBoxKeyDownHandler, OnChannelTextBoxKeyDown<txmp::ColorChannel::Channel2>);
EVENT_HANDLER(wux::Input::KeyEventHandler, m_Channel3TextBoxKeyDownHandler, OnChannelTextBoxKeyDown<txmp::ColorChannel::Channel3>);
EVENT_HANDLER(wux::Input::KeyEventHandler, m_AlphaChannelTextBoxKeyDownHandler, OnChannelTextBoxKeyDown<txmp::ColorChannel::Alpha>);
EVENT_HANDLER(wux::Input::KeyEventHandler, m_HexInputTextBoxKeyDownHandler, OnHexInputTextBoxKeyDown);
EVENT_HANDLER(wux::RoutedEventHandler, m_Channel1TextBoxLostFocusHandler, OnChannelTextBoxLostFocus<txmp::ColorChannel::Channel1>);
EVENT_HANDLER(wux::RoutedEventHandler, m_Channel2TextBoxLostFocusHandler, OnChannelTextBoxLostFocus<txmp::ColorChannel::Channel2>);
EVENT_HANDLER(wux::RoutedEventHandler, m_Channel3TextBoxLostFocusHandler, OnChannelTextBoxLostFocus<txmp::ColorChannel::Channel3>);
EVENT_HANDLER(wux::RoutedEventHandler, m_AlphaChannelTextBoxLostFocusHandler, OnChannelTextBoxLostFocus<txmp::ColorChannel::Alpha>);
EVENT_HANDLER(wux::RoutedEventHandler, m_HexInputTextBoxLostFocusHandler, OnHexInputTextBoxLostFocus);
EVENT_HANDLER(wux::RoutedEventHandler, m_CheckeredBackgroundBorderLoadedHandler, OnCheckeredBackgroundBorderLoaded);
EVENT_HANDLER(wux::DependencyPropertyChangedCallback, m_CheckeredBackgroundBorderInvertedPropertyChangedHandler, OnCheckeredBackgroundInvertedPropertyChanged)
EVENT_HANDLER(wux::RoutedEventHandler, m_ColorSpectrumControlGotFocusHandler, OnColorSpectrumControlGotFocus);
EVENT_HANDLER(wux::RoutedEventHandler, m_HsvToggleButtonCheckedChangedHandler, OnColorRepresentationToggleButtonCheckedChanged<txmp::ColorRepresentation::Hsva>);
EVENT_HANDLER(wux::RoutedEventHandler, m_RgbToggleButtonCheckedChangedHandler, OnColorRepresentationToggleButtonCheckedChanged<txmp::ColorRepresentation::Rgba>);
EVENT_HANDLER(wux::Input::PointerEventHandler, m_PreviewBorderPointerPressedHandler, OnPreviewBorderPointerPressed);
// These two manually declared because macros suck
wf::TypedEventHandler<muxc::Primitives::ColorSpectrum, muxc::ColorChangedEventArgs> m_ColorSpectrumControlColorChangedHandler = { get_weak(), &ColorPicker::OnColorSpectrumControlColorChanged };
wf::TypedEventHandler<wux::XamlRoot, wux::XamlRootChangedEventArgs> m_XamlRootChangedHandler = { get_weak(), &ColorPicker::OnXamlRootChanged };
#undef EVENT_HANDLER
void ApplyChannelTextBoxValue(const wuxc::TextBox &channelTextBox, txmp::ColorChannel channel);
void UpdateColorRightNow(Windows::UI::Color newColor, bool isFromSpectrum = false);
void ScheduleColorUpdate(Windows::UI::Color newColor, bool isFromSpectrum = false);
void SetActiveColorRepresentation(txmp::ColorRepresentation representation);
void SetColorChannel(txmp::ColorRepresentation representation, txmp::ColorChannel channel, double newValue);
void UpdateVisualState(bool useTransitions);
void UpdateColorControlValues();
void UpdateChannelSliderBackgrounds();
void UpdateChannelSliderBackground(const ColorPickerSlider &slider, txmp::ColorChannel channel, txmp::ColorRepresentation representation);
void UpdateCustomPalette();
txmp::ColorRepresentation GetActiveColorRepresentation();
txmp::ColorChannel GetActiveColorSpectrumThirdDimension();
static wux::DependencyProperty m_InvertedCheckerboardProperty;
};
}
FACTORY(winrt::TranslucentTB::Xaml::Controls, ColorPicker);
| 14,117
|
C++
|
.h
| 181
| 74.834254
| 195
| 0.829059
|
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,983
|
ConstrainedBox.h
|
TranslucentTB_TranslucentTB/Xaml/Controls/ConstrainedBox.h
|
#pragma once
#include "../dependencyproperty.h"
#include "../factory.h"
#include "winrt.hpp"
#include "Controls/ConstrainedBox.g.h"
namespace winrt::TranslucentTB::Xaml::Controls::implementation
{
struct ConstrainedBox : ConstrainedBoxT<ConstrainedBox>
{
private:
// make DECL_DEPENDENCY_PROPERTY_WITH_METADATA below work
static void OnDependencyPropertyChanged(const IInspectable &sender, const wux::DependencyPropertyChangedEventArgs &args);
public:
ConstrainedBox() = default;
wf::Size MeasureOverride(wf::Size availableSize);
wf::Size ArrangeOverride(wf::Size finalSize);
DECL_DEPENDENCY_PROPERTY_WITH_METADATA(int32_t, MultipleX,
wux::PropertyMetadata(box_value(1), OnDependencyPropertyChanged));
DECL_DEPENDENCY_PROPERTY_WITH_METADATA(int32_t, MultipleY,
wux::PropertyMetadata(box_value(1), OnDependencyPropertyChanged));
private:
static bool IsPositiveRealNumber(double value) noexcept;
static void ApplyMultiple(int32_t multiple, float &value) noexcept;
void CalculateConstrainedSize(wf::Size &availableSize);
// Value used to determine when we re-calculate in the arrange step or re-use a previous calculation. Within roughly a pixel seems like a good value?
static constexpr double CALCULATION_TOLERANCE = 1.5;
wf::Size m_OriginalSize = { };
wf::Size m_LastMeasuredSize = { };
};
}
FACTORY(winrt::TranslucentTB::Xaml::Controls, ConstrainedBox);
| 1,420
|
C++
|
.h
| 31
| 42.709677
| 151
| 0.784627
|
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,984
|
SwitchPresenter.h
|
TranslucentTB_TranslucentTB/Xaml/Controls/SwitchPresenter.h
|
#pragma once
#include "../dependencyproperty.h"
#include "../factory.h"
#include "winrt.hpp"
#include "Controls/SwitchPresenter.g.h"
namespace winrt::TranslucentTB::Xaml::Controls::implementation
{
struct SwitchPresenter : SwitchPresenterT<SwitchPresenter>
{
private:
// make DECL_DEPENDENCY_PROPERTY_WITH_METADATA below work
static void OnValueChanged(const IInspectable &sender, const wux::DependencyPropertyChangedEventArgs &args);
// This one manually implemented to not expose the setter
DECL_DEPENDENCY_PROPERTY_FIELD(Controls::Case, CurrentCase, nullptr);
public:
SwitchPresenter();
static wux::DependencyProperty CurrentCaseProperty() noexcept
{
return DEPENDENCY_PROPERTY_FIELD(CurrentCase);
}
Controls::Case CurrentCase()
{
return GetValue(DEPENDENCY_PROPERTY_FIELD(CurrentCase)).as<Controls::Case>();
}
DECL_DEPENDENCY_PROPERTY_WITH_METADATA(IInspectable, Value, wux::PropertyMetadata(nullptr, OnValueChanged));
wfc::IObservableVector<Controls::Case> SwitchCases() noexcept
{
return m_Cases;
}
void OnApplyTemplate();
~SwitchPresenter();
private:
void EvaluateCases();
void OnCasesChanged(const wfc::IObservableVector<Controls::Case> &sender, const wfc::IVectorChangedEventArgs &event);
event_token m_CasesChangedToken;
wfc::IObservableVector<Controls::Case> m_Cases = single_threaded_observable_vector<Controls::Case>();
void OnLoaded(const IInspectable &sender, const wux::RoutedEventArgs &args);
event_token m_LoadedToken;
static bool CompareValues(const IInspectable &compare, const IInspectable &value);
static hstring ValueToString(const IInspectable &value);
};
}
FACTORY(winrt::TranslucentTB::Xaml::Controls, SwitchPresenter);
| 1,726
|
C++
|
.h
| 43
| 37.27907
| 119
| 0.793165
|
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,985
|
FocusBorderColorSpectrum.h
|
TranslucentTB_TranslucentTB/Xaml/Controls/FocusBorderColorSpectrum.h
|
#pragma once
#include "../factory.h"
#include "winrt.hpp"
#include "Controls/FocusBorderColorSpectrum.g.h"
namespace winrt::TranslucentTB::Xaml::Controls::implementation
{
struct FocusBorderColorSpectrum : FocusBorderColorSpectrum_base<FocusBorderColorSpectrum>
{
FocusBorderColorSpectrum() = default;
void OnApplyTemplate();
private:
wux::FrameworkElement::SizeChanged_revoker m_SizingGridSizeChangedRevoker;
wuxc::Border m_FocusBorder;
void OnSizingGridSizeChanged(const IInspectable &sender, const wux::SizeChangedEventArgs &args);
void UpdateFocusBorder(const wux::FrameworkElement &sizingGrid);
};
}
FACTORY(winrt::TranslucentTB::Xaml::Controls, FocusBorderColorSpectrum);
| 715
|
C++
|
.h
| 18
| 36.666667
| 98
| 0.808973
|
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,986
|
colorpickerrendering.hpp
|
TranslucentTB_TranslucentTB/Xaml/Controls/colorpickerrendering.hpp
|
#pragma once
#include <cstdint>
#include <vector>
#include "util/color.hpp"
constexpr Util::Color GetCheckerPixelColor(int32_t x, int32_t y, Util::Color checkerColor, double renderScale, bool invert = false) noexcept
{
constexpr int32_t CHECKER_SIZE_PRE_SCALE = 4;
const int32_t checkerSize = static_cast<int32_t>(CHECKER_SIZE_PRE_SCALE * renderScale);
// We want the checkered pattern to alternate both vertically and horizontally.
// In order to achieve that, we'll toggle visibility of the current pixel on or off
// depending on both its x- and its y-position. If x == CheckerSize, we'll turn visibility off,
// but then if y == CheckerSize, we'll turn it back on.
// The below is a shorthand for the above intent.
bool pixelShouldBeBlank = (x / checkerSize + y / checkerSize) % 2 == 0 ? 255 : 0;
if (invert)
{
pixelShouldBeBlank = !pixelShouldBeBlank;
}
if (pixelShouldBeBlank)
{
return { };
}
else
{
return checkerColor.Premultiply();
}
}
constexpr Util::Color CompositeColors(Util::Color bottom, Util::Color top) noexcept
{
/* The following algorithm is used to blend the two bitmaps creating the final composite.
* In this formula, pixel data is normalized 0..1, actual pixel data is in the range 0..255.
* The color channel gradient should apply OVER the checkered background.
*
* R = R0 * A0 * (1 - A1) + R1 * A1 = RA0 * (1 - A1) + RA1
* G = G0 * A0 * (1 - A1) + G1 * A1 = GA0 * (1 - A1) + GA1
* B = B0 * A0 * (1 - A1) + B1 * A1 = BA0 * (1 - A1) + BA1
* A = A0 * (1 - A1) + A1 = A0 * (1 - A1) + A1
*
* Considering only the red channel, some algebraic transformation is applied to
* make the math quicker to solve.
*
* => ((RA0 / 255.0) * (1.0 - A1 / 255.0) + (RA1 / 255.0)) * 255.0
* => ((RA0 * 255) - (RA0 * A1) + (RA1 * 255)) / 255
*/
return {
static_cast<uint8_t>(((bottom.R * 255) - (bottom.R * top.A) + (top.R * 255)) / 255),
static_cast<uint8_t>(((bottom.G * 255) - (bottom.G * top.A) + (top.G * 255)) / 255),
static_cast<uint8_t>(((bottom.B * 255) - (bottom.B * top.A) + (top.B * 255)) / 255),
static_cast<uint8_t>(((bottom.A * 255) - (bottom.A * top.A) + (top.A * 255)) / 255)
};
}
constexpr void FillCheckeredBitmap(uint8_t *bgraPixelData, int32_t width, int32_t height, double renderScale, Util::Color checkerColor, bool invert) noexcept
{
for (int y = 0; y < height; y++)
{
const int32_t pixelRowIndex = width * y;
for (int x = 0; x < width; x++)
{
const auto rgbColor = GetCheckerPixelColor(x, y, checkerColor, renderScale, invert);
const int32_t pixelDataIndex = 4 * (x + pixelRowIndex);
bgraPixelData[pixelDataIndex + 0] = rgbColor.B;
bgraPixelData[pixelDataIndex + 1] = rgbColor.G;
bgraPixelData[pixelDataIndex + 2] = rgbColor.R;
bgraPixelData[pixelDataIndex + 3] = rgbColor.A;
}
}
}
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);
Util::Color GetChannelPixelColor(double channelValue, txmp::ColorChannel channel, txmp::ColorRepresentation representation, Util::HsvColor baseHsvColor, Util::Color baseRgbColor);
| 3,331
|
C++
|
.h
| 69
| 45.782609
| 315
| 0.689231
|
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,987
|
ChromeButton.h
|
TranslucentTB_TranslucentTB/Xaml/Controls/ChromeButton.h
|
#pragma once
#include "../dependencyproperty.h"
#include "../factory.h"
#include "winrt.hpp"
#include "Controls/ChromeButton.g.h"
namespace winrt::TranslucentTB::Xaml::Controls::implementation
{
// Explicitly use ChromeButton_base because the XAML compiler generates an empty .xaml.g.h
struct ChromeButton : ChromeButton_base<ChromeButton>
{
ChromeButton();
DECL_DEPENDENCY_PROPERTY(wuxc::IconElement, Icon);
DECL_DEPENDENCY_PROPERTY(Windows::UI::Color, NormalForeground);
DECL_DEPENDENCY_PROPERTY(Windows::UI::Color, NormalBackground);
DECL_DEPENDENCY_PROPERTY(Windows::UI::Color, HoverForeground);
DECL_DEPENDENCY_PROPERTY(Windows::UI::Color, HoverBackground);
DECL_DEPENDENCY_PROPERTY(Windows::UI::Color, PressedForeground);
DECL_DEPENDENCY_PROPERTY(Windows::UI::Color, PressedBackground);
DECL_DEPENDENCY_PROPERTY_WITH_DEFAULT(bool, IsTogglable, box_value(false));
void OnToggle();
};
}
FACTORY(winrt::TranslucentTB::Xaml::Controls, ChromeButton);
| 981
|
C++
|
.h
| 23
| 40.391304
| 91
| 0.791186
|
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,988
|
Case.h
|
TranslucentTB_TranslucentTB/Xaml/Controls/Case.h
|
#pragma once
#include "../dependencyproperty.h"
#include "../factory.h"
#include "winrt.hpp"
#include "Controls/Case.g.h"
namespace winrt::TranslucentTB::Xaml::Controls::implementation
{
struct Case : CaseT<Case>
{
Case() = default;
DECL_DEPENDENCY_PROPERTY(wux::UIElement, Content);
DECL_DEPENDENCY_PROPERTY_WITH_DEFAULT(bool, IsDefault, box_value(false));
DECL_DEPENDENCY_PROPERTY(IInspectable, Value);
};
}
FACTORY(winrt::TranslucentTB::Xaml::Controls, Case);
| 478
|
C++
|
.h
| 16
| 27.9375
| 75
| 0.764192
|
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,989
|
ColorPickerSlider.h
|
TranslucentTB_TranslucentTB/Xaml/Controls/ColorPickerSlider.h
|
#pragma once
#include "../dependencyproperty.h"
#include "../factory.h"
#include "winrt.hpp"
#include "Controls/ColorPickerSlider.g.h"
namespace winrt::TranslucentTB::Xaml::Controls::implementation
{
// Explicitly use ColorPickerSlider_base because the XAML compiler generates an empty .xaml.g.h
struct ColorPickerSlider : ColorPickerSlider_base<ColorPickerSlider>
{
private:
// make DECL_DEPENDENCY_PROPERTY_WITH_METADATA below work
static void OnDependencyPropertyChanged(const IInspectable &sender, const wux::DependencyPropertyChangedEventArgs &args);
public:
ColorPickerSlider();
~ColorPickerSlider();
void UpdateColors();
// Colors::White
DECL_DEPENDENCY_PROPERTY_WITH_METADATA(Windows::UI::Color, Color,
wux::PropertyMetadata(box_value(Windows::UI::Color { 0xFF, 0xFF, 0xFF, 0xFF }), OnDependencyPropertyChanged));
DECL_DEPENDENCY_PROPERTY_WITH_METADATA(txmp::ColorChannel, ColorChannel,
wux::PropertyMetadata(box_value(txmp::ColorChannel::Channel1), OnDependencyPropertyChanged));
DECL_DEPENDENCY_PROPERTY_WITH_METADATA(txmp::ColorRepresentation, ColorRepresentation,
wux::PropertyMetadata(box_value(txmp::ColorRepresentation::Rgba), OnDependencyPropertyChanged));
// Colors::White but in HSV
DECL_DEPENDENCY_PROPERTY_WITH_METADATA(txmp::HsvColor, HsvColor,
wux::PropertyMetadata(box_value(txmp::HsvColor { 0.0, 0.0, 1.0, 1.0 }), OnDependencyPropertyChanged));
DECL_DEPENDENCY_PROPERTY_WITH_METADATA(bool, IsAlphaMaxForced,
wux::PropertyMetadata(box_value(true), OnDependencyPropertyChanged));
DECL_DEPENDENCY_PROPERTY_WITH_METADATA(bool, IsAutoUpdatingEnabled,
wux::PropertyMetadata(box_value(true), OnDependencyPropertyChanged));
DECL_DEPENDENCY_PROPERTY_WITH_METADATA(bool, IsSaturationValueMaxForced,
wux::PropertyMetadata(box_value(true), OnDependencyPropertyChanged));
// Gray-ish?
// Doesn't really matter, overriden in the template for SystemListLowColor
DECL_DEPENDENCY_PROPERTY_WITH_METADATA(Windows::UI::Color, CheckerBackgroundColor,
wux::PropertyMetadata(box_value(Windows::UI::Color { 0x19, 0x80, 0x80, 0x80 }), OnDependencyPropertyChanged));
void OnApplyTemplate();
wf::Size MeasureOverride(const wf::Size &availableSize);
private:
wf::Size oldSize = {};
wf::Size measuredSize = {};
wf::Size cachedSize = {};
event_token m_OrientationPropertyChangedToken;
static void OnOrientationPropertyChanged(const wux::DependencyObject &sender, const wux::DependencyProperty &prop);
wux::Shapes::Rectangle m_HorizontalTrackRect = nullptr;
wux::Shapes::Rectangle m_VerticalTrackRect = nullptr;
event_token m_LoadedToken, m_UnloadedToken;
void OnLoaded(const IInspectable &sender, const wux::RoutedEventArgs &args);
void OnUnloaded(const IInspectable &sender, const wux::RoutedEventArgs &args);
// revoker is OK here because we don't need to hold a strong ref
wux::XamlRoot::Changed_revoker m_XamlRootChangedRevoker;
void OnXamlRootChanged(const wux::XamlRoot &sender, const wux::XamlRootChangedEventArgs &args);
wf::TypedEventHandler<wux::XamlRoot, wux::XamlRootChangedEventArgs> m_XamlRootChangedHandler = { get_weak(), &ColorPickerSlider::OnXamlRootChanged };
void UpdateVisualState();
void UpdateBackground(txmp::HsvColor color);
fire_and_forget RenderBackground(weak_ref<wux::Shapes::Rectangle> rect_weak, txmp::HsvColor color, wuxc::Orientation orientation, int32_t width, int32_t height, double renderScale);
};
}
FACTORY(winrt::TranslucentTB::Xaml::Controls, ColorPickerSlider);
| 3,520
|
C++
|
.h
| 60
| 55.616667
| 183
| 0.794767
|
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,990
|
UniformGrid.h
|
TranslucentTB_TranslucentTB/Xaml/Controls/UniformGrid.h
|
#pragma once
#include "../dependencyproperty.h"
#include "../factory.h"
#include "winrt.hpp"
#include <experimental/generator>
#include <tuple>
#include <vector>
#include "Controls/UniformGrid.g.h"
namespace winrt::TranslucentTB::Xaml::Controls::implementation
{
struct UniformGrid : UniformGridT<UniformGrid>
{
private:
static void OnDependencyPropertyChanged(const IInspectable &ender, const wux::DependencyPropertyChangedEventArgs &args);
public:
wf::Size MeasureOverride(const wf::Size &availableSize);
wf::Size ArrangeOverride(const wf::Size &finalSize);
DECL_DEPENDENCY_PROPERTY_WITH_METADATA(int32_t, Columns,
wux::PropertyMetadata(box_value(0), OnDependencyPropertyChanged));
DECL_DEPENDENCY_PROPERTY_WITH_METADATA(int32_t, FirstColumn,
wux::PropertyMetadata(box_value(0), OnDependencyPropertyChanged));
DECL_DEPENDENCY_PROPERTY_WITH_METADATA(wuxc::Orientation, Orientation,
wux::PropertyMetadata(box_value(wuxc::Orientation::Horizontal), OnDependencyPropertyChanged));
DECL_DEPENDENCY_PROPERTY_WITH_METADATA(int32_t, Rows,
wux::PropertyMetadata(box_value(0), OnDependencyPropertyChanged));
static wux::DependencyProperty AutoLayoutProperty() noexcept
{
return m_AutoLayoutProperty;
}
static wf::IReference<bool> GetAutoLayout(const wux::FrameworkElement &element)
{
if (element)
{
return element.GetValue(m_AutoLayoutProperty).as<wf::IReference<bool>>();
}
else
{
return nullptr;
}
}
static void SetAutoLayout(const wux::FrameworkElement &element, const wf::IReference<bool> &value)
{
if (element)
{
element.SetValue(m_AutoLayoutProperty, value);
}
}
private:
static wf::IReference<bool> GetAutoLayout(const wuxc::RowDefinition &element)
{
if (element)
{
return element.GetValue(m_AutoLayoutProperty).as<wf::IReference<bool>>();
}
else
{
return nullptr;
}
}
static void SetAutoLayout(const wuxc::RowDefinition &element, const wf::IReference<bool> &value)
{
if (element)
{
element.SetValue(m_AutoLayoutProperty, value);
}
}
static wf::IReference<bool> GetAutoLayout(const wuxc::ColumnDefinition&element)
{
if (element)
{
return element.GetValue(m_AutoLayoutProperty).as<wf::IReference<bool>>();
}
else
{
return nullptr;
}
}
static void SetAutoLayout(const wuxc::ColumnDefinition &element, const wf::IReference<bool> &value)
{
if (element)
{
element.SetValue(m_AutoLayoutProperty, value);
}
}
static std::tuple<int, int> GetDimensions(const std::vector<wux::FrameworkElement> &visible, int rows, int cols, int firstColumn);
void SetupRowDefinitions(uint32_t rows);
void SetupColumnDefinitions(uint32_t columns);
bool GetSpot(int i, int j);
void FillSpots(bool value, int row, int column, int width, int height);
std::experimental::generator<std::tuple<int, int>> GetFreeSpots(int firstColumn, bool topDown);
static wux::DependencyProperty m_AutoLayoutProperty;
std::vector<bool> m_TakenSpots;
int m_SpotsHeight = 0, m_SpotsWidth = 0;
std::vector<wux::UIElement> m_Overflow;
};
}
FACTORY(winrt::TranslucentTB::Xaml::Controls, UniformGrid);
| 3,179
|
C++
|
.h
| 97
| 29.371134
| 132
| 0.752857
|
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,991
|
ThicknessFilterConverter.h
|
TranslucentTB_TranslucentTB/Xaml/Converters/ThicknessFilterConverter.h
|
#pragma once
#include "../dependencyproperty.h"
#include "../factory.h"
#include "winrt.hpp"
#include "Converters/ThicknessFilterConverter.g.h"
namespace winrt::TranslucentTB::Xaml::Converters::implementation
{
struct ThicknessFilterConverter : ThicknessFilterConverterT<ThicknessFilterConverter>
{
ThicknessFilterConverter() = default;
DECL_DEPENDENCY_PROPERTY_WITH_DEFAULT(txmp::ThicknessFilterKind, Filter, box_value(txmp::ThicknessFilterKind::None));
DECL_DEPENDENCY_PROPERTY_WITH_DEFAULT(double, Scale, box_value(1.0));
IInspectable Convert(const IInspectable &value, const wux::Interop::TypeName &targetType, const IInspectable ¶meter, const hstring &language);
IInspectable ConvertBack(const IInspectable &value, const wux::Interop::TypeName &targetType, const IInspectable ¶meter, const hstring &language);
private:
static wux::Thickness ApplyFilter(wux::Thickness thickness, txmp::ThicknessFilterKind filter);
};
}
FACTORY(winrt::TranslucentTB::Xaml::Converters, ThicknessFilterConverter);
| 1,029
|
C++
|
.h
| 19
| 52
| 152
| 0.814741
|
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,992
|
ContrastBrushConverter.h
|
TranslucentTB_TranslucentTB/Xaml/Converters/ContrastBrushConverter.h
|
#pragma once
#include "../factory.h"
#include "winrt.hpp"
#include "Converters/ContrastBrushConverter.g.h"
namespace winrt::TranslucentTB::Xaml::Converters::implementation
{
struct ContrastBrushConverter : ContrastBrushConverterT<ContrastBrushConverter>
{
ContrastBrushConverter() = default;
uint8_t AlphaThreshold() noexcept;
void AlphaThreshold(uint8_t value) noexcept;
IInspectable Convert(const IInspectable &value, const wux::Interop::TypeName &targetType, const IInspectable ¶meter, const hstring &language);
IInspectable ConvertBack(const IInspectable &value, const wux::Interop::TypeName &targetType, const IInspectable ¶meter, const hstring &language);
private:
uint8_t m_AlphaThreshold = 128;
};
}
FACTORY(winrt::TranslucentTB::Xaml::Converters, ContrastBrushConverter);
| 811
|
C++
|
.h
| 18
| 42.833333
| 152
| 0.811944
|
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,993
|
ColorToColorShadeConverter.h
|
TranslucentTB_TranslucentTB/Xaml/Converters/ColorToColorShadeConverter.h
|
#pragma once
#include "../factory.h"
#include "winrt.hpp"
#include "Converters/ColorToColorShadeConverter.g.h"
namespace winrt::TranslucentTB::Xaml::Converters::implementation
{
struct ColorToColorShadeConverter : ColorToColorShadeConverterT<ColorToColorShadeConverter>
{
ColorToColorShadeConverter() = default;
IInspectable Convert(const IInspectable &value, const wux::Interop::TypeName &targetType, const IInspectable ¶meter, const hstring &language);
IInspectable ConvertBack(const IInspectable &value, const wux::Interop::TypeName &targetType, const IInspectable ¶meter, const hstring &language);
private:
static Windows::UI::Color GetShade(Windows::UI::Color col, int shade);
};
}
FACTORY(winrt::TranslucentTB::Xaml::Converters, ColorToColorShadeConverter);
| 789
|
C++
|
.h
| 16
| 47.25
| 152
| 0.816406
|
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,994
|
ColorToDisplayNameConverter.h
|
TranslucentTB_TranslucentTB/Xaml/Converters/ColorToDisplayNameConverter.h
|
#pragma once
#include "../factory.h"
#include "winrt.hpp"
#include "Converters/ColorToDisplayNameConverter.g.h"
namespace winrt::TranslucentTB::Xaml::Converters::implementation
{
struct ColorToDisplayNameConverter : ColorToDisplayNameConverterT<ColorToDisplayNameConverter>
{
ColorToDisplayNameConverter() = default;
IInspectable Convert(const IInspectable &value, const wux::Interop::TypeName &targetType, const IInspectable ¶meter, const hstring &language);
IInspectable ConvertBack(const IInspectable &value, const wux::Interop::TypeName &targetType, const IInspectable ¶meter, const hstring &language);
};
}
FACTORY(winrt::TranslucentTB::Xaml::Converters, ColorToDisplayNameConverter);
| 711
|
C++
|
.h
| 14
| 48.857143
| 152
| 0.82684
|
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,995
|
testingdata.hpp
|
TranslucentTB_TranslucentTB/Tests/testingdata.hpp
|
#pragma once
#include <tuple>
static constexpr wchar_t numbers[] = {
L'0', L'1', L'2', L'3', L'4', L'5', L'6', L'7', L'8', L'9'
};
static constexpr std::tuple<wchar_t, wchar_t> alphabet[] = {
{ L'A', L'a'}, { L'B', L'b'}, { L'C', L'c'}, { L'D', L'd'},
{ L'E', L'e'}, { L'F', L'f'}, { L'G', L'g'}, { L'H', L'h'},
{ L'I', L'i'}, { L'J', L'j'}, { L'K', L'k'}, { L'L', L'l'},
{ L'M', L'm'}, { L'N', L'n'}, { L'O', L'o'}, { L'P', L'p'},
{ L'Q', L'q'}, { L'R', L'r'}, { L'S', L's'}, { L'T', L't'},
{ L'U', L'u'}, { L'V', L'v'}, { L'W', L'w'}, { L'X', L'x'},
{ L'Y', L'y'}, { L'Z', L'z'}
};
static constexpr wchar_t specialCharacters[] = {
L' ', L'!', L'"', L'#', L'$', L'%', L'&', L'\'', L'(',
L')', L'*', L'+', L',', L'-', L'.', L'/', L':', L';',
L'<', L'=', L'>', L'?', L'@', L'[', L'\\', L']', L'^',
L'_', L'`', L'{', L'|', L'}', L'~'
};
| 850
|
C++
|
.h
| 20
| 40.75
| 60
| 0.348247
|
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,996
|
objdump.cpp
|
RPCS3_rpcs3/objdump.cpp
|
// objdump injection utility for Linux perf tools.
// Profiling JIT generated code is always problematic.
// On Linux, perf annotation tools do not automatically
// disassemble runtime-generated code.
// However, it's possible to override objdump utility
// which is used to disassemeble executables.
// This tool intercepts objdump commands, and if they
// correspond to JIT generated objects in RPCS3,
// it should be able to correctly disassemble them.
// Usage:
// 1. Make sure ~/.cache/rpcs3/ASMJIT directory exists.
// 2. Build this utility, for example:
// g++-11 objdump.cpp -o objdump
// 3. Run perf, for example:
// perf record -b -p `pgrep rpcs3`
// 4. Specify --objdump override, for example:
// perf report --objdump=./objdump --gtk
#include <cstring>
#include <cstdio>
#include <cstdint>
#include <unistd.h>
#include <sys/file.h>
#include <sys/mman.h>
#include <string>
#include <vector>
#include <charconv>
std::string to_hex(std::uint64_t value, bool prfx = true)
{
char buf[20]{}, *ptr = buf + 19;
do *--ptr = "0123456789abcdef"[value % 16], value /= 16; while (value);
if (!prfx) return ptr;
*--ptr = 'x';
*--ptr = '0';
return ptr;
}
int main(int argc, char* argv[])
{
std::string home;
if (const char* d = ::getenv("XDG_CACHE_HOME"))
home = d;
else if (const char* d = ::getenv("XDG_CONFIG_HOME"))
home = d;
else if (const char* d = ::getenv("HOME"))
home = d, home += "/.cache";
// Get cache path
home += "/rpcs3/ASMJIT/";
// Get objects
int fd = open((home + ".objects").c_str(), O_RDONLY);
if (fd < 0)
return 1;
// Map 4GiB (full size)
const auto data = mmap(nullptr, 0x10000'0000, PROT_READ, MAP_SHARED, fd, 0);
struct entry
{
std::uint64_t addr;
std::uint32_t size;
std::uint32_t off;
};
// Index part (precedes actual data)
const auto index = static_cast<const entry*>(data);
const entry* found = nullptr;
std::string out_file;
std::vector<std::string> args;
for (int i = 0; i < argc; i++)
{
// Replace args
std::string arg = argv[i];
if (std::uintptr_t(data) != -1 && arg.find("--start-address=0x") == 0)
{
// Decode address and try to find the object
std::uint64_t addr = -1;
std::from_chars(arg.data() + strlen("--start-address=0x"), arg.data() + arg.size(), addr, 16);
for (int j = 0; j < 0x100'0000; j++)
{
if (index[j].addr == 0)
{
break;
}
if (index[j].addr == addr)
{
found = index + j;
break;
}
}
if (found)
{
// Extract object into a new file (read file name from the mapped memory)
const char* name = static_cast<char*>(data) + found->off + found->size;
if (name[0])
{
out_file = home + name;
}
else
{
out_file = "/tmp/rpcs3.objdump." + std::to_string(getpid());
unlink(out_file.c_str());
}
const int fd2 = open(out_file.c_str(), O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if (fd2 > 0)
{
// Don't overwrite if exists
write(fd2, static_cast<char*>(data) + found->off, found->size);
close(fd2);
}
args.emplace_back("--adjust-vma=" + to_hex(addr));
continue;
}
}
if (found && arg.find("--stop-address=0x") == 0)
{
continue;
}
if (found && arg == "-d")
{
arg = "-D";
}
if (arg == "-l")
{
arg = "-Mintel,x86-64";
}
args.emplace_back(std::move(arg));
}
if (found)
{
args.pop_back();
args.emplace_back("-b");
args.emplace_back("binary");
args.emplace_back("-m");
args.emplace_back("i386:x86-64");
args.emplace_back(std::move(out_file));
}
args[0] = "/usr/bin/objdump";
std::vector<char*> new_argv;
for (auto& arg : args)
{
new_argv.push_back(arg.data());
}
new_argv.push_back(nullptr);
if (found)
{
int fds[2];
pipe(fds);
if (fork() > 0)
{
close(fds[1]);
char c = 0;
std::string buf;
while (read(fds[0], &c, 1) != 0)
{
if (c)
{
buf += c;
if (c == '\n')
{
write(STDOUT_FILENO, buf.data(), buf.size());
buf.clear();
}
}
c = 0;
}
return 0;
}
else
{
while ((dup2(fds[1], STDOUT_FILENO) == -1) && (errno == EINTR)) {}
close(fds[1]);
close(fds[0]);
// Fallthrough
}
}
return execv(new_argv[0], new_argv.data());
}
| 4,268
|
C++
|
.cpp
| 172
| 21.511628
| 111
| 0.609317
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
4,997
|
stb_image.cpp
|
RPCS3_rpcs3/rpcs3/stb_image.cpp
|
#include "stdafx.h"
// Defines STB_IMAGE_IMPLEMENTATION *once* for stb_image.h includes (Should this be placed somewhere else?)
#define STB_IMAGE_IMPLEMENTATION
// Sneak in truetype as well.
#define STB_TRUETYPE_IMPLEMENTATION
// This header generates lots of errors, so we ignore those (not rpcs3 code)
#ifdef _MSC_VER
#pragma warning(push, 0)
#include <stb_image.h>
#include <stb_truetype.h>
#pragma warning(pop)
#else
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wall"
#pragma GCC diagnostic ignored "-Wextra"
#pragma GCC diagnostic ignored "-Wold-style-cast"
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#pragma GCC diagnostic ignored "-Wcast-qual"
#pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
#ifndef __clang__
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#pragma GCC diagnostic ignored "-Wduplicated-branches"
#endif
#pragma GCC diagnostic ignored "-Wsign-compare"
#include <stb_image.h>
#include <stb_truetype.h>
#pragma GCC diagnostic pop
#endif
| 1,003
|
C++
|
.cpp
| 28
| 34.75
| 107
| 0.795478
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
4,998
|
main_application.cpp
|
RPCS3_rpcs3/rpcs3/main_application.cpp
|
#include "stdafx.h"
#include "main_application.h"
#include "display_sleep_control.h"
#include "util/types.hpp"
#include "util/logs.hpp"
#include "util/sysinfo.hpp"
#include "Utilities/Thread.h"
#include "Utilities/File.h"
#include "Input/pad_thread.h"
#include "Emu/System.h"
#include "Emu/system_config.h"
#include "Emu/system_utils.hpp"
#include "Emu/IdManager.h"
#include "Emu/Io/Null/NullKeyboardHandler.h"
#include "Emu/Io/Null/NullMouseHandler.h"
#include "Emu/Io/KeyboardHandler.h"
#include "Emu/Io/MouseHandler.h"
#include "Input/basic_keyboard_handler.h"
#include "Input/basic_mouse_handler.h"
#include "Input/raw_mouse_handler.h"
#include "Emu/Audio/AudioBackend.h"
#include "Emu/Audio/Null/NullAudioBackend.h"
#include "Emu/Audio/Null/null_enumerator.h"
#include "Emu/Audio/Cubeb/CubebBackend.h"
#include "Emu/Audio/Cubeb/cubeb_enumerator.h"
#ifdef _WIN32
#include "Emu/Audio/XAudio2/XAudio2Backend.h"
#include "Emu/Audio/XAudio2/xaudio2_enumerator.h"
#endif
#ifdef HAVE_FAUDIO
#include "Emu/Audio/FAudio/FAudioBackend.h"
#include "Emu/Audio/FAudio/faudio_enumerator.h"
#endif
#include <QFileInfo> // This shouldn't be outside rpcs3qt...
#include <QImageReader> // This shouldn't be outside rpcs3qt...
#include <QStandardPaths> // This shouldn't be outside rpcs3qt...
#include <thread>
LOG_CHANNEL(sys_log, "SYS");
namespace audio
{
extern void configure_audio(bool force_reset = false);
extern void configure_rsxaudio();
}
namespace rsx::overlays
{
extern void reset_performance_overlay();
extern void reset_debug_overlay();
}
/** Emu.Init() wrapper for user management */
void main_application::InitializeEmulator(const std::string& user, bool show_gui)
{
Emu.SetHasGui(show_gui);
Emu.SetUsr(user);
Emu.Init();
// Log Firmware Version after Emu was initialized
const std::string firmware_version = utils::get_firmware_version();
const std::string firmware_string = firmware_version.empty() ? "Missing Firmware" : ("Firmware version: " + firmware_version);
sys_log.always()("%s", firmware_string);
}
void main_application::OnEmuSettingsChange()
{
if (Emu.IsRunning())
{
if (g_cfg.misc.prevent_display_sleep)
{
disable_display_sleep();
}
else
{
enable_display_sleep();
}
}
if (!Emu.IsStopped())
{
// Change logging (only allowed during gameplay)
rpcs3::utils::configure_logs();
// Force audio provider
g_cfg.audio.provider.set(Emu.IsVsh() ? audio_provider::rsxaudio : audio_provider::cell_audio);
}
audio::configure_audio();
audio::configure_rsxaudio();
rsx::overlays::reset_performance_overlay();
rsx::overlays::reset_debug_overlay();
}
/** RPCS3 emulator has functions it desires to call from the GUI at times. Initialize them in here. */
EmuCallbacks main_application::CreateCallbacks()
{
EmuCallbacks callbacks{};
callbacks.update_emu_settings = [this]()
{
Emu.CallFromMainThread([&]()
{
OnEmuSettingsChange();
});
};
callbacks.save_emu_settings = [this]()
{
Emu.BlockingCallFromMainThread([&]()
{
Emulator::SaveSettings(g_cfg.to_string(), Emu.GetTitleID());
});
};
callbacks.init_kb_handler = [this]()
{
switch (g_cfg.io.keyboard.get())
{
case keyboard_handler::null:
{
g_fxo->init<KeyboardHandlerBase, NullKeyboardHandler>(Emu.DeserialManager());
break;
}
case keyboard_handler::basic:
{
basic_keyboard_handler* ret = g_fxo->init<KeyboardHandlerBase, basic_keyboard_handler>(Emu.DeserialManager());
ensure(ret);
ret->moveToThread(get_thread());
ret->SetTargetWindow(m_game_window);
break;
}
}
};
callbacks.init_mouse_handler = [this]()
{
mouse_handler handler = g_cfg.io.mouse;
if (handler == mouse_handler::null)
{
switch (g_cfg.io.move)
{
case move_handler::mouse:
handler = mouse_handler::basic;
break;
case move_handler::raw_mouse:
handler = mouse_handler::raw;
break;
default:
break;
}
}
switch (handler)
{
case mouse_handler::null:
{
g_fxo->init<MouseHandlerBase, NullMouseHandler>(Emu.DeserialManager());
break;
}
case mouse_handler::basic:
{
basic_mouse_handler* ret = g_fxo->init<MouseHandlerBase, basic_mouse_handler>(Emu.DeserialManager());
ensure(ret);
ret->moveToThread(get_thread());
ret->SetTargetWindow(m_game_window);
break;
}
case mouse_handler::raw:
{
g_fxo->init<MouseHandlerBase, raw_mouse_handler>(Emu.DeserialManager());
break;
}
}
};
callbacks.init_pad_handler = [this](std::string_view title_id)
{
ensure(g_fxo->init<named_thread<pad_thread>>(get_thread(), m_game_window, title_id));
extern void process_qt_events();
while (!pad::g_started) process_qt_events();
};
callbacks.get_audio = []() -> std::shared_ptr<AudioBackend>
{
std::shared_ptr<AudioBackend> result;
switch (g_cfg.audio.renderer.get())
{
case audio_renderer::null: result = std::make_shared<NullAudioBackend>(); break;
#ifdef _WIN32
case audio_renderer::xaudio: result = std::make_shared<XAudio2Backend>(); break;
#endif
case audio_renderer::cubeb: result = std::make_shared<CubebBackend>(); break;
#ifdef HAVE_FAUDIO
case audio_renderer::faudio: result = std::make_shared<FAudioBackend>(); break;
#endif
}
if (!result->Initialized())
{
// Fall back to a null backend if something went wrong
sys_log.error("Audio renderer %s could not be initialized, using a Null renderer instead. Make sure that no other application is running that might block audio access (e.g. Netflix).", result->GetName());
result = std::make_shared<NullAudioBackend>();
}
return result;
};
callbacks.get_audio_enumerator = [](u64 renderer) -> std::shared_ptr<audio_device_enumerator>
{
switch (static_cast<audio_renderer>(renderer))
{
case audio_renderer::null: return std::make_shared<null_enumerator>();
#ifdef _WIN32
case audio_renderer::xaudio: return std::make_shared<xaudio2_enumerator>();
#endif
case audio_renderer::cubeb: return std::make_shared<cubeb_enumerator>();
#ifdef HAVE_FAUDIO
case audio_renderer::faudio: return std::make_shared<faudio_enumerator>();
#endif
default: fmt::throw_exception("Invalid renderer index %u", renderer);
}
};
callbacks.get_image_info = [](const std::string& filename, std::string& sub_type, s32& width, s32& height, s32& orientation) -> bool
{
sub_type.clear();
width = 0;
height = 0;
orientation = 0; // CELL_SEARCH_ORIENTATION_UNKNOWN
bool success = false;
Emu.BlockingCallFromMainThread([&]()
{
const QImageReader reader(QString::fromStdString(filename));
if (reader.canRead())
{
const QSize size = reader.size();
width = size.width();
height = size.height();
sub_type = reader.subType().toStdString();
switch (reader.transformation())
{
case QImageIOHandler::Transformation::TransformationNone:
orientation = 1; // CELL_SEARCH_ORIENTATION_TOP_LEFT = 0째
break;
case QImageIOHandler::Transformation::TransformationRotate90:
orientation = 2; // CELL_SEARCH_ORIENTATION_TOP_RIGHT = 90째
break;
case QImageIOHandler::Transformation::TransformationRotate180:
orientation = 3; // CELL_SEARCH_ORIENTATION_BOTTOM_RIGHT = 180째
break;
case QImageIOHandler::Transformation::TransformationRotate270:
orientation = 4; // CELL_SEARCH_ORIENTATION_BOTTOM_LEFT = 270째
break;
default:
// Ignore other transformations for now
break;
}
success = true;
sys_log.notice("get_image_info found image: filename='%s', sub_type='%s', width=%d, height=%d, orientation=%d", filename, sub_type, width, height, orientation);
}
else
{
sys_log.error("get_image_info failed to read '%s'. Error='%s'", filename, reader.errorString());
}
});
return success;
};
callbacks.get_scaled_image = [](const std::string& path, s32 target_width, s32 target_height, s32& width, s32& height, u8* dst, bool force_fit) -> bool
{
width = 0;
height = 0;
if (target_width <= 0 || target_height <= 0 || !dst || !fs::is_file(path))
{
return false;
}
bool success = false;
Emu.BlockingCallFromMainThread([&]()
{
// We use QImageReader instead of QImage. This way we can load and scale image in one step.
QImageReader reader(QString::fromStdString(path));
if (reader.canRead())
{
QSize size = reader.size();
width = size.width();
height = size.height();
if (width <= 0 || height <= 0)
{
return;
}
if (force_fit || width > target_width || height > target_height)
{
const f32 target_ratio = target_width / static_cast<f32>(target_height);
const f32 image_ratio = width / static_cast<f32>(height);
const f32 convert_ratio = image_ratio / target_ratio;
if (convert_ratio > 1.0f)
{
size = QSize(target_width, target_height / convert_ratio);
}
else if (convert_ratio < 1.0f)
{
size = QSize(target_width * convert_ratio, target_height);
}
else
{
size = QSize(target_width, target_height);
}
reader.setScaledSize(size);
width = size.width();
height = size.height();
}
QImage image = reader.read();
if (image.format() != QImage::Format::Format_RGBA8888)
{
image = image.convertToFormat(QImage::Format::Format_RGBA8888);
}
std::memcpy(dst, image.constBits(), std::min(target_width * target_height * 4LL, image.height() * image.bytesPerLine()));
success = true;
sys_log.notice("get_scaled_image scaled image: path='%s', width=%d, height=%d", path, width, height);
}
else
{
sys_log.error("get_scaled_image failed to read '%s'. Error='%s'", path, reader.errorString());
}
});
return success;
};
callbacks.resolve_path = [](std::string_view sv)
{
// May result in an empty string if path does not exist
return QFileInfo(QString::fromUtf8(sv.data(), static_cast<int>(sv.size()))).canonicalFilePath().toStdString();
};
callbacks.get_font_dirs = []()
{
const QStringList locations = QStandardPaths::standardLocations(QStandardPaths::FontsLocation);
std::vector<std::string> font_dirs;
for (const QString& location : locations)
{
std::string font_dir = location.toStdString();
if (!font_dir.ends_with('/'))
{
font_dir += '/';
}
font_dirs.push_back(font_dir);
}
return font_dirs;
};
callbacks.on_install_pkgs = [](const std::vector<std::string>& pkgs)
{
for (const std::string& pkg : pkgs)
{
if (!rpcs3::utils::install_pkg(pkg))
{
sys_log.error("Failed to install %s", pkg);
return false;
}
}
return true;
};
return callbacks;
}
| 10,547
|
C++
|
.cpp
| 340
| 27.761765
| 207
| 0.701476
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
4,999
|
main.cpp
|
RPCS3_rpcs3/rpcs3/main.cpp
|
// Qt6 frontend implementation for rpcs3. Known to work on Windows, Linux, Mac
// by Sacha Refshauge, Megamouse and flash-fire
#include <iostream>
#include <chrono>
#include <clocale>
#include <QApplication>
#include <QCommandLineParser>
#include <QFileInfo>
#include <QTimer>
#include <QObject>
#include <QStyleFactory>
#include <QByteArray>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QMessageBox>
#include <QMetaEnum>
#include <QStandardPaths>
#include "rpcs3qt/gui_application.h"
#include "rpcs3qt/fatal_error_dialog.h"
#include "rpcs3qt/curl_handle.h"
#include "rpcs3qt/main_window.h"
#include "rpcs3qt/uuid.h"
#include "headless_application.h"
#include "Utilities/sema.h"
#include "Utilities/date_time.h"
#include "util/console.h"
#include "Crypto/decrypt_binaries.h"
#ifdef _WIN32
#include "module_verifier.hpp"
#include "util/dyn_lib.hpp"
// TODO(cjj19970505@live.cn)
// When compiling with WIN32_LEAN_AND_MEAN definition
// NTSTATUS is defined in CMake build but not in VS build
// May be caused by some different header pre-inclusion between CMake and VS configurations.
#if !defined(NTSTATUS)
// Copied from ntdef.h
typedef _Return_type_success_(return >= 0) LONG NTSTATUS;
#endif
DYNAMIC_IMPORT("ntdll.dll", NtQueryTimerResolution, NTSTATUS(PULONG MinimumResolution, PULONG MaximumResolution, PULONG CurrentResolution));
DYNAMIC_IMPORT("ntdll.dll", NtSetTimerResolution, NTSTATUS(ULONG DesiredResolution, BOOLEAN SetResolution, PULONG CurrentResolution));
#else
#include <unistd.h>
#include <spawn.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <signal.h>
#endif
#ifdef __linux__
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/prctl.h>
#endif
#if defined(__APPLE__)
#include <dispatch/dispatch.h>
#if defined (__x86_64__)
// sysinfo_darwin.mm
namespace Darwin_Version
{
extern int getNSmajorVersion();
extern int getNSminorVersion();
extern int getNSpatchVersion();
}
#endif
#endif
#include "Utilities/Config.h"
#include "Utilities/Thread.h"
#include "Utilities/File.h"
#include "Utilities/StrUtil.h"
#include "util/media_utils.h"
#include "rpcs3_version.h"
#include "Emu/System.h"
#include "Emu/system_utils.hpp"
#include <thread>
#include <charconv>
#include "util/sysinfo.hpp"
// Let's initialize the locale first
static const bool s_init_locale = []()
{
std::setlocale(LC_ALL, "C");
return true;
}();
static semaphore<> s_qt_init;
static atomic_t<bool> s_headless = false;
static atomic_t<bool> s_no_gui = false;
static atomic_t<char*> s_argv0 = nullptr;
static bool s_is_error_launch = false;
std::string g_input_config_override;
extern thread_local std::string(*g_tls_log_prefix)();
extern thread_local std::string_view g_tls_serialize_name;
#ifndef _WIN32
extern char **environ;
#endif
LOG_CHANNEL(sys_log, "SYS");
LOG_CHANNEL(q_debug, "QDEBUG");
[[noreturn]] extern void report_fatal_error(std::string_view _text, bool is_html = false, bool include_help_text = true)
{
#ifdef __linux__
extern void jit_announce(uptr, usz, std::string_view);
#endif
std::string buf;
if (!s_is_error_launch)
{
buf = std::string(_text);
// Check if thread id is in string
if (_text.find("\nThread id = "sv) == umax && !thread_ctrl::is_main())
{
// Append thread id if it isn't already, except on main thread
fmt::append(buf, "\n\nThread id = %u.", thread_ctrl::get_tid());
}
if (!g_tls_serialize_name.empty())
{
fmt::append(buf, "\nSerialized Object: %s", g_tls_serialize_name);
}
const system_state state = Emu.GetStatus(false);
if (state == system_state::stopped)
{
fmt::append(buf, "\nEmulation is stopped");
}
else
{
const std::string& name = Emu.GetTitleAndTitleID();
fmt::append(buf, "\nTitle: \"%s\" (emulation is %s)", name.empty() ? "N/A" : name.data(), state == system_state::stopping ? "stopping" : "running");
}
fmt::append(buf, "\nBuild: \"%s\"", rpcs3::get_verbose_version());
fmt::append(buf, "\nDate: \"%s\"", std::chrono::system_clock::now());
}
std::string_view text = s_is_error_launch ? _text : buf;
if (s_headless)
{
utils::attach_console(utils::console_stream::std_err, true);
utils::output_stderr(fmt::format("RPCS3: %s\n", text));
#ifdef __linux__
jit_announce(0, 0, "");
#endif
std::abort();
}
const bool local = s_qt_init.try_lock();
// Possibly created and assigned here
static QScopedPointer<QCoreApplication> app;
if (local)
{
static int argc = 1;
static char* argv[] = {+s_argv0};
app.reset(new QApplication{argc, argv});
}
else
{
utils::output_stderr(fmt::format("RPCS3: %s\n", text));
}
static auto show_report = [is_html, include_help_text](std::string_view text)
{
fatal_error_dialog dlg(text, is_html, include_help_text);
dlg.exec();
};
#if defined(__APPLE__)
if (!pthread_main_np())
{
dispatch_sync_f(dispatch_get_main_queue(), &text, [](void* text){ show_report(*static_cast<std::string_view*>(text)); });
}
else
#endif
{
// If Qt is already initialized, spawn a new RPCS3 process with an --error argument
if (local)
{
show_report(text);
#ifdef _WIN32
ExitProcess(0);
#else
kill(getpid(), SIGKILL);
#endif
}
#ifdef _WIN32
constexpr DWORD size = 32767;
std::vector<wchar_t> buffer(size);
GetModuleFileNameW(nullptr, buffer.data(), size);
const std::wstring arg(text.cbegin(), text.cend()); // ignore unicode for now
_wspawnl(_P_WAIT, buffer.data(), buffer.data(), L"--error", arg.c_str(), nullptr);
#else
pid_t pid;
std::vector<char> data(text.data(), text.data() + text.size() + 1);
std::string run_arg = +s_argv0;
std::string err_arg = "--error";
if (run_arg.find_first_of('/') == umax)
{
// AppImage has "rpcs3" in argv[0], can't just execute it
#ifdef __linux__
char buffer[PATH_MAX]{};
if (::readlink("/proc/self/exe", buffer, sizeof(buffer) - 1) > 0)
{
printf("Found exec link: %s\n", buffer);
run_arg = buffer;
}
#endif
}
char* argv[] = {run_arg.data(), err_arg.data(), data.data(), nullptr};
int ret = posix_spawn(&pid, run_arg.c_str(), nullptr, nullptr, argv, environ);
if (ret == 0)
{
int status;
waitpid(pid, &status, 0);
}
else
{
std::fprintf(stderr, "posix_spawn() failed: %d\n", ret);
}
#endif
}
#ifdef __linux__
jit_announce(0, 0, "");
#endif
std::abort();
}
struct fatal_error_listener final : logs::listener
{
public:
~fatal_error_listener() override = default;
void log(u64 /*stamp*/, const logs::message& msg, const std::string& prefix, const std::string& text) override
{
if (msg == logs::level::fatal || (msg == logs::level::always && m_log_always))
{
std::string _msg = "RPCS3: ";
if (!prefix.empty())
{
_msg += prefix;
_msg += ": ";
}
if (msg->name && '\0' != *msg->name)
{
_msg += msg->name;
_msg += ": ";
}
_msg += text;
_msg += '\n';
// If launched from CMD
utils::attach_console(msg == logs::level::fatal ? utils::console_stream::std_err : utils::console_stream::std_out, false);
// Output to error stream as is
if (msg == logs::level::fatal)
{
utils::output_stderr(_msg);
}
else
{
std::cout << _msg;
}
#ifdef _WIN32
if (IsDebuggerPresent())
{
// Output string to attached debugger
OutputDebugStringA(_msg.c_str());
}
#endif
if (msg == logs::level::fatal)
{
// Pause emulation if fatal error encountered
Emu.Pause(true);
}
}
}
void log_always(bool enabled)
{
m_log_always = enabled;
}
private:
bool m_log_always = false;
};
// Arguments that force a headless application (need to be checked in create_application)
constexpr auto arg_headless = "headless";
constexpr auto arg_decrypt = "decrypt";
constexpr auto arg_commit_db = "get-commit-db";
// Arguments that can be used with a gui application
constexpr auto arg_no_gui = "no-gui";
constexpr auto arg_fullscreen = "fullscreen"; // only useful with no-gui
constexpr auto arg_gs_screen = "game-screen";
constexpr auto arg_high_dpi = "hidpi";
constexpr auto arg_rounding = "dpi-rounding";
constexpr auto arg_styles = "styles";
constexpr auto arg_style = "style";
constexpr auto arg_stylesheet = "stylesheet";
constexpr auto arg_config = "config";
constexpr auto arg_input_config = "input-config"; // only useful with no-gui
constexpr auto arg_q_debug = "qDebug";
constexpr auto arg_error = "error";
constexpr auto arg_updating = "updating";
constexpr auto arg_user_id = "user-id";
constexpr auto arg_installfw = "installfw";
constexpr auto arg_installpkg = "installpkg";
constexpr auto arg_savestate = "savestate";
constexpr auto arg_rsx_capture = "rsx-capture";
constexpr auto arg_timer = "high-res-timer";
constexpr auto arg_verbose_curl = "verbose-curl";
constexpr auto arg_any_location = "allow-any-location";
constexpr auto arg_codecs = "codecs";
#ifdef _WIN32
constexpr auto arg_stdout = "stdout";
constexpr auto arg_stderr = "stderr";
#endif
int find_arg(std::string arg, int& argc, char* argv[])
{
arg = "--" + arg;
for (int i = 0; i < argc; ++i) // It's not guaranteed that argv 0 is the executable.
if (!strcmp(arg.c_str(), argv[i]))
return i;
return -1;
}
QCoreApplication* create_application(int& argc, char* argv[])
{
if (find_arg(arg_headless, argc, argv) != -1 ||
find_arg(arg_decrypt, argc, argv) != -1 ||
find_arg(arg_commit_db, argc, argv) != -1)
{
return new headless_application(argc, argv);
}
#ifdef __linux__
// set the DISPLAY variable in order to open web browsers
if (qEnvironmentVariable("DISPLAY", "").isEmpty())
{
qputenv("DISPLAY", ":0");
}
// Set QT_AUTO_SCREEN_SCALE_FACTOR to 0. This value is deprecated but still seems to make problems on some distros
if (!qEnvironmentVariable("QT_AUTO_SCREEN_SCALE_FACTOR", "").isEmpty())
{
qputenv("QT_AUTO_SCREEN_SCALE_FACTOR", "0");
}
#endif
bool use_high_dpi = true;
const int i_hdpi = find_arg(arg_high_dpi, argc, argv);
if (i_hdpi != -1)
{
const std::string cmp_str = "0";
const auto i_hdpi_2 = (argc > (i_hdpi + 1)) ? (i_hdpi + 1) : 0;
const auto high_dpi_setting = (i_hdpi_2 && !strcmp(cmp_str.c_str(), argv[i_hdpi_2])) ? "0" : "1";
// Set QT_ENABLE_HIGHDPI_SCALING from environment. Defaults to cli argument, which defaults to 1.
use_high_dpi = "1" == qEnvironmentVariable("QT_ENABLE_HIGHDPI_SCALING", high_dpi_setting);
}
if (use_high_dpi)
{
// Set QT_SCALE_FACTOR_ROUNDING_POLICY from environment. Defaults to cli argument, which defaults to PassThrough.
Qt::HighDpiScaleFactorRoundingPolicy rounding_val = Qt::HighDpiScaleFactorRoundingPolicy::PassThrough;
const QMetaEnum meta_enum = QMetaEnum::fromType<Qt::HighDpiScaleFactorRoundingPolicy>();
QString rounding_str_cli = meta_enum.valueToKey(static_cast<int>(rounding_val));
const auto check_dpi_rounding_arg = [&rounding_str_cli, &rounding_val, &meta_enum](const char* val) -> bool
{
// Try to find out if the argument is a valid string representation of Qt::HighDpiScaleFactorRoundingPolicy
bool ok{false};
if (const int enum_index = meta_enum.keyToValue(val, &ok); ok)
{
rounding_str_cli = meta_enum.valueToKey(enum_index);
rounding_val = static_cast<Qt::HighDpiScaleFactorRoundingPolicy>(enum_index);
}
return ok;
};
if (const int i_rounding = find_arg(arg_rounding, argc, argv); i_rounding != -1)
{
if (const int i_rounding_2 = i_rounding + 1; argc > i_rounding_2)
{
if (const auto arg_val = argv[i_rounding_2]; !check_dpi_rounding_arg(arg_val))
{
const std::string msg = fmt::format("The command line value %s for %s is not allowed. Please use a valid value for Qt::HighDpiScaleFactorRoundingPolicy.", arg_val, arg_rounding);
sys_log.error("%s", msg); // Don't exit with fatal error. The resulting dialog might be unreadable with dpi problems.
utils::output_stderr(msg, true);
}
}
}
// Get the environment variable. Fallback to cli argument.
rounding_str_cli = qEnvironmentVariable("QT_SCALE_FACTOR_ROUNDING_POLICY", rounding_str_cli);
if (!check_dpi_rounding_arg(rounding_str_cli.toStdString().c_str()))
{
const std::string msg = fmt::format("The value %s for the environment variable QT_SCALE_FACTOR_ROUNDING_POLICY is not allowed. Please use a valid value for Qt::HighDpiScaleFactorRoundingPolicy.", rounding_str_cli.toStdString());
sys_log.error("%s", msg); // Don't exit with fatal error. The resulting dialog might be unreadable with dpi problems.
std::cerr << msg << std::endl;
}
QApplication::setHighDpiScaleFactorRoundingPolicy(rounding_val);
}
return new gui_application(argc, argv);
}
template <>
void fmt_class_string<QString>::format(std::string& out, u64 arg)
{
out += get_object(arg).toStdString();
}
void log_q_debug(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
Q_UNUSED(context)
switch (type)
{
case QtDebugMsg: q_debug.trace("%s", msg); break;
case QtInfoMsg: q_debug.notice("%s", msg); break;
case QtWarningMsg: q_debug.warning("%s", msg); break;
case QtCriticalMsg: q_debug.error("%s", msg); break;
case QtFatalMsg: q_debug.fatal("%s", msg); break;
}
}
template <>
void fmt_class_string<std::chrono::sys_time<typename std::chrono::system_clock::duration>>::format(std::string& out, u64 arg)
{
const std::time_t dateTime = std::chrono::system_clock::to_time_t(get_object(arg));
out += date_time::fmt_time("%Y-%m-%dT%H:%M:%S", dateTime);
}
void run_platform_sanity_checks()
{
#ifdef _WIN32
// Check if we loaded modules correctly
WIN32_module_verifier::run();
#endif
}
int main(int argc, char** argv)
{
#ifdef _WIN32
ULONG64 intro_cycles{};
QueryThreadCycleTime(GetCurrentThread(), &intro_cycles);
#elif defined(RUSAGE_THREAD)
struct ::rusage intro_stats{};
::getrusage(RUSAGE_THREAD, &intro_stats);
const u64 intro_time = (intro_stats.ru_utime.tv_sec + intro_stats.ru_stime.tv_sec) * 1000000000ull + (intro_stats.ru_utime.tv_usec + intro_stats.ru_stime.tv_usec) * 1000ull;
#endif
#ifdef __linux__
// Set timerslack value for Linux. The default value is 50,000ns. Change this to just 1 since we value precise timers.
prctl(PR_SET_TIMERSLACK, 1, 0, 0, 0);
#endif
s_argv0 = argv[0]; // Save for report_fatal_error
// Only run RPCS3 to display an error
if (int err_pos = find_arg(arg_error, argc, argv); err_pos != -1)
{
// Reconstruction of the error from multiple args
std::string error;
for (int i = err_pos + 1; i < argc; i++)
{
if (i > err_pos + 1)
error += ' ';
error += argv[i];
}
s_is_error_launch = true;
report_fatal_error(error);
}
const std::string lock_name = fs::get_cache_dir() + "RPCS3.buf";
const std::string log_name = fs::get_cache_dir() + "RPCS3.log";
static fs::file instance_lock;
// True if an argument --updating found
const bool is_updating = find_arg(arg_updating, argc, argv) != -1;
// Keep trying to lock the file for ~2s normally, and for ~10s in the case of --updating
for (u32 num = 0; num < (is_updating ? 500u : 100u) && !instance_lock.open(lock_name, fs::rewrite + fs::lock); num++)
{
std::this_thread::sleep_for(20ms);
}
if (!instance_lock)
{
if (fs::g_tls_error == fs::error::acces)
{
if (fs::exists(lock_name))
{
report_fatal_error(fmt::format("Another instance of RPCS3 is running.\nClose it or kill its process, if necessary.\n'%s' still exists.", lock_name));
}
report_fatal_error(fmt::format("Cannot create '%s' or '%s' (access denied).\n"
#ifdef _WIN32
"Note that RPCS3 cannot be installed in Program Files or similar directories with limited permissions."
#else
"Please, check RPCS3 permissions."
#endif
, log_name, lock_name));
}
report_fatal_error(fmt::format("Cannot create'%s' or '%s' (error=%s)", log_name, lock_name, fs::g_tls_error));
}
#ifdef _WIN32
if (!SetProcessWorkingSetSize(GetCurrentProcess(), 0x80000000, 0xC0000000)) // 2-3 GiB
{
report_fatal_error("Not enough memory for RPCS3 process.");
}
WSADATA wsa_data{};
if (const int res = WSAStartup(MAKEWORD(2, 2), &wsa_data); res != 0)
{
report_fatal_error(fmt::format("WSAStartup failed (error=%s)", fmt::win_error{static_cast<unsigned long>(res), nullptr}));
}
#endif
#if defined(__APPLE__) && defined(__x86_64__)
const int osx_ver_major = Darwin_Version::getNSmajorVersion();
const int osx_ver_minor = Darwin_Version::getNSminorVersion();
if ((osx_ver_major == 14 && osx_ver_minor < 3) && (utils::get_cpu_brand().rfind("VirtualApple", 0) == 0))
{
const int osx_ver_patch = Darwin_Version::getNSpatchVersion();
report_fatal_error(fmt::format("RPCS3 requires macOS 14.3.0 or later.\nYou're currently using macOS %i.%i.%i.\nPlease update macOS from System Settings.\n\n", osx_ver_major, osx_ver_minor, osx_ver_patch));
}
#endif
ensure(thread_ctrl::is_main(), "Not main thread");
// Initialize thread pool finalizer (on first use)
static_cast<void>(named_thread("", [](int) {}));
static std::unique_ptr<logs::listener> log_file;
{
// Check free space
fs::device_stat stats{};
if (!fs::statfs(fs::get_cache_dir(), stats) || stats.avail_free < 128 * 1024 * 1024)
{
std::fprintf(stderr, "Not enough free space for logs (%f KB)", stats.avail_free / 1000000.);
}
// Limit log size to ~25% of free space
log_file = logs::make_file_listener(log_name, stats.avail_free / 4);
}
static std::unique_ptr<fatal_error_listener> fatal_listener = std::make_unique<fatal_error_listener>();
logs::listener::add(fatal_listener.get());
{
// Write RPCS3 version
logs::stored_message ver{sys_log.always()};
ver.text = fmt::format("RPCS3 v%s", rpcs3::get_verbose_version());
// Write System information
logs::stored_message sys{sys_log.always()};
sys.text = utils::get_system_info();
// Write OS version
logs::stored_message os{sys_log.always()};
os.text = utils::get_OS_version();
// Write Qt version
logs::stored_message qt{(strcmp(QT_VERSION_STR, qVersion()) != 0) ? sys_log.error : sys_log.notice};
qt.text = fmt::format("Qt version: Compiled against Qt %s | Run-time uses Qt %s", QT_VERSION_STR, qVersion());
logs::stored_message time{sys_log.always()};
time.text = fmt::format("Current Time: %s", std::chrono::system_clock::now());
logs::set_init({std::move(ver), std::move(sys), std::move(os), std::move(qt), std::move(time)});
}
#ifdef _WIN32
sys_log.notice("Initialization times before main(): %fGc", intro_cycles / 1000000000.);
#elif defined(RUSAGE_THREAD)
sys_log.notice("Initialization times before main(): %fs", intro_time / 1000000000.);
#endif
std::string argument_str;
for (int i = 0; i < argc; i++)
{
argument_str += '\'' + std::string(argv[i]) + '\'';
if (i != argc - 1) argument_str += " ";
}
sys_log.notice("argc: %d, argv: %s", argc, argument_str);
// Before we proceed, run some sanity checks
run_platform_sanity_checks();
#ifdef __linux__
struct ::rlimit rlim;
rlim.rlim_cur = 4096;
rlim.rlim_max = 4096;
#ifdef RLIMIT_NOFILE
if (::setrlimit(RLIMIT_NOFILE, &rlim) != 0)
{
std::cerr << "Failed to set max open file limit (4096).\n";
}
#endif
rlim.rlim_cur = 0x80000000;
rlim.rlim_max = 0x80000000;
#ifdef RLIMIT_MEMLOCK
if (::setrlimit(RLIMIT_MEMLOCK, &rlim) != 0)
{
std::cerr << "Failed to set RLIMIT_MEMLOCK size to 2 GiB. Try to update your system configuration.\n";
}
#endif
// Work around crash on startup on KDE: https://bugs.kde.org/show_bug.cgi?id=401637
setenv( "KDE_DEBUG", "1", 0 );
#endif
#ifdef __APPLE__
struct ::rlimit rlim;
::getrlimit(RLIMIT_NOFILE, &rlim);
rlim.rlim_cur = OPEN_MAX;
if (::setrlimit(RLIMIT_NOFILE, &rlim) != 0)
{
std::cerr << "Failed to set max open file limit (" << OPEN_MAX << ").\n";
}
#endif
#ifndef _WIN32
// Write file limits
sys_log.notice("Maximum open file descriptors: %i", utils::get_maxfiles());
#endif
if (utils::get_low_power_mode())
{
sys_log.error("Low Power Mode is enabled, performance may be reduced.");
}
std::lock_guard qt_init(s_qt_init);
// The constructor of QApplication eats the --style and --stylesheet arguments.
// By checking for stylesheet().isEmpty() we could implicitly know if a stylesheet was passed,
// but I haven't found an implicit way to check for style yet, so we naively check them both here for now.
const bool use_cli_style = find_arg(arg_style, argc, argv) != -1 || find_arg(arg_stylesheet, argc, argv) != -1;
QScopedPointer<QCoreApplication> app(create_application(argc, argv));
app->setApplicationVersion(QString::fromStdString(rpcs3::get_version().to_string()));
app->setApplicationName("RPCS3");
app->setOrganizationName("RPCS3");
// Command line args
static QCommandLineParser parser;
parser.setApplicationDescription("Welcome to RPCS3 command line.");
parser.addPositionalArgument("(S)ELF", "Path for directly executing a (S)ELF");
parser.addPositionalArgument("[Args...]", "Optional args for the executable");
const QCommandLineOption help_option = parser.addHelpOption();
const QCommandLineOption version_option = parser.addVersionOption();
parser.addOption(QCommandLineOption(arg_headless, "Run RPCS3 in headless mode."));
parser.addOption(QCommandLineOption(arg_no_gui, "Run RPCS3 without its GUI."));
parser.addOption(QCommandLineOption(arg_fullscreen, "Run games in fullscreen mode. Only used when no-gui is set."));
const QCommandLineOption screen_option(arg_gs_screen, "Forces the emulator to use the specified screen for the game window.", "index", "");
parser.addOption(screen_option);
parser.addOption(QCommandLineOption(arg_high_dpi, "Enables Qt High Dpi Scaling.", "enabled", "1"));
parser.addOption(QCommandLineOption(arg_rounding, "Sets the Qt::HighDpiScaleFactorRoundingPolicy for values like 150% zoom.", "rounding", "4"));
parser.addOption(QCommandLineOption(arg_styles, "Lists the available styles."));
parser.addOption(QCommandLineOption(arg_style, "Loads a custom style.", "style", ""));
parser.addOption(QCommandLineOption(arg_stylesheet, "Loads a custom stylesheet.", "path", ""));
const QCommandLineOption config_option(arg_config, "Forces the emulator to use this configuration file for CLI-booted game.", "path", "");
parser.addOption(config_option);
const QCommandLineOption input_config_option(arg_input_config, "Forces the emulator to use this input config file for CLI-booted game.", "name", "");
parser.addOption(input_config_option);
const QCommandLineOption installfw_option(arg_installfw, "Forces the emulator to install this firmware file.", "path", "");
parser.addOption(installfw_option);
const QCommandLineOption installpkg_option(arg_installpkg, "Forces the emulator to install this pkg file.", "path", "");
parser.addOption(installpkg_option);
const QCommandLineOption decrypt_option(arg_decrypt, "Decrypt PS3 binaries.", "path(s)", "");
parser.addOption(decrypt_option);
const QCommandLineOption user_id_option(arg_user_id, "Start RPCS3 as this user.", "user id", "");
parser.addOption(user_id_option);
const QCommandLineOption savestate_option(arg_savestate, "Path for directly loading a savestate.", "path", "");
parser.addOption(savestate_option);
const QCommandLineOption rsx_capture_option(arg_rsx_capture, "Path for directly loading an rsx capture.", "path", "");
parser.addOption(rsx_capture_option);
parser.addOption(QCommandLineOption(arg_q_debug, "Log qDebug to RPCS3.log."));
parser.addOption(QCommandLineOption(arg_error, "For internal usage."));
parser.addOption(QCommandLineOption(arg_updating, "For internal usage."));
parser.addOption(QCommandLineOption(arg_commit_db, "Update commits.lst cache. Optional arguments: <path> <sha>"));
parser.addOption(QCommandLineOption(arg_timer, "Enable high resolution timer for better performance (windows)", "enabled", "1"));
parser.addOption(QCommandLineOption(arg_verbose_curl, "Enable verbose curl logging."));
parser.addOption(QCommandLineOption(arg_any_location, "Allow RPCS3 to be run from any location. Dangerous"));
const QCommandLineOption codec_option(arg_codecs, "List ffmpeg codecs");
parser.addOption(codec_option);
#ifdef _WIN32
parser.addOption(QCommandLineOption(arg_stdout, "Attach the console window and listen to standard output stream. (STDOUT)"));
parser.addOption(QCommandLineOption(arg_stderr, "Attach the console window and listen to error output stream. (STDERR)"));
#endif
parser.process(app->arguments());
// Don't start up the full rpcs3 gui if we just want the version or help.
if (parser.isSet(version_option) || parser.isSet(help_option))
return 0;
if (parser.isSet(codec_option))
{
utils::attach_console(utils::console_stream::std_out | utils::console_stream::std_err, true);
for (const utils::ffmpeg_codec& codec : utils::list_ffmpeg_decoders())
{
fprintf(stdout, "Found ffmpeg decoder: %s (%d, %s)\n", codec.name.c_str(), codec.codec_id, codec.long_name.c_str());
sys_log.success("Found ffmpeg decoder: %s (%d, %s)", codec.name, codec.codec_id, codec.long_name);
}
for (const utils::ffmpeg_codec& codec : utils::list_ffmpeg_encoders())
{
fprintf(stdout, "Found ffmpeg encoder: %s (%d, %s)\n", codec.name.c_str(), codec.codec_id, codec.long_name.c_str());
sys_log.success("Found ffmpeg encoder: %s (%d, %s)", codec.name, codec.codec_id, codec.long_name);
}
return 0;
}
#ifdef _WIN32
if (parser.isSet(arg_stdout) || parser.isSet(arg_stderr))
{
int stream = 0;
if (parser.isSet(arg_stdout))
{
stream |= utils::console_stream::std_out;
}
if (parser.isSet(arg_stderr))
{
stream |= utils::console_stream::std_err;
}
utils::attach_console(stream, true);
}
#endif
// Set curl to verbose if needed
rpcs3::curl::g_curl_verbose = parser.isSet(arg_verbose_curl);
if (rpcs3::curl::g_curl_verbose)
{
utils::attach_console(utils::console_stream::std_out | utils::console_stream::std_err, true);
fprintf(stdout, "Enabled Curl verbose logging.\n");
sys_log.always()("Enabled Curl verbose logging. Please look at your console output.");
}
// Handle update of commit database
if (parser.isSet(arg_commit_db))
{
utils::attach_console(utils::console_stream::std_out | utils::console_stream::std_err, true);
#ifdef _WIN32
std::string path;
#else
std::string path = "bin/git/commits.lst";
#endif
std::string from_sha;
if (const int i_arg_commit_db = find_arg(arg_commit_db, argc, argv); i_arg_commit_db != -1)
{
if (int i = i_arg_commit_db + 1; argc > i)
{
path = argv[i++];
if (argc > i)
{
from_sha = argv[i];
}
}
#ifdef _WIN32
else
{
fprintf(stderr, "Missing path argument.\n");
return 1;
}
#endif
}
else
{
fprintf(stderr, "Can not find argument --%s\n", arg_commit_db);
return 1;
}
fs::file file(path, fs::read + fs::write + fs::append + fs::create);
if (!file)
{
fprintf(stderr, "Failed to open file: '%s' (errno=%d)\n", path.c_str(), errno);
return 1;
}
fprintf(stdout, "\nAppending commits to '%s' ...\n", path.c_str());
// Get existing list
std::string data = file.to_string();
std::vector<std::string> list = fmt::split(data, {"\n"});
const bool was_empty = data.empty();
// SHA to start
std::string last;
if (!list.empty())
{
// Decode last entry to check last written commit
QByteArray buf(list.back().c_str(), list.back().size());
QJsonDocument doc = QJsonDocument::fromJson(buf);
if (doc.isObject() && doc["sha"].isString())
{
last = doc["sha"].toString().toStdString();
}
}
list.clear();
// JSON buffer
QByteArray buf;
// CURL handle to work with GitHub API
rpcs3::curl::curl_handle curl;
struct curl_slist* hhdr{};
hhdr = curl_slist_append(hhdr, "Accept: application/vnd.github.v3+json");
hhdr = curl_slist_append(hhdr, "User-Agent: curl/7.37.0");
CURLcode err = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, hhdr);
if (err != CURLE_OK) fprintf(stderr, "curl_easy_setopt(CURLOPT_HTTPHEADER) error: %s", curl_easy_strerror(err));
err = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, +[](const char* ptr, usz, usz size, void* json) -> usz
{
static_cast<QByteArray*>(json)->append(ptr, size);
return size;
});
if (err != CURLE_OK) fprintf(stderr, "curl_easy_setopt(CURLOPT_WRITEFUNCTION) error: %s", curl_easy_strerror(err));
err = curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buf);
if (err != CURLE_OK) fprintf(stderr, "curl_easy_setopt(CURLOPT_WRITEDATA) error: %s", curl_easy_strerror(err));
u32 page = 1;
constexpr u32 per_page = 100;
while (page <= 55)
{
fprintf(stdout, "Fetching page %d ...\n", page);
std::string url = "https://api.github.com/repos/RPCS3/rpcs3/commits?per_page=";
fmt::append(url, "%u&page=%u", per_page, page++);
if (!from_sha.empty())
fmt::append(url, "&sha=%s", from_sha);
err = curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
if (err != CURLE_OK)
{
fprintf(stderr, "curl_easy_setopt(CURLOPT_URL, %s) error: %s", url.c_str(), curl_easy_strerror(err));
break;
}
// Reset error buffer before we call curl_easy_perform
curl.reset_error_buffer();
err = curl_easy_perform(curl);
if (err != CURLE_OK)
{
const std::string error_string = curl.get_verbose_error(err);
fprintf(stderr, "curl_easy_perform(): %s", error_string.c_str());
break;
}
QJsonDocument info = QJsonDocument::fromJson(buf);
if (!info.isArray()) [[unlikely]]
{
fprintf(stderr, "Bad response:\n%s", buf.data());
break;
}
u32 count = 0;
for (auto&& ref : info.array())
{
if (!ref.isObject())
{
page = -1;
break;
}
count++;
QJsonObject result, author, committer;
QJsonObject commit = ref.toObject();
auto commit_ = commit["commit"].toObject();
auto author_ = commit_["author"].toObject();
auto committer_ = commit_["committer"].toObject();
auto _author = commit["author"].toObject();
auto _committer = commit["committer"].toObject();
result["sha"] = commit["sha"];
result["msg"] = commit_["message"];
author["name"] = author_["name"];
author["date"] = author_["date"];
author["email"] = author_["email"];
author["login"] = _author["login"];
author["avatar"] = _author["avatar_url"];
committer["name"] = committer_["name"];
committer["date"] = committer_["date"];
committer["email"] = committer_["email"];
committer["login"] = _committer["login"];
committer["avatar"] = _committer["avatar_url"];
result["author"] = author;
result["committer"] = committer;
QJsonDocument out(result);
buf = out.toJson(QJsonDocument::JsonFormat::Compact);
buf += "\n";
if (was_empty || !from_sha.empty())
{
data = buf.toStdString() + std::move(data);
}
else if (commit["sha"].toString().toStdString() == last)
{
page = -1;
break;
}
else
{
// Append to the list
list.emplace_back(buf.data(), buf.size());
}
}
buf.clear();
if (count < per_page)
{
break;
}
}
if (was_empty || !from_sha.empty())
{
file.trunc(0);
file.write(data);
}
else
{
// Append list in reverse order
for (usz i = list.size() - 1; ~i; --i)
{
file.write(list[i]);
}
}
curl_slist_free_all(hhdr);
fprintf(stdout, "Finished fetching commits: %s\n", path.c_str());
return 0;
}
if (parser.isSet(arg_q_debug))
{
qInstallMessageHandler(log_q_debug);
}
if (parser.isSet(arg_styles))
{
utils::attach_console(utils::console_stream::std_out, true);
for (const auto& style : QStyleFactory::keys())
std::cout << "\n" << style.toStdString();
return 0;
}
// Enable console output of "always" log messages.
// Do this after parsing any Qt cli args that might open a window.
fatal_listener->log_always(true);
// Log unique ID
gui::utils::log_uuid();
std::string active_user;
if (parser.isSet(arg_user_id))
{
active_user = parser.value(arg_user_id).toStdString();
if (rpcs3::utils::check_user(active_user) == 0)
{
report_fatal_error(fmt::format("Failed to set user ID '%s'.\nThe user ID must consist of 8 digits and cannot be 00000000.", active_user));
}
}
s_no_gui = parser.isSet(arg_no_gui);
if (gui_application* gui_app = qobject_cast<gui_application*>(app.data()))
{
gui_app->setAttribute(Qt::AA_DontCheckOpenGLContextThreadAffinity);
gui_app->SetShowGui(!s_no_gui);
gui_app->SetUseCliStyle(use_cli_style);
gui_app->SetWithCliBoot(parser.isSet(arg_installfw) || parser.isSet(arg_installpkg) || !parser.positionalArguments().isEmpty());
gui_app->SetActiveUser(active_user);
if (parser.isSet(arg_fullscreen))
{
if (!s_no_gui)
{
report_fatal_error(fmt::format("The option '%s' can only be used in combination with '%s'.", arg_fullscreen, arg_no_gui));
}
gui_app->SetStartGamesFullscreen(true);
}
if (parser.isSet(arg_gs_screen))
{
const int game_screen_index = parser.value(arg_gs_screen).toInt();
if (game_screen_index < 0)
{
report_fatal_error(fmt::format("The option '%s' can only be used with numbers >= 0 (you used %d)", arg_gs_screen, game_screen_index));
}
gui_app->SetGameScreenIndex(game_screen_index);
}
if (!gui_app->Init())
{
Emu.Quit(true);
return 0;
}
}
else if (headless_application* headless_app = qobject_cast<headless_application*>(app.data()))
{
s_headless = true;
headless_app->SetActiveUser(active_user);
if (!headless_app->Init())
{
Emu.Quit(true);
return 0;
}
}
else
{
// Should be unreachable
report_fatal_error("RPCS3 initialization failed!");
}
// Check if the current location is actually useable
if (!parser.isSet(arg_any_location))
{
const std::string emu_dir = rpcs3::utils::get_emu_dir();
// Check temporary directories
for (const QString& path : QStandardPaths::standardLocations(QStandardPaths::StandardLocation::TempLocation))
{
if (Emu.IsPathInsideDir(emu_dir, path.toStdString()))
{
report_fatal_error(fmt::format(
"RPCS3 should never be run from a temporary location!\n"
"Please install RPCS3 in a persistent location.\n"
"Current location:\n%s", emu_dir));
return 1;
}
}
// Check nonsensical archive locations
for (const std::string_view& expr : { "/Rar$"sv })
{
if (emu_dir.find(expr) != umax)
{
report_fatal_error(fmt::format(
"RPCS3 should never be run from an archive!\n"
"Please install RPCS3 in a persistent location.\n"
"Current location:\n%s", emu_dir));
return 1;
}
}
}
// Set timerslack value for Linux. The default value is 50,000ns. Change this to just 1 since we value precise timers.
#ifdef __linux__
prctl(PR_SET_TIMERSLACK, 1, 0, 0, 0);
#endif
#ifdef _WIN32
// Create dummy permanent low resolution timer to workaround messing with system timer resolution
QTimer* dummy_timer = new QTimer(app.data());
dummy_timer->start(13);
ULONG min_res, max_res, orig_res;
bool got_timer_resolution = NtQueryTimerResolution(&min_res, &max_res, &orig_res) == 0;
// Set 0.5 msec timer resolution for best performance
// - As QT timers (QTimer) sets the timer resolution to 1 msec, override it here.
if (parser.value(arg_timer).toStdString() == "1")
{
ULONG new_res;
if (got_timer_resolution && NtSetTimerResolution(max_res, TRUE, &new_res) == 0)
{
NtSetTimerResolution(max_res, TRUE, &new_res);
sys_log.notice("New timer resolution: %d us (old=%d us, min=%d us, max=%d us)", new_res / 10, orig_res / 10, min_res / 10, max_res / 10);
got_timer_resolution = false; // Invalidate for log message later
}
else
{
sys_log.error("Failed to set timer resolution!");
}
}
else
{
sys_log.warning("High resolution timer disabled!");
}
if (got_timer_resolution)
{
sys_log.notice("Timer resolution: %d us (min=%d us, max=%d us)", orig_res / 10, min_res / 10, max_res / 10);
}
#endif
if (parser.isSet(arg_decrypt))
{
utils::attach_console(utils::console_stream::std_out | utils::console_stream::std_in, true);
std::vector<std::string> vec_modules;
for (const QString& mod : parser.values(decrypt_option))
{
const QFileInfo fi(mod);
if (!fi.exists())
{
std::cout << "File not found: " << mod.toStdString() << std::endl;
return 1;
}
if (!fi.isFile())
{
std::cout << "Not a file: " << mod.toStdString() << std::endl;
return 1;
}
vec_modules.push_back(fi.absoluteFilePath().toStdString());
}
Emu.Init();
std::shared_ptr<decrypt_binaries_t> decrypter = std::make_shared<decrypt_binaries_t>(std::move(vec_modules));
usz mod_index = decrypter->decrypt();
usz repeat_count = mod_index == 0 ? 1 : 0;
while (!decrypter->done())
{
const std::string& path = (*decrypter)[mod_index];
const std::string filename = path.substr(path.find_last_of(fs::delim) + 1);
const std::string hint = fmt::format("Hint: KLIC (KLicense key) is a 16-byte long string. (32 hexadecimal characters)"
"\nAnd is logged with some sceNpDrm* functions when the game/application which owns \"%0\" is running.", filename);
if (repeat_count >= 2)
{
std::cout << "Failed to decrypt " << path << " with specfied KLIC, retrying.\n" << hint << std::endl;
}
std::cout << "Enter KLIC of " << filename << "\nHexadecimal only, 32 characters:" << std::endl;
std::string input;
std::cin >> input;
if (input.empty())
{
break;
}
const usz new_index = decrypter->decrypt(input);
repeat_count = new_index == mod_index ? repeat_count + 1 : 0;
mod_index = new_index;
}
Emu.Quit(true);
return 0;
}
// Force install firmware or pkg first if specified through command-line
if (parser.isSet(arg_installfw) || parser.isSet(arg_installpkg))
{
if (auto gui_app = qobject_cast<gui_application*>(app.data()))
{
if (s_no_gui)
{
report_fatal_error("Cannot perform installation in no-gui mode!");
}
if (gui_app->m_main_window)
{
if (parser.isSet(arg_installfw) && parser.isSet(arg_installpkg))
{
QMessageBox::warning(gui_app->m_main_window, QObject::tr("Invalid command-line arguments!"), QObject::tr("Cannot perform multiple installations at the same time!"));
}
else if (parser.isSet(arg_installfw))
{
gui_app->m_main_window->InstallPup(parser.value(installfw_option));
}
else
{
gui_app->m_main_window->InstallPackages({parser.value(installpkg_option)});
}
}
else
{
report_fatal_error("Cannot perform installation. No main window found!");
}
}
else
{
report_fatal_error("Cannot perform installation in headless mode!");
}
}
for (const auto& opt : parser.optionNames())
{
sys_log.notice("Option passed via command line: %s %s", opt, parser.value(opt));
}
if (parser.isSet(arg_savestate))
{
const std::string savestate_path = parser.value(savestate_option).toStdString();
sys_log.notice("Booting savestate from command line: %s", savestate_path);
if (!fs::is_file(savestate_path))
{
report_fatal_error(fmt::format("No savestate file found: %s", savestate_path));
}
Emu.CallFromMainThread([path = savestate_path]()
{
Emu.SetForceBoot(true);
if (const game_boot_result error = Emu.BootGame(path); error != game_boot_result::no_errors)
{
sys_log.error("Booting savestate '%s' failed: reason: %s", path, error);
if (s_headless || s_no_gui)
{
report_fatal_error(fmt::format("Booting savestate '%s' failed!\n\nReason: %s", path, error));
}
}
});
}
else if (parser.isSet(arg_rsx_capture))
{
const std::string rsx_capture_path = parser.value(rsx_capture_option).toStdString();
sys_log.notice("Booting rsx capture from command line: %s", rsx_capture_path);
if (!fs::is_file(rsx_capture_path))
{
report_fatal_error(fmt::format("No rsx capture file found: %s", rsx_capture_path));
}
Emu.CallFromMainThread([path = rsx_capture_path]()
{
if (!Emu.BootRsxCapture(path))
{
sys_log.error("Booting rsx capture '%s' failed", path);
if (s_headless || s_no_gui)
{
report_fatal_error(fmt::format("Booting rsx capture '%s' failed!", path));
}
}
});
}
else if (const QStringList args = parser.positionalArguments(); !args.isEmpty() && !is_updating && !parser.isSet(arg_installfw) && !parser.isSet(arg_installpkg))
{
const std::string spath = ::at32(args, 0).toStdString();
if (spath.starts_with(Emulator::vfs_boot_prefix))
{
sys_log.notice("Booting application from command line using VFS path: %s", spath.substr(Emulator::vfs_boot_prefix.size()));
}
else if (spath.starts_with(Emulator::game_id_boot_prefix))
{
sys_log.notice("Booting application from command line using GAMEID: %s", spath.substr(Emulator::game_id_boot_prefix.size()));
}
else
{
sys_log.notice("Booting application from command line: %s", spath);
}
// Propagate command line arguments
std::vector<std::string> rpcs3_argv;
if (args.length() > 1)
{
rpcs3_argv.emplace_back();
for (int i = 1; i < args.length(); i++)
{
const std::string arg = args[i].toStdString();
rpcs3_argv.emplace_back(arg);
sys_log.notice("Optional command line argument %d: %s", i, arg);
}
}
std::string config_path;
if (parser.isSet(arg_config))
{
config_path = parser.value(config_option).toStdString();
if (!fs::is_file(config_path))
{
report_fatal_error(fmt::format("No config file found: %s", config_path));
}
}
if (parser.isSet(arg_input_config))
{
if (!s_no_gui)
{
report_fatal_error(fmt::format("The option '%s' can only be used in combination with '%s'.", arg_input_config, arg_no_gui));
}
g_input_config_override = parser.value(input_config_option).toStdString();
if (g_input_config_override.empty())
{
report_fatal_error(fmt::format("Input config file name is empty"));
}
}
// Postpone startup to main event loop
Emu.CallFromMainThread([path = spath.starts_with("%RPCS3_") ? spath : QFileInfo(::at32(args, 0)).absoluteFilePath().toStdString(), rpcs3_argv = std::move(rpcs3_argv), config_path = std::move(config_path)]() mutable
{
Emu.argv = std::move(rpcs3_argv);
Emu.SetForceBoot(true);
const cfg_mode config_mode = config_path.empty() ? cfg_mode::custom : cfg_mode::config_override;
if (const game_boot_result error = Emu.BootGame(path, "", false, config_mode, config_path); error != game_boot_result::no_errors)
{
sys_log.error("Booting '%s' with cli argument failed: reason: %s", path, error);
if (s_headless || s_no_gui)
{
report_fatal_error(fmt::format("Booting '%s' failed!\n\nReason: %s", path, error));
}
}
});
}
else if (s_headless || s_no_gui)
{
// If launched from CMD
utils::attach_console(utils::console_stream::std_out | utils::console_stream::std_err, false);
sys_log.error("Cannot run %s mode without boot target. Terminating...", s_headless ? "headless" : "no-gui");
fprintf(stderr, "Cannot run %s mode without boot target. Terminating...\n", s_headless ? "headless" : "no-gui");
if (s_no_gui)
{
QMessageBox::warning(nullptr, QObject::tr("Missing command-line arguments!"), QObject::tr("Cannot run no-gui mode without boot target.\nTerminating..."));
}
Emu.Quit(true);
return 0;
}
// run event loop (maybe only needed for the gui application)
return app->exec();
}
| 43,224
|
C++
|
.cpp
| 1,182
| 33.551607
| 231
| 0.688901
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,000
|
module_verifier.cpp
|
RPCS3_rpcs3/rpcs3/module_verifier.cpp
|
#include "stdafx.h"
#include "module_verifier.hpp"
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>
#include <Shlwapi.h>
#include <util/types.hpp>
#include <util/logs.hpp>
#include <Utilities/StrUtil.h>
#include <Utilities/StrFmt.h>
LOG_CHANNEL(sys_log, "SYS");
[[noreturn]] void report_fatal_error(std::string_view text, bool is_html, bool include_help_text);
void WIN32_module_verifier::run_module_verification()
{
struct module_info_t
{
std::wstring_view name;
std::string_view package_name;
std::string_view dl_link;
};
const std::vector<module_info_t> special_module_infos = {
{ L"vulkan-1.dll", "Vulkan Runtime", "https://sdk.lunarg.com/sdk/download/latest/windows/vulkan-runtime.exe" },
{ L"msvcp140.dll", "Microsoft Visual C++ 2015-2022 Redistributable", "https://aka.ms/vs/17/release/VC_redist.x64.exe" },
{ L"vcruntime140.dll", "Microsoft Visual C++ 2015-2022 Redistributable", "https://aka.ms/vs/17/release/VC_redist.x64.exe" },
{ L"msvcp140_1.dll", "Microsoft Visual C++ 2015-2022 Redistributable", "https://aka.ms/vs/17/release/VC_redist.x64.exe" },
{ L"vcruntime140_1.dll", "Microsoft Visual C++ 2015-2022 Redistributable", "https://aka.ms/vs/17/release/VC_redist.x64.exe" }
};
WCHAR windir[MAX_PATH];
if (!GetWindowsDirectory(windir, MAX_PATH))
{
report_fatal_error(fmt::format("WIN32_module_verifier: Failed to query WindowsDirectory"), false, true);
}
for (const auto& module : special_module_infos)
{
const HMODULE hModule = GetModuleHandle(module.name.data());
if (hModule == NULL)
{
continue;
}
WCHAR wpath[MAX_PATH];
if (const auto len = GetModuleFileName(hModule, wpath, MAX_PATH))
{
if (::StrStrI(wpath, windir) != wpath)
{
const std::string path = wchar_to_utf8(wpath);
const std::string win_path = wchar_to_utf8(windir);
const std::string module_name = wchar_to_utf8(module.name);
const std::string error_message = fmt::format(
"<p>"
"The module <strong>%s</strong> was incorrectly installed at<br>"
"'%s'<br>"
"<br>"
"This module is part of the <strong>%s</strong> package.<br>"
"Install this package, then delete <strong>%s</strong> from rpcs3's installation directory.<br>"
"<br>"
"You can install this package from this URL:<br>"
"<a href='%s'>%s</a>"
"</p>",
module_name,
path,
module.package_name,
module_name,
module.dl_link,
module.dl_link
);
sys_log.error("Found incorrectly installed module: '%s' (path='%s', windows='%s')", module_name, path, win_path);
report_fatal_error(error_message, true, false);
}
}
}
}
void WIN32_module_verifier::run()
{
WIN32_module_verifier verifier{};
verifier.run_module_verification();
}
#endif // _WIN32
| 2,803
|
C++
|
.cpp
| 79
| 32.164557
| 127
| 0.693245
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
5,001
|
headless_application.cpp
|
RPCS3_rpcs3/rpcs3/headless_application.cpp
|
#include "headless_application.h"
#include "Emu/RSX/Null/NullGSRender.h"
#include "Emu/Cell/Modules/cellMsgDialog.h"
#include "Emu/Cell/Modules/cellOskDialog.h"
#include "Emu/Cell/Modules/cellSaveData.h"
#include "Emu/Cell/Modules/sceNpTrophy.h"
#include "Emu/Io/Null/null_camera_handler.h"
#include "Emu/Io/Null/null_music_handler.h"
#include <clocale>
[[noreturn]] void report_fatal_error(std::string_view text, bool is_html = false, bool include_help_text = true);
// For now, a trivial constructor/destructor. May add command line usage later.
headless_application::headless_application(int& argc, char** argv) : QCoreApplication(argc, argv)
{
}
bool headless_application::Init()
{
// Force init the emulator
InitializeEmulator(m_active_user.empty() ? "00000001" : m_active_user, false);
// Create callbacks from the emulator, which reference the handlers.
InitializeCallbacks();
// Create connects to propagate events throughout Gui.
InitializeConnects();
// As per Qt recommendations to avoid conflicts for POSIX functions
std::setlocale(LC_NUMERIC, "C");
return true;
}
void headless_application::InitializeConnects() const
{
qRegisterMetaType<std::function<void()>>("std::function<void()>");
connect(this, &headless_application::RequestCallFromMainThread, this, &headless_application::CallFromMainThread);
}
/** RPCS3 emulator has functions it desires to call from the GUI at times. Initialize them in here. */
void headless_application::InitializeCallbacks()
{
EmuCallbacks callbacks = CreateCallbacks();
callbacks.try_to_quit = [this](bool force_quit, std::function<void()> on_exit) -> bool
{
if (force_quit)
{
if (on_exit)
{
on_exit();
}
quit();
return true;
}
return false;
};
callbacks.call_from_main_thread = [this](std::function<void()> func, atomic_t<u32>* wake_up)
{
RequestCallFromMainThread(std::move(func), wake_up);
};
callbacks.init_gs_render = [](utils::serial* ar)
{
switch (const video_renderer type = g_cfg.video.renderer)
{
case video_renderer::null:
{
g_fxo->init<rsx::thread, named_thread<NullGSRender>>(ar);
break;
}
case video_renderer::opengl:
case video_renderer::vulkan:
{
fmt::throw_exception("Headless mode can only be used with the %s video renderer. Current renderer: %s", video_renderer::null, type);
[[fallthrough]];
}
default:
{
fmt::throw_exception("Invalid video renderer: %s", type);
}
}
};
callbacks.get_camera_handler = []() -> std::shared_ptr<camera_handler_base>
{
switch (g_cfg.io.camera.get())
{
case camera_handler::null:
case camera_handler::fake:
{
return std::make_shared<null_camera_handler>();
}
case camera_handler::qt:
{
fmt::throw_exception("Headless mode can not be used with this camera handler. Current handler: %s", g_cfg.io.camera.get());
}
}
return nullptr;
};
callbacks.get_music_handler = []() -> std::shared_ptr<music_handler_base>
{
switch (g_cfg.audio.music.get())
{
case music_handler::null:
{
return std::make_shared<null_music_handler>();
}
case music_handler::qt:
{
fmt::throw_exception("Headless mode can not be used with this music handler. Current handler: %s", g_cfg.audio.music.get());
}
}
return nullptr;
};
callbacks.get_gs_frame = []() -> std::unique_ptr<GSFrameBase>
{
if (g_cfg.video.renderer != video_renderer::null)
{
fmt::throw_exception("Headless mode can only be used with the %s video renderer. Current renderer: %s", video_renderer::null, g_cfg.video.renderer.get());
}
return std::unique_ptr<GSFrameBase>();
};
callbacks.get_msg_dialog = []() -> std::shared_ptr<MsgDialogBase> { return std::shared_ptr<MsgDialogBase>(); };
callbacks.get_osk_dialog = []() -> std::shared_ptr<OskDialogBase> { return std::shared_ptr<OskDialogBase>(); };
callbacks.get_save_dialog = []() -> std::unique_ptr<SaveDialogBase> { return std::unique_ptr<SaveDialogBase>(); };
callbacks.get_trophy_notification_dialog = []() -> std::unique_ptr<TrophyNotificationBase> { return std::unique_ptr<TrophyNotificationBase>(); };
callbacks.on_run = [](bool /*start_playtime*/) {};
callbacks.on_pause = []() {};
callbacks.on_resume = []() {};
callbacks.on_stop = []() {};
callbacks.on_ready = []() {};
callbacks.on_emulation_stop_no_response = [](std::shared_ptr<atomic_t<bool>> closed_successfully, int /*seconds_waiting_already*/)
{
if (!closed_successfully || !*closed_successfully)
{
report_fatal_error(tr("Stopping emulator took too long."
"\nSome thread has probably deadlocked. Aborting.").toStdString());
}
};
callbacks.on_save_state_progress = [](std::shared_ptr<atomic_t<bool>>, stx::shared_ptr<utils::serial>, stx::atomic_ptr<std::string>*, std::shared_ptr<void>)
{
};
callbacks.enable_disc_eject = [](bool) {};
callbacks.enable_disc_insert = [](bool) {};
callbacks.on_missing_fw = []() { return false; };
callbacks.handle_taskbar_progress = [](s32, s32) {};
callbacks.get_localized_string = [](localized_string_id, const char*) -> std::string { return {}; };
callbacks.get_localized_u32string = [](localized_string_id, const char*) -> std::u32string { return {}; };
callbacks.get_localized_setting = [](const cfg::_base*, u32) -> std::string { return {}; };
callbacks.play_sound = [](const std::string&){};
callbacks.add_breakpoint = [](u32 /*addr*/){};
Emu.SetCallbacks(std::move(callbacks));
}
/**
* Using connects avoids timers being unable to be used in a non-qt thread. So, even if this looks stupid to just call func, it's succinct.
*/
void headless_application::CallFromMainThread(const std::function<void()>& func, atomic_t<u32>* wake_up)
{
func();
if (wake_up)
{
*wake_up = true;
wake_up->notify_one();
}
}
| 5,789
|
C++
|
.cpp
| 155
| 34.774194
| 157
| 0.69884
|
RPCS3/rpcs3
| 15,204
| 1,895
| 1,021
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.