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,318
Qv2rayLog.hpp
Qv2ray_Qv2ray/src/base/Qv2rayLog.hpp
#pragma once #include "3rdparty/QJsonStruct/macroexpansion.hpp" #include "base/Qv2rayBaseApplication.hpp" #include "base/models/QvStartupConfig.hpp" #include <QPair> #include <QString> #include <QTextStream> #include <iostream> #ifdef Q_OS_ANDROID #include <android/log.h> #endif #define NEWLINE "\r\n" #define QVLOG_A_DO_EXPAND(___x) , QPair<std::string, decltype(___x)>(std::string(#___x), [&] { return ___x; }()) #define QVLOG_A(...) FOREACH_CALL_FUNC(QVLOG_A_DO_EXPAND, __VA_ARGS__) #ifdef QT_DEBUG #define QV2RAY_IS_DEBUG true // __FILE__ ":" QT_STRINGIFY(__LINE__), #define QV2RAY_LOG_PREPEND_CONTENT Q_FUNC_INFO, #else #define QV2RAY_IS_DEBUG false #define QV2RAY_LOG_PREPEND_CONTENT #endif #define _LOG_ARG_(...) QV2RAY_LOG_PREPEND_CONTENT "[" QV_MODULE_NAME "]", __VA_ARGS__ #define LOG(...) Qv2ray::base::log_internal<QV2RAY_LOG_NORMAL>(_LOG_ARG_(__VA_ARGS__)) #define DEBUG(...) Qv2ray::base::log_internal<QV2RAY_LOG_DEBUG>(_LOG_ARG_(__VA_ARGS__)) enum QvLogType { QV2RAY_LOG_NORMAL = 0, QV2RAY_LOG_DEBUG = 1 }; Q_DECLARE_METATYPE(const char *) namespace Qv2ray::base { inline QString logBuffer; inline QString tempBuffer; inline QTextStream logStream{ &logBuffer }; inline QTextStream tempStream{ &tempBuffer }; inline QString ReadLog() { return logStream.readAll(); } template<QvLogType t, typename... T> inline void log_internal(T... v) { ((logStream << v << " "), ...); ((tempStream << v << " "), ...); logStream << NEWLINE; #ifndef QT_DEBUG // We only process DEBUG log in Release mode // Prevent QvCoreApplication nullptr // TODO: Move log function inside QvCoreApplication if (t == QV2RAY_LOG_DEBUG && QvCoreApplication && !QvCoreApplication->StartupArguments.debugLog) { // Discard debug log in non-debug Qv2ray version with // no-debugLog mode. return; } #endif const auto logString = tempStream.readAll(); #ifdef Q_OS_ANDROID __android_log_write(ANDROID_LOG_INFO, "Qv2ray", logString.toStdString().c_str()); #else std::cout << logString.toStdString() << std::endl; #endif } } // namespace Qv2ray::base template<typename TKey, typename TVal> QTextStream &operator<<(QTextStream &stream, const QPair<TKey, TVal> &pair) { return stream << pair.first << ": " << pair.second; } inline QTextStream &operator<<(QTextStream &stream, const std::string &ss) { return stream << ss.data(); } template<typename TKey, typename TVal> QTextStream &operator<<(QTextStream &stream, const QMap<TKey, TVal> &map) { stream << "{ "; for (const auto &[k, v] : map.toStdMap()) stream << QPair<TKey, TVal>(k, v) << "; "; stream << "}"; return stream; } template<typename TVal> QTextStream &operator<<(QTextStream &stream, const std::initializer_list<TVal> &init_list) { for (const auto &x : init_list) stream << x; return stream; }
2,985
C++
.h
91
28.978022
112
0.666667
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,319
JsonHelpers.hpp
Qv2ray_Qv2ray/src/base/JsonHelpers.hpp
#pragma once #define STRINGIZE(arg) STRINGIZE1(arg) #define STRINGIZE1(arg) STRINGIZE2(arg) #define STRINGIZE2(arg) #arg #define CONCATENATE1(arg1, arg2) CONCATENATE2(arg1, arg2) #define CONCATENATE2(arg1, arg2) arg1##arg2 // Add key value pair into JSON named 'root' #define JADDEx(field) root.insert(#field, field); #define JADD(...) FOR_EACH(JADDEx, __VA_ARGS__)
369
C++
.h
9
39.666667
57
0.764706
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,320
Qv2rayBaseApplication.hpp
Qv2ray_Qv2ray/src/base/Qv2rayBaseApplication.hpp
#pragma once #include "base/models/QvSettingsObject.hpp" #include <QCoreApplication> #include <QObject> namespace Qv2ray { enum MessageOpt { OK, Cancel, Yes, No, Ignore }; enum Qv2rayExitReason { EXIT_NORMAL = 0, EXIT_NEW_VERSION_TRIGGER = EXIT_NORMAL, EXIT_SECONDARY_INSTANCE = EXIT_NORMAL, EXIT_INITIALIZATION_FAILED = -1, EXIT_PRECONDITION_FAILED = -2, }; struct Qv2rayStartupArguments { enum Argument { NORMAL = 0, QV2RAY_LINK = 1, EXIT = 2, RECONNECT = 3, DISCONNECT = 4 }; QList<Argument> arguments; QString version; int buildVersion; QString data; QList<QString> links; QList<QString> fullArgs; // bool noAPI; bool noAutoConnection; bool debugLog; bool noPlugins; bool exitQv2ray; // QString _qvNewVersionPath; JSONSTRUCT_REGISTER(Qv2rayStartupArguments, F(arguments, data, version, links, fullArgs, buildVersion)) }; class Qv2rayApplicationInterface { public: Qv2ray::base::config::Qv2rayConfigObject *ConfigObject; QString ConfigPath; Qv2rayStartupArguments StartupArguments; public: explicit Qv2rayApplicationInterface(); ~Qv2rayApplicationInterface(); public: virtual QStringList GetAssetsPaths(const QString &dirName) const final; // virtual void MessageBoxWarn(QWidget *parent, const QString &title, const QString &text) = 0; virtual void MessageBoxInfo(QWidget *parent, const QString &title, const QString &text) = 0; virtual MessageOpt MessageBoxAsk(QWidget *parent, const QString &title, const QString &text, const QList<MessageOpt> &buttons) = 0; virtual void OpenURL(const QString &url) = 0; }; inline Qv2rayApplicationInterface *QvCoreApplication = nullptr; } // namespace Qv2ray #define GlobalConfig (*Qv2ray::QvCoreApplication->ConfigObject)
2,114
C++
.h
68
23.455882
139
0.642612
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,321
Qv2rayBase.hpp
Qv2ray_Qv2ray/src/base/Qv2rayBase.hpp
#pragma once // #include <QMap> #include <QtCore> #include <algorithm> #include <ctime> #include <iostream> #include <optional> #include <vector> // Base support. #include "base/JsonHelpers.hpp" #include "base/Qv2rayFeatures.hpp" #include "base/Qv2rayLog.hpp" // Code Models #include "base/Qv2rayBaseApplication.hpp" #include "base/models/CoreObjectModels.hpp" #include "base/models/QvConfigIdentifier.hpp" #include "base/models/QvRuntimeConfig.hpp" #include "base/models/QvSafeType.hpp" #include "base/models/QvSettingsObject.hpp" #include "base/models/QvStartupConfig.hpp" using namespace Qv2ray; using namespace Qv2ray::base; using namespace Qv2ray::base::safetype; using namespace Qv2ray::base::config; using namespace Qv2ray::base::objects; using namespace Qv2ray::base::objects::protocol; using namespace Qv2ray::base::objects::transfer; #define QV2RAY_BUILD_INFO QString(_QV2RAY_BUILD_INFO_STR_) #define QV2RAY_BUILD_EXTRA_INFO QString(_QV2RAY_BUILD_EXTRA_INFO_STR_) // Base folder suffix. #ifdef QT_DEBUG #define QV2RAY_CONFIG_DIR_SUFFIX "_debug/" #define _BOMB_ (static_cast<QObject *>(nullptr)->event(nullptr)) #else #define _BOMB_ #define QV2RAY_CONFIG_DIR_SUFFIX "/" #endif #ifdef Q_OS_WIN #define QV2RAY_EXECUTABLE_SUFFIX ".exe" #else #define QV2RAY_EXECUTABLE_SUFFIX "" #endif #ifdef Q_OS_WIN #define QV2RAY_LIBRARY_SUFFIX ".dll" #else #define QV2RAY_LIBRARY_SUFFIX ".so" #endif // Get Configured Config Dir Path #define QV2RAY_CONFIG_DIR (QvCoreApplication->ConfigPath) #define QV2RAY_CONFIG_FILE (QV2RAY_CONFIG_DIR + "Qv2ray.conf") #define QV2RAY_CONNECTIONS_DIR (QV2RAY_CONFIG_DIR + "connections/") #define QV2RAY_PLUGIN_SETTINGS_DIR (QV2RAY_CONFIG_DIR + "plugin_settings/") #define QV2RAY_CONFIG_FILE_EXTENSION ".qv2ray.json" #define QV2RAY_GENERATED_DIR (QV2RAY_CONFIG_DIR + "generated/") #if !defined(QV2RAY_DEFAULT_VCORE_PATH) && !defined(QV2RAY_DEFAULT_VASSETS_PATH) #define QV2RAY_DEFAULT_VASSETS_PATH (QV2RAY_CONFIG_DIR + "vcore/") #define QV2RAY_DEFAULT_VCORE_PATH (QV2RAY_CONFIG_DIR + "vcore/v2ray" QV2RAY_EXECUTABLE_SUFFIX) #if !defined(QV2RAY_USE_V5_CORE) #define QV2RAY_DEFAULT_VCTL_PATH (QV2RAY_CONFIG_DIR + "vcore/v2ctl" QV2RAY_EXECUTABLE_SUFFIX) #endif #elif defined(QV2RAY_DEFAULT_VCORE_PATH) && defined(QV2RAY_DEFAULT_VASSETS_PATH) // ---- Using user-specified VCore and VAssets path #else #error Both QV2RAY_DEFAULT_VCORE_PATH and QV2RAY_DEFAULT_VASSETS_PATH need to be presented when using manually specify the paths. #endif #define QSTRN(num) QString::number(num) #define OUTBOUND_TAG_BLACKHOLE "BLACKHOLE" #define OUTBOUND_TAG_DIRECT "DIRECT" #define OUTBOUND_TAG_PROXY "PROXY" #define OUTBOUND_TAG_FORWARD_PROXY "QV2RAY_FORWARD_PROXY" #define API_TAG_DEFAULT "QV2RAY_API" #define API_TAG_INBOUND "QV2RAY_API_INBOUND" #define QV2RAY_USE_FPROXY_KEY "_QV2RAY_USE_GLOBAL_FORWARD_PROXY_"
2,833
C++
.h
74
37.135135
129
0.79294
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,322
QvSafeType.hpp
Qv2ray_Qv2ray/src/base/models/QvSafeType.hpp
#pragma once #include "3rdparty/QJsonStruct/QJsonStruct.hpp" #include <QJsonArray> #include <QJsonDocument> #include <QJsonObject> #include <QMap> template<typename placeholder, typename BASETYPE_T> class SAFETYPE_IMPL : public BASETYPE_T { public: template<class... Args> explicit SAFETYPE_IMPL(Args... args) : BASETYPE_T(args...){}; const BASETYPE_T &raw() const { return *this; } }; #define SAFE_TYPEDEF(BASE, CLASS) \ class __##CLASS##__; \ typedef SAFETYPE_IMPL<__##CLASS##__, BASE> CLASS; #define nothing namespace Qv2ray::base::safetype { // To prevent anonying QJsonObject misuse SAFE_TYPEDEF(QJsonObject, INBOUNDSETTING); SAFE_TYPEDEF(QJsonObject, OUTBOUNDSETTING); SAFE_TYPEDEF(QJsonObject, INBOUND); SAFE_TYPEDEF(QJsonObject, OUTBOUND); SAFE_TYPEDEF(QJsonObject, CONFIGROOT); SAFE_TYPEDEF(QJsonObject, ROUTING); SAFE_TYPEDEF(QJsonObject, ROUTERULE); // SAFE_TYPEDEF(QJsonArray, OUTBOUNDS); SAFE_TYPEDEF(QJsonArray, INBOUNDS); template<typename T1, typename T2 = T1> struct QvPair { T1 value1; T2 value2; friend bool operator==(const QvPair<T1, T2> &one, const QvPair<T1, T2> &another) { return another.value1 == one.value1 && another.value2 == one.value2; } JSONSTRUCT_REGISTER(___qvpair_t, F(value1, value2)) private: typedef QvPair<T1, T2> ___qvpair_t; }; template<typename enumKey, typename TValue, typename = typename std::enable_if_t<std::is_enum_v<enumKey>>> struct QvEnumMap : QMap<enumKey, TValue> { // WARN: Changing this will break all existing JSON. static constexpr auto ENUM_JSON_KEY_PREFIX = "$"; void loadJson(const QJsonValue &json_object) { QMap<QString, TValue> data; JsonStructHelper::Deserialize(data, json_object); this->clear(); for (QString k_str : data.keys()) { enumKey k = static_cast<enumKey>(k_str.remove(ENUM_JSON_KEY_PREFIX).toInt()); this->insert(k, data[ENUM_JSON_KEY_PREFIX + k_str]); } } [[nodiscard]] static auto fromJson(const QJsonValue &json) { QvEnumMap t; t.loadJson(json); return t; } [[nodiscard]] const QJsonObject toJson() const { QMap<QString, TValue> data; for (const auto &k : this->keys()) { data[ENUM_JSON_KEY_PREFIX + QString::number(k)] = this->value(k); } return JsonStructHelper::Serialize(data).toObject(); } }; } // namespace Qv2ray::base::safetype using namespace Qv2ray::base::safetype;
2,995
C++
.h
81
29.790123
150
0.572461
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,323
CoreObjectModels.hpp
Qv2ray_Qv2ray/src/base/models/CoreObjectModels.hpp
#pragma once #include "3rdparty/QJsonStruct/QJsonIO.hpp" #include "3rdparty/QJsonStruct/QJsonStruct.hpp" #include <QList> #include <QMap> #include <QString> namespace Qv2ray::base::objects { struct DNSObject { struct DNSServerObject { bool QV2RAY_DNS_IS_COMPLEX_DNS; QString address; int port; QList<QString> domains; QList<QString> expectIPs; DNSServerObject() : QV2RAY_DNS_IS_COMPLEX_DNS(false), port(53){}; DNSServerObject(const QString &_address) : DNSServerObject() { address = _address; }; friend bool operator==(const DNSServerObject &left, const DNSServerObject &right) { return left.QV2RAY_DNS_IS_COMPLEX_DNS == right.QV2RAY_DNS_IS_COMPLEX_DNS && // left.address == right.address && // left.port == right.port && // left.domains == right.domains && // left.expectIPs == right.expectIPs; } friend bool operator!=(const DNSServerObject &left, const DNSServerObject &right) { return !(left == right); } void loadJson(const QJsonValue &___json_object_) { DNSServerObject ___qjsonstruct_default_check; // Hack to convert simple DNS settings to complex format. if (___json_object_.isString()) { address = ___json_object_.toString(); QV2RAY_DNS_IS_COMPLEX_DNS = false; return; } FOREACH_CALL_FUNC(___DESERIALIZE_FROM_JSON_EXTRACT_B_F, F(QV2RAY_DNS_IS_COMPLEX_DNS, address, port, domains, expectIPs)); } [[nodiscard]] static auto fromJson(const QJsonValue &___json_object_) { DNSServerObject _t; _t.loadJson(___json_object_); return _t; } [[nodiscard]] const QJsonObject toJson() const { QJsonObject ___json_object_; DNSServerObject ___qjsonstruct_default_check; FOREACH_CALL_FUNC(___SERIALIZE_TO_JSON_EXTRACT_B_F, F(QV2RAY_DNS_IS_COMPLEX_DNS, address, port, domains, expectIPs)); return ___json_object_; } }; QMap<QString, QString> hosts; QList<DNSServerObject> servers; QString clientIp; QString tag; bool disableCache = false; bool disableFallback = false; QString queryStrategy = "UseIP"; friend bool operator==(const DNSObject &left, const DNSObject &right) { return left.hosts == right.hosts && // left.servers == right.servers && // left.clientIp == right.clientIp && // left.tag == right.tag && // left.disableCache == right.disableCache && // left.disableFallback == right.disableFallback && // left.queryStrategy == right.queryStrategy; } friend bool operator!=(const DNSObject &left, const DNSObject &right) { return !(left == right); } JSONSTRUCT_REGISTER(DNSObject, F(hosts, servers, clientIp, tag, disableCache, disableFallback, queryStrategy)) }; // // Used in config generation struct AccountObject { QString user; QString pass; JSONSTRUCT_COMPARE(AccountObject, user, pass) JSONSTRUCT_REGISTER(AccountObject, F(user, pass)) }; // // struct RuleObject { bool QV2RAY_RULE_ENABLED = true; QString QV2RAY_RULE_TAG = "New Rule"; // QString type = "field"; QList<QString> inboundTag; QString outboundTag; QString balancerTag; // Addresses QList<QString> source; QList<QString> domain; QList<QString> ip; // Ports QString sourcePort; QString port; // QString network; QList<QString> protocol; QString attrs; JSONSTRUCT_COMPARE(RuleObject, type, outboundTag, balancerTag, // QV2RAY_RULE_ENABLED, QV2RAY_RULE_TAG, // domain, ip, port, sourcePort, network, source, inboundTag, protocol, attrs) JSONSTRUCT_REGISTER(RuleObject, // A(type, outboundTag, balancerTag), // A(QV2RAY_RULE_ENABLED, QV2RAY_RULE_TAG), // F(domain, ip, port, sourcePort, network, source, inboundTag, protocol, attrs)) }; // // struct StrategyObject { QString type; JSONSTRUCT_COMPARE(StrategyObject, type) JSONSTRUCT_REGISTER(StrategyObject, F(type)) }; struct BalancerObject { QString tag; QList<QString> selector; StrategyObject strategy; JSONSTRUCT_COMPARE(BalancerObject, tag, selector, strategy) JSONSTRUCT_REGISTER(BalancerObject, F(tag, selector, strategy)) }; // // namespace transfer { struct HTTPRequestObject { QString version = "1.1"; QString method = "GET"; QList<QString> path = { "/" }; QMap<QString, QList<QString>> headers; HTTPRequestObject() { headers = { { "Host", { "www.baidu.com", "www.bing.com" } }, { "User-Agent", { "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36", "Mozilla/5.0 (iPhone; CPU iPhone OS 10_0_2 like Mac OS X) AppleWebKit/601.1 (KHTML, like Gecko) CriOS/53.0.2785.109 Mobile/14A456 Safari/601.1.46" } }, { "Accept-Encoding", { "gzip, deflate" } }, { "Connection", { "keep-alive" } }, { "Pragma", { "no-cache" } } }; } JSONSTRUCT_COMPARE(HTTPRequestObject, version, method, path, headers) JSONSTRUCT_REGISTER(HTTPRequestObject, F(version, method, path, headers)) }; // // struct HTTPResponseObject { QString version = "1.1"; QString status = "200"; QString reason = "OK"; QMap<QString, QList<QString>> headers; HTTPResponseObject() { headers = { { "Content-Type", { "application/octet-stream", "video/mpeg" } }, // { "Transfer-Encoding", { "chunked" } }, // { "Connection", { "keep-alive" } }, // { "Pragma", { "no-cache" } } }; } JSONSTRUCT_COMPARE(HTTPResponseObject, version, status, reason, headers) JSONSTRUCT_REGISTER(HTTPResponseObject, F(version, status, reason, headers)) }; // // struct TCPHeader_Internal { QString type = "none"; HTTPRequestObject request; HTTPResponseObject response; JSONSTRUCT_COMPARE(TCPHeader_Internal, type, request, response) JSONSTRUCT_REGISTER(TCPHeader_Internal, A(type), F(request, response)) }; // // struct ObfsHeaderObject { QString type = "none"; JSONSTRUCT_COMPARE(ObfsHeaderObject, type) JSONSTRUCT_REGISTER(ObfsHeaderObject, F(type)) }; // // struct TCPObject { TCPHeader_Internal header; JSONSTRUCT_COMPARE(TCPObject, header) JSONSTRUCT_REGISTER(TCPObject, F(header)) }; // // struct KCPObject { int mtu = 1350; int tti = 50; int uplinkCapacity = 5; int downlinkCapacity = 20; bool congestion = false; int readBufferSize = 2; int writeBufferSize = 2; QString seed; ObfsHeaderObject header; KCPObject(){}; JSONSTRUCT_COMPARE(KCPObject, mtu, tti, uplinkCapacity, downlinkCapacity, congestion, readBufferSize, writeBufferSize, seed, header) JSONSTRUCT_REGISTER(KCPObject, F(mtu, tti, uplinkCapacity, downlinkCapacity, congestion, readBufferSize, writeBufferSize, header, seed)) }; // // struct WebSocketObject { QString path = "/"; QMap<QString, QString> headers; int maxEarlyData = 0; bool useBrowserForwarding = false; QString earlyDataHeaderName; JSONSTRUCT_COMPARE(WebSocketObject, path, headers, maxEarlyData, useBrowserForwarding, earlyDataHeaderName) JSONSTRUCT_REGISTER(WebSocketObject, F(path, headers, maxEarlyData, useBrowserForwarding, earlyDataHeaderName)) }; // // struct HttpObject { QList<QString> host; QString path = "/"; QString method = "PUT"; QMap<QString, QList<QString>> headers; JSONSTRUCT_COMPARE(HttpObject, host, path, method, headers) JSONSTRUCT_REGISTER(HttpObject, F(host, path, method, headers)) }; // // struct DomainSocketObject { QString path = "/"; JSONSTRUCT_COMPARE(DomainSocketObject, path) JSONSTRUCT_REGISTER(DomainSocketObject, F(path)) }; // // struct QuicObject { QString security = "none"; QString key; ObfsHeaderObject header; JSONSTRUCT_COMPARE(QuicObject, security, key, header) JSONSTRUCT_REGISTER(QuicObject, F(security, key, header)) }; // // struct gRPCObject { QString serviceName; bool multiMode = false; JSONSTRUCT_COMPARE(gRPCObject, serviceName, multiMode) JSONSTRUCT_REGISTER(gRPCObject, F(serviceName, multiMode)) }; // // struct SockoptObject { int mark = 0; bool tcpFastOpen = false; QString tproxy = "off"; int tcpKeepAliveInterval = 0; JSONSTRUCT_COMPARE(SockoptObject, mark, tcpFastOpen, tproxy, tcpKeepAliveInterval) JSONSTRUCT_REGISTER(SockoptObject, F(mark, tcpFastOpen, tproxy, tcpKeepAliveInterval)) }; // // struct CertificateObject { QString usage = "encipherment"; QString certificateFile; QString keyFile; QList<QString> certificate; QList<QString> key; JSONSTRUCT_COMPARE(CertificateObject, usage, certificateFile, keyFile, certificate, key) JSONSTRUCT_REGISTER(CertificateObject, F(usage, certificateFile, keyFile, certificate, key)) }; // // struct TLSObject { QString serverName; bool allowInsecure = false; bool enableSessionResumption = false; bool disableSystemRoot = false; QList<QString> alpn; QList<QString> pinnedPeerCertificateChainSha256; QList<CertificateObject> certificates; JSONSTRUCT_COMPARE(TLSObject, serverName, allowInsecure, enableSessionResumption, disableSystemRoot, alpn, pinnedPeerCertificateChainSha256, certificates) JSONSTRUCT_REGISTER(TLSObject, F(serverName, allowInsecure, enableSessionResumption, disableSystemRoot, alpn, pinnedPeerCertificateChainSha256, certificates)) }; // // struct XTLSObject { QString serverName; bool allowInsecure = false; bool enableSessionResumption = false; bool disableSystemRoot = false; QList<QString> alpn; QList<CertificateObject> certificates; JSONSTRUCT_COMPARE(XTLSObject, serverName, allowInsecure, enableSessionResumption, disableSystemRoot, alpn, certificates) JSONSTRUCT_REGISTER(XTLSObject, F(serverName, allowInsecure, enableSessionResumption, disableSystemRoot, alpn, certificates)) }; } // namespace transfer // // struct StreamSettingsObject { QString network = "tcp"; QString security = "none"; transfer::SockoptObject sockopt; transfer::TLSObject tlsSettings; transfer::XTLSObject xtlsSettings; transfer::TCPObject tcpSettings; transfer::KCPObject kcpSettings; transfer::WebSocketObject wsSettings; transfer::HttpObject httpSettings; transfer::DomainSocketObject dsSettings; transfer::QuicObject quicSettings; transfer::gRPCObject grpcSettings; JSONSTRUCT_COMPARE(StreamSettingsObject, network, security, sockopt, // tcpSettings, tlsSettings, xtlsSettings, kcpSettings, wsSettings, httpSettings, dsSettings, quicSettings, grpcSettings) JSONSTRUCT_REGISTER(StreamSettingsObject, F(network, security, sockopt), F(tcpSettings, tlsSettings, xtlsSettings, kcpSettings, wsSettings, httpSettings, dsSettings, quicSettings, grpcSettings)) }; struct FakeDNSObject { QString ipPool = "198.18.0.0/15"; int poolSize = 65535; JSONSTRUCT_REGISTER(FakeDNSObject, A(ipPool, poolSize)) JSONSTRUCT_COMPARE(FakeDNSObject, ipPool, poolSize) }; // // Some protocols from: https://v2ray.com/chapter_02/02_protocols.html namespace protocol { // // VMess Server constexpr auto VMESS_USER_ALTERID_DEFAULT = 0; struct VMessServerObject { struct UserObject { QString id; int alterId = VMESS_USER_ALTERID_DEFAULT; QString security = "auto"; int level = 0; JSONSTRUCT_COMPARE(UserObject, id, alterId, security, level) JSONSTRUCT_REGISTER(UserObject, F(id, alterId, security, level)) }; QString address; int port; QList<UserObject> users; JSONSTRUCT_COMPARE(VMessServerObject, address, port, users) JSONSTRUCT_REGISTER(VMessServerObject, F(address, port, users)) }; // // ShadowSocks Server struct ShadowSocksServerObject { QString address; QString method; QString password; int port; JSONSTRUCT_COMPARE(ShadowSocksServerObject, address, method, password) JSONSTRUCT_REGISTER(ShadowSocksServerObject, F(address, port, method, password)) }; } // namespace protocol } // namespace Qv2ray::base::objects
15,413
C++
.h
392
27.678571
175
0.557658
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,324
QvConfigIdentifier.hpp
Qv2ray_Qv2ray/src/base/models/QvConfigIdentifier.hpp
#pragma once #include "3rdparty/QJsonStruct/QJsonStruct.hpp" #include "QvCoreSettings.hpp" #include <QHash> #include <QHashFunctions> #include <QString> #include <QtCore> namespace Qv2ray::base { template<typename T> class IDType { public: explicit IDType() : m_id("null"){}; explicit IDType(const QString &id) : m_id(id){}; friend bool operator==(const IDType<T> &lhs, const IDType<T> &rhs) { return lhs.m_id == rhs.m_id; } friend bool operator!=(const IDType<T> &lhs, const IDType<T> &rhs) { return lhs.m_id != rhs.m_id; } const QString toString() const { return m_id; } void loadJson(const QJsonValue &d) { m_id = d.toString("null"); } QJsonValue toJson() const { return m_id; } private: QString m_id; }; // Define several safetypes to prevent misuse of QString. #define DECL_IDTYPE(type) \ class __##type; \ typedef IDType<__##type> type DECL_IDTYPE(GroupId); DECL_IDTYPE(ConnectionId); DECL_IDTYPE(GroupRoutingId); inline const static ConnectionId NullConnectionId; inline const static GroupId NullGroupId; inline const static GroupRoutingId NullRoutingId; class ConnectionGroupPair { public: ConnectionGroupPair() : connectionId(NullConnectionId), groupId(NullGroupId){}; ConnectionGroupPair(const ConnectionId &conn, const GroupId &group) : connectionId(conn), groupId(group){}; Q_PROPERTY(ConnectionId connectionId MEMBER) Q_PROPERTY(GroupId groupId MEMBER) // ConnectionId connectionId = NullConnectionId; GroupId groupId = NullGroupId; public slots: void clear() { connectionId = NullConnectionId; groupId = NullGroupId; } public: bool isEmpty() const { return groupId == NullGroupId || connectionId == NullConnectionId; } bool operator==(const ConnectionGroupPair &rhs) const { return groupId == rhs.groupId && connectionId == rhs.connectionId; } bool operator!=(const ConnectionGroupPair &rhs) const { return !(*this == rhs); } JSONSTRUCT_REGISTER(ConnectionGroupPair, F(connectionId, groupId)) }; constexpr unsigned int LATENCY_TEST_VALUE_ERROR = 99999; constexpr unsigned int LATENCY_TEST_VALUE_NODATA = LATENCY_TEST_VALUE_ERROR - 1; using namespace std::chrono; struct __Qv2rayConfigObjectBase { QString displayName; qint64 creationDate = system_clock::to_time_t(system_clock::now()); qint64 lastUpdatedDate = system_clock::to_time_t(system_clock::now()); JSONSTRUCT_REGISTER(__Qv2rayConfigObjectBase, F(displayName, creationDate, lastUpdatedDate)) }; struct GroupRoutingConfig : __Qv2rayConfigObjectBase { bool overrideDNS = false; config::QvConfig_DNS dnsConfig; config::QvConfig_FakeDNS fakeDNSConfig; // bool overrideRoute = false; config::QvConfig_Route routeConfig; // bool overrideConnectionConfig = false; config::QvConfig_Connection connectionConfig; // bool overrideForwardProxyConfig = false; config::QvConfig_ForwardProxy forwardProxyConfig; // JSONSTRUCT_COMPARE(GroupRoutingConfig, // overrideDNS, dnsConfig, fakeDNSConfig, // overrideRoute, routeConfig, // overrideConnectionConfig, connectionConfig, // overrideForwardProxyConfig, forwardProxyConfig) JSONSTRUCT_REGISTER(GroupRoutingConfig, // F(overrideRoute, routeConfig), // F(overrideDNS, dnsConfig, fakeDNSConfig), // F(overrideConnectionConfig, connectionConfig), // F(overrideForwardProxyConfig, forwardProxyConfig)) }; enum SubscriptionFilterRelation { RELATION_AND = 0, RELATION_OR = 1 }; struct SubscriptionConfigObject { QString address; QString type = "sip008"; float updateInterval = 10; QList<QString> IncludeKeywords; QList<QString> ExcludeKeywords; SubscriptionFilterRelation IncludeRelation = RELATION_OR; SubscriptionFilterRelation ExcludeRelation = RELATION_AND; JSONSTRUCT_COMPARE(SubscriptionConfigObject, address, type, updateInterval, // IncludeKeywords, ExcludeKeywords, IncludeRelation, ExcludeRelation) JSONSTRUCT_REGISTER(SubscriptionConfigObject, F(updateInterval, address, type), F(IncludeRelation, ExcludeRelation, IncludeKeywords, ExcludeKeywords)) }; struct GroupObject : __Qv2rayConfigObjectBase { bool isSubscription = false; QList<ConnectionId> connections; GroupRoutingId routeConfigId; SubscriptionConfigObject subscriptionOption; GroupObject() : __Qv2rayConfigObjectBase(){}; JSONSTRUCT_COMPARE(GroupObject, isSubscription, connections, routeConfigId, subscriptionOption) JSONSTRUCT_REGISTER(GroupObject, F(connections, isSubscription, routeConfigId, subscriptionOption), B(__Qv2rayConfigObjectBase)) }; enum StatisticsType { API_INBOUND = 0, API_OUTBOUND_PROXY = 1, API_OUTBOUND_DIRECT = 2, API_OUTBOUND_BLACKHOLE = 3, }; typedef long qvspeed; typedef quint64 qvdata; typedef std::pair<qvspeed, qvspeed> QvStatsSpeed; typedef std::pair<qvdata, qvdata> QvStatsData; typedef std::pair<QvStatsSpeed, QvStatsData> QvStatsSpeedData; struct ConnectionStatsEntryObject { qvdata upLinkData; qvdata downLinkData; QvStatsData toData() { return { upLinkData, downLinkData }; } void fromData(const QvStatsData &d) { upLinkData = d.first; downLinkData = d.second; } JSONSTRUCT_REGISTER(ConnectionStatsEntryObject, F(upLinkData, downLinkData)) }; enum ConnectionImportSource { IMPORT_SOURCE_SUBSCRIPTION, IMPORT_SOURCE_MANUAL }; struct ConnectionStatsObject { ConnectionStatsEntryObject &operator[](StatisticsType i) { while (entries.count() <= i) entries.append(ConnectionStatsEntryObject{}); return entries[i]; } QJsonValue toJson() const { return JsonStructHelper::Serialize(entries); } friend bool operator==(const ConnectionStatsObject &left, const ConnectionStatsObject &right) { return left.toJson() == right.toJson(); } void loadJson(const QJsonValue &d) { JsonStructHelper::Deserialize(entries, d); } void Clear() { entries.clear(); } private: QList<ConnectionStatsEntryObject> entries; }; struct ConnectionObject : __Qv2rayConfigObjectBase { qint64 lastConnected; qint64 latency = LATENCY_TEST_VALUE_NODATA; ConnectionImportSource importSource = IMPORT_SOURCE_MANUAL; ConnectionStatsObject stats; // int __qvConnectionRefCount = 0; JSONSTRUCT_COMPARE(ConnectionObject, lastConnected, latency, importSource, stats, displayName, creationDate, lastUpdatedDate) JSONSTRUCT_REGISTER(ConnectionObject, F(lastConnected, latency, importSource, stats), B(__Qv2rayConfigObjectBase)) }; struct ProtocolSettingsInfoObject { QString protocol; QString address; int port; ProtocolSettingsInfoObject(){}; ProtocolSettingsInfoObject(const QString &_protocol, const QString _address, int _port) : protocol(_protocol), // address(_address), // port(_port) // {}; JSONSTRUCT_REGISTER(ProtocolSettingsInfoObject, F(protocol, address, port)) }; template<typename T> inline size_t qHash(IDType<T> key) { return ::qHash(key.toString()); } inline size_t qHash(const Qv2ray::base::ConnectionGroupPair &pair) { return ::qHash(pair.connectionId.toString() + pair.groupId.toString()); } } // namespace Qv2ray::base using namespace Qv2ray::base; Q_DECLARE_METATYPE(ConnectionGroupPair) Q_DECLARE_METATYPE(ConnectionId) Q_DECLARE_METATYPE(GroupId) Q_DECLARE_METATYPE(GroupRoutingId) Q_DECLARE_METATYPE(QvStatsSpeed) Q_DECLARE_METATYPE(QvStatsData) Q_DECLARE_METATYPE(QvStatsSpeedData) Q_DECLARE_METATYPE(StatisticsType)
9,228
C++
.h
246
28.922764
150
0.61925
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,325
QvCoreSettings.hpp
Qv2ray_Qv2ray/src/base/models/QvCoreSettings.hpp
#pragma once #include "QJsonStruct.hpp" #include "base/models/CoreObjectModels.hpp" namespace Qv2ray::base::config { struct QvConfig_Route { struct QvRouteConfig_Impl { QList<QString> direct; QList<QString> block; QList<QString> proxy; QvRouteConfig_Impl(){}; QvRouteConfig_Impl(const QList<QString> &_direct, const QList<QString> &_block, const QList<QString> &_proxy) : direct(_direct), block(_block), proxy(_proxy){}; JSONSTRUCT_COMPARE(QvRouteConfig_Impl, direct, block, proxy) JSONSTRUCT_REGISTER(QvRouteConfig_Impl, F(proxy, block, direct)) }; QString domainStrategy; QString domainMatcher = "mph"; QvRouteConfig_Impl domains; QvRouteConfig_Impl ips; QvConfig_Route(){}; QvConfig_Route(const QvRouteConfig_Impl &_domains, const QvRouteConfig_Impl &_ips, const QString &ds) : domainStrategy(ds), domains(_domains), ips(_ips){}; JSONSTRUCT_COMPARE(QvConfig_Route, domainStrategy, domainMatcher, domains, ips) JSONSTRUCT_REGISTER(QvConfig_Route, A(domainStrategy, domainMatcher, domains, ips)) }; using QvConfig_DNS = objects::DNSObject; using QvConfig_FakeDNS = objects::FakeDNSObject; struct QvConfig_Outbounds { int mark = 255; JSONSTRUCT_COMPARE(QvConfig_Outbounds, mark) JSONSTRUCT_REGISTER(QvConfig_Outbounds, F(mark)) }; struct QvConfig_ForwardProxy { bool enableForwardProxy = false; QString type = "http"; QString serverAddress = ""; int port = 0; bool useAuth = false; QString username = ""; QString password = ""; JSONSTRUCT_COMPARE(QvConfig_ForwardProxy, enableForwardProxy, type, serverAddress, port, useAuth, username, password) JSONSTRUCT_REGISTER(QvConfig_ForwardProxy, F(enableForwardProxy, type, serverAddress, port, useAuth, username, password)) }; struct QvConfig_Connection { bool enableProxy = true; bool bypassCN = true; bool bypassBT = false; bool bypassLAN = true; bool v2rayFreedomDNS = false; bool dnsIntercept = false; JSONSTRUCT_COMPARE(QvConfig_Connection, enableProxy, // bypassCN, bypassBT, bypassLAN, // v2rayFreedomDNS, dnsIntercept) JSONSTRUCT_REGISTER(QvConfig_Connection, F(bypassCN, bypassBT, bypassLAN, enableProxy, v2rayFreedomDNS, dnsIntercept)) }; struct QvConfig_SystemProxy { bool setSystemProxy = true; JSONSTRUCT_COMPARE(QvConfig_SystemProxy, setSystemProxy) JSONSTRUCT_REGISTER(QvConfig_SystemProxy, F(setSystemProxy)) }; struct Qv2rayConfig_ProtocolInboundBase { int port = 0; bool useAuth = false; bool sniffing = false; QList<QString> destOverride = { "http", "tls" }; objects::AccountObject account; bool metadataOnly = true; Qv2rayConfig_ProtocolInboundBase(){}; JSONSTRUCT_REGISTER(Qv2rayConfig_ProtocolInboundBase, F(port, useAuth, sniffing, destOverride, account, metadataOnly)) }; struct QvConfig_SocksInbound : Qv2rayConfig_ProtocolInboundBase { bool enableUDP = true; QString localIP = "127.0.0.1"; QvConfig_SocksInbound() : Qv2rayConfig_ProtocolInboundBase() { port = 1089; } JSONSTRUCT_COMPARE(QvConfig_SocksInbound, enableUDP, localIP, port, useAuth, sniffing, destOverride, metadataOnly) JSONSTRUCT_REGISTER(QvConfig_SocksInbound, B(Qv2rayConfig_ProtocolInboundBase), F(enableUDP, localIP)) }; struct QvConfig_HttpInbound : Qv2rayConfig_ProtocolInboundBase { QvConfig_HttpInbound() : Qv2rayConfig_ProtocolInboundBase() { port = 8889; } JSONSTRUCT_COMPARE(QvConfig_HttpInbound, port, useAuth, sniffing, destOverride, metadataOnly) JSONSTRUCT_REGISTER(QvConfig_HttpInbound, B(Qv2rayConfig_ProtocolInboundBase)) }; struct QvConfig_TProxy : Qv2rayConfig_ProtocolInboundBase { QString tProxyIP = "127.0.0.1"; QString tProxyV6IP = "::1"; bool hasTCP = true; bool hasUDP = true; QString mode = "tproxy"; QvConfig_TProxy() : Qv2rayConfig_ProtocolInboundBase() { port = 12345; sniffing = true; } JSONSTRUCT_COMPARE(QvConfig_TProxy, tProxyIP, tProxyV6IP, hasTCP, hasUDP, mode, port, useAuth, sniffing, destOverride, metadataOnly) JSONSTRUCT_REGISTER(QvConfig_TProxy, B(Qv2rayConfig_ProtocolInboundBase), F(tProxyIP, tProxyV6IP, hasTCP, hasUDP, mode)) }; struct QvConfig_BrowserForwarder { QString address = "127.0.0.1"; int port = 8088; QvConfig_BrowserForwarder() {} JSONSTRUCT_COMPARE(QvConfig_BrowserForwarder, address, port) JSONSTRUCT_REGISTER(QvConfig_BrowserForwarder, F(address, port)) }; struct QvConfig_Inbounds { QString listenip = "127.0.0.1"; bool useSocks = true; bool useHTTP = true; bool useTPROXY = false; // QvConfig_TProxy tProxySettings; QvConfig_HttpInbound httpSettings; QvConfig_SocksInbound socksSettings; QvConfig_SystemProxy systemProxySettings; QvConfig_BrowserForwarder browserForwarderSettings; // JSONSTRUCT_COMPARE(QvConfig_Inbounds, listenip, useSocks, useHTTP, useTPROXY, tProxySettings, httpSettings, socksSettings, systemProxySettings, browserForwarderSettings); JSONSTRUCT_REGISTER(QvConfig_Inbounds, // A(socksSettings), // F(listenip, useSocks, useHTTP, useTPROXY), // F(tProxySettings, httpSettings, systemProxySettings, browserForwarderSettings)); }; } // namespace Qv2ray::base::config
6,070
C++
.h
142
33.746479
140
0.653137
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,326
QvRuntimeConfig.hpp
Qv2ray_Qv2ray/src/base/models/QvRuntimeConfig.hpp
#pragma once #define SET_RUNTIME_CONFIG(conf, val) RuntimeConfig.conf = val(); #define RESTORE_RUNTIME_CONFIG(conf, func) func(RuntimeConfig.conf); namespace Qv2ray::base { struct Qv2rayRuntimeConfig { bool screenShotHideQv2ray = false; }; inline base::Qv2rayRuntimeConfig RuntimeConfig = base::Qv2rayRuntimeConfig(); } // namespace Qv2ray::base
372
C++
.h
11
30.454545
81
0.754875
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
4,327
QvComplexConfigModels.hpp
Qv2ray_Qv2ray/src/base/models/QvComplexConfigModels.hpp
#pragma once #include "CoreObjectModels.hpp" #include "QvConfigIdentifier.hpp" #include "QvSafeType.hpp" namespace Qv2ray::base::objects::complex { /***************************************************************** * ROOT * | Original Structures * | ====================== * | - Inbounds * | - Routing Rules * | - DNS / * | * | Qv2ray-only structures * | ====================== * | * | - Outbounds * | | * | | - OUTBOUND * | | - Original Outbound Object * | | ========================================== * | | - "QV2RAY_OUTBOUND_METADATA" -> OutboundObjectMeta * | | - realOutbound -> OUTBOUND A.K.A ref<OUTBOUND> * | | - chainId -> ChainID * | | - object -> OutboundObject * | | - metaType -> MetaOutboundObjectType * | | - ORIGINAL -> Enables realOutbound * | | - EXTERNAL -> Enables connectionId * | | - CHAINED -> Enables chainId * | | - BALANCER -> ? * | * *******************************************************************/ enum ComplexTagNodeMode { NODE_INBOUND, NODE_OUTBOUND, NODE_RULE }; enum MetaOutboundObjectType { METAOUTBOUND_ORIGINAL, METAOUTBOUND_EXTERNAL, METAOUTBOUND_BALANCER, METAOUTBOUND_CHAIN }; constexpr auto META_OUTBOUND_KEY_NAME = "QV2RAY_OUTBOUND_METADATA"; constexpr auto QV2RAY_CHAINED_OUTBOUND_PORT_ALLOCATION = 15500; typedef BalancerObject ComplexBalancerObject; struct OutboundObjectMeta { MetaOutboundObjectType metaType; QString displayName; // ConnectionId connectionId; QList<QString> outboundTags; QString strategyType; int chainPortAllocation = QV2RAY_CHAINED_OUTBOUND_PORT_ALLOCATION; // safetype::OUTBOUND realOutbound; QString getDisplayName() const { if (metaType == METAOUTBOUND_ORIGINAL) return realOutbound["tag"].toString(); else return displayName; } static OutboundObjectMeta loadFromOutbound(const safetype::OUTBOUND &out) { OutboundObjectMeta meta; meta.loadJson(out[META_OUTBOUND_KEY_NAME].toObject()); meta.realOutbound = out; return meta; } OutboundObjectMeta() : metaType(METAOUTBOUND_ORIGINAL){}; JSONSTRUCT_REGISTER(OutboundObjectMeta, F(metaType, displayName, connectionId, outboundTags, chainPortAllocation, strategyType)) }; inline OutboundObjectMeta make_chained_outbound(const QList<QString> &chain, const QString &tag) { OutboundObjectMeta meta; meta.metaType = METAOUTBOUND_CHAIN; meta.outboundTags = chain; meta.displayName = tag; return meta; } inline OutboundObjectMeta make_balancer_outbound(const QList<QString> &outbounds, const QString &type, const QString &tag) { OutboundObjectMeta meta; meta.metaType = METAOUTBOUND_BALANCER; meta.outboundTags = outbounds; meta.strategyType = type; meta.displayName = tag; return meta; } inline OutboundObjectMeta make_external_outbound(const ConnectionId &id, const QString &tag) { OutboundObjectMeta meta; meta.metaType = METAOUTBOUND_EXTERNAL; meta.connectionId = id; meta.displayName = tag; return meta; } inline OutboundObjectMeta make_normal_outbound(const safetype::OUTBOUND &outbound) { OutboundObjectMeta meta; meta.metaType = METAOUTBOUND_ORIGINAL; meta.realOutbound = outbound; meta.displayName = outbound["tag"].toString(); return meta; } } // namespace Qv2ray::base::objects::complex using namespace Qv2ray::base::objects::complex;
4,220
C++
.h
113
30.053097
136
0.547253
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,328
QvSettingsObject.hpp
Qv2ray_Qv2ray/src/base/models/QvSettingsObject.hpp
#pragma once #include "base/models/QvConfigIdentifier.hpp" #include "base/models/QvCoreSettings.hpp" #include "base/models/QvSafeType.hpp" #include <chrono> constexpr int QV2RAY_CONFIG_VERSION = 14; namespace Qv2ray::base::config { struct QvGraphPenConfig { int R = 150, G = 150, B = 150; float width = 1.5f; Qt::PenStyle style = Qt::SolidLine; QvGraphPenConfig(){}; QvGraphPenConfig(int R, int G, int B, float w, Qt::PenStyle s) { this->R = R; this->G = G; this->B = B; this->width = w; this->style = s; }; friend bool operator==(const QvGraphPenConfig &one, const QvGraphPenConfig &another) { return one.R == another.R && one.G == another.G && one.B == another.B && one.width == another.width && one.style == another.style; } JSONSTRUCT_REGISTER(QvGraphPenConfig, F(R, G, B, width, style)) }; struct Qv2rayConfig_Graph { bool useOutboundStats = true; bool hasDirectStats = true; safetype::QvEnumMap<StatisticsType, safetype::QvPair<QvGraphPenConfig>> colorConfig; JSONSTRUCT_COMPARE(Qv2rayConfig_Graph, useOutboundStats, hasDirectStats, colorConfig) JSONSTRUCT_REGISTER(Qv2rayConfig_Graph, F(useOutboundStats, hasDirectStats, colorConfig)) const static inline QvPair<QvGraphPenConfig> DefaultPen{ { 134, 196, 63, 1.5f, Qt::SolidLine }, { 50, 153, 255, 1.5f, Qt::SolidLine } }; const static inline QvPair<QvGraphPenConfig> DirectPen{ { 0, 210, 240, 1.5f, Qt::DotLine }, { 235, 220, 42, 1.5f, Qt::DotLine } }; }; struct Qv2rayConfig_UI { #ifdef Q_OS_WIN QString theme = "windowsvista"; #elif defined(Q_OS_MACOS) QString theme = "macintosh"; #else QString theme = "Fusion"; #endif QString language = "en_US"; QList<ConnectionGroupPair> recentConnections; Qv2rayConfig_Graph graphConfig; bool quietMode = false; bool useDarkTheme = false; bool useGlyphTrayIcon = true; bool useDarkTrayIcon = false; int maximumLogLines = 500; int maxJumpListCount = 20; bool useOldShareLinkFormat = false; bool startMinimized = true; bool exitByCloseEvent = false; JSONSTRUCT_COMPARE(Qv2rayConfig_UI, theme, language, quietMode, graphConfig, useDarkTheme, useDarkTrayIcon, useGlyphTrayIcon, maximumLogLines, maxJumpListCount, recentConnections, useOldShareLinkFormat, startMinimized, exitByCloseEvent) JSONSTRUCT_REGISTER(Qv2rayConfig_UI, F(theme, language, quietMode, graphConfig, useDarkTheme, useDarkTrayIcon, useGlyphTrayIcon, maximumLogLines, maxJumpListCount, recentConnections, useOldShareLinkFormat, startMinimized, exitByCloseEvent)) }; struct Qv2rayConfig_Plugin { QMap<QString, bool> pluginStates; bool v2rayIntegration = true; int portAllocationStart = 15000; JSONSTRUCT_COMPARE(Qv2rayConfig_Plugin, pluginStates, v2rayIntegration, portAllocationStart) JSONSTRUCT_REGISTER(Qv2rayConfig_Plugin, F(pluginStates, v2rayIntegration, portAllocationStart)) }; struct Qv2rayConfig_Kernel { bool enableAPI = true; int statsPort = 15490; // QString v2CorePath_linux; QString v2AssetsPath_linux; QString v2CorePath_macx; QString v2AssetsPath_macx; QString v2CorePath_win; QString v2AssetsPath_win; #ifdef Q_OS_LINUX #define _VARNAME_VCOREPATH_ v2CorePath_linux #define _VARNAME_VASSETSPATH_ v2AssetsPath_linux #elif defined(Q_OS_MACOS) #define _VARNAME_VCOREPATH_ v2CorePath_macx #define _VARNAME_VASSETSPATH_ v2AssetsPath_macx #elif defined(Q_OS_WIN) #define _VARNAME_VCOREPATH_ v2CorePath_win #define _VARNAME_VASSETSPATH_ v2AssetsPath_win #endif inline const QString KernelPath(const QString &path = "") { return path.isEmpty() ? _VARNAME_VCOREPATH_ : _VARNAME_VCOREPATH_ = path; } inline const QString AssetsPath(const QString &path = "") { return path.isEmpty() ? _VARNAME_VASSETSPATH_ : _VARNAME_VASSETSPATH_ = path; } #undef _VARNAME_VCOREPATH_ #undef _VARNAME_VASSETSPATH_ JSONSTRUCT_COMPARE(Qv2rayConfig_Kernel, enableAPI, statsPort, // v2CorePath_linux, v2AssetsPath_linux, // v2CorePath_macx, v2AssetsPath_macx, // v2CorePath_win, v2AssetsPath_win) JSONSTRUCT_REGISTER(Qv2rayConfig_Kernel, // F(enableAPI, statsPort), // F(v2CorePath_linux, v2AssetsPath_linux), // F(v2CorePath_macx, v2AssetsPath_macx), // F(v2CorePath_win, v2AssetsPath_win)) }; struct Qv2rayConfig_Update { enum UpdateChannel { CHANNEL_STABLE = 0, CHANNEL_TESTING = 1 }; UpdateChannel updateChannel = CHANNEL_STABLE; QString ignoredVersion; JSONSTRUCT_COMPARE(Qv2rayConfig_Update, updateChannel, ignoredVersion) JSONSTRUCT_REGISTER(Qv2rayConfig_Update, F(ignoredVersion, updateChannel)) }; struct Qv2rayConfig_Advanced { bool testLatencyPeriodically = false; bool disableSystemRoot = false; bool testLatencyOnConnected = false; JSONSTRUCT_COMPARE(Qv2rayConfig_Advanced, testLatencyPeriodically, disableSystemRoot, testLatencyOnConnected) JSONSTRUCT_REGISTER(Qv2rayConfig_Advanced, F(testLatencyPeriodically, disableSystemRoot, testLatencyOnConnected)) }; enum Qv2rayLatencyTestingMethod { TCPING = 0, ICMPING = 1, REALPING = 2 }; struct Qv2rayConfig_Network { enum Qv2rayProxyType { QVPROXY_NONE = 0, QVPROXY_SYSTEM = 1, QVPROXY_CUSTOM = 2 }; Qv2rayLatencyTestingMethod latencyTestingMethod = TCPING; QString latencyRealPingTestURL = "https://www.google.com"; Qv2rayProxyType proxyType = QVPROXY_NONE; QString address = "127.0.0.1"; QString type = "http"; int port = 8000; QString userAgent = "Qv2ray/$VERSION WebRequestHelper"; JSONSTRUCT_COMPARE(Qv2rayConfig_Network, latencyTestingMethod, latencyRealPingTestURL, proxyType, type, address, port, userAgent) JSONSTRUCT_REGISTER(Qv2rayConfig_Network, F(latencyTestingMethod, latencyRealPingTestURL, proxyType, type, address, port, userAgent)) }; enum Qv2rayAutoConnectionBehavior { AUTO_CONNECTION_NONE = 0, AUTO_CONNECTION_FIXED = 1, AUTO_CONNECTION_LAST_CONNECTED = 2 }; struct Qv2rayConfigObject { int config_version; int logLevel = 0; // ConnectionGroupPair autoStartId; ConnectionGroupPair lastConnectedId; Qv2rayAutoConnectionBehavior autoStartBehavior = AUTO_CONNECTION_NONE; // Qv2rayConfig_UI uiConfig; Qv2rayConfig_Plugin pluginConfig; Qv2rayConfig_Kernel kernelConfig; Qv2rayConfig_Update updateConfig; Qv2rayConfig_Network networkConfig; QvConfig_Inbounds inboundConfig; QvConfig_Outbounds outboundConfig; Qv2rayConfig_Advanced advancedConfig; GroupRoutingConfig defaultRouteConfig; explicit Qv2rayConfigObject() { config_version = QV2RAY_CONFIG_VERSION; } #if QT_VERSION < QT_VERSION_CHECK(5, 13, 0) Q_DISABLE_COPY(Qv2rayConfigObject); #else Q_DISABLE_COPY_MOVE(Qv2rayConfigObject); #endif JSONSTRUCT_COMPARE(Qv2rayConfigObject, config_version, logLevel, autoStartId, lastConnectedId, autoStartBehavior, uiConfig, pluginConfig, kernelConfig, updateConfig, networkConfig, inboundConfig, outboundConfig, advancedConfig, defaultRouteConfig) JSONSTRUCT_REGISTER_NOCOPYMOVE(Qv2rayConfigObject, // A(config_version, autoStartId, lastConnectedId, autoStartBehavior, logLevel), // A(uiConfig, advancedConfig, pluginConfig, updateConfig, kernelConfig, networkConfig), // A(inboundConfig, outboundConfig, defaultRouteConfig)) }; } // namespace Qv2ray::base::config
8,614
C++
.h
198
34.373737
158
0.651661
Qv2ray/Qv2ray
16,635
3,255
47
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,359
MockAudioObjects.cpp
kyleneideck_BackgroundMusic/BGMApp/BGMAppTests/UnitTests/Mocks/MockAudioObjects.cpp
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // MockAudioObjects.cpp // BGMAppUnitTests // // Copyright © 2020 Kyle Neideck // // Self Include #include "MockAudioObjects.h" // PublicUtility Includes #include "CACFString.h" // static MockAudioObjects::MockDeviceMap MockAudioObjects::sDevices; // static MockAudioObjects::MockDeviceMapByUID MockAudioObjects::sDevicesByUID; // static std::shared_ptr<MockAudioDevice> MockAudioObjects::CreateMockDevice(const std::string& inUID) { std::shared_ptr<MockAudioDevice> mockDevice = std::make_shared<MockAudioDevice>(inUID); sDevices.insert(MockDeviceMap::value_type(mockDevice->GetObjectID(), mockDevice)); sDevicesByUID.insert(MockDeviceMapByUID::value_type(inUID, mockDevice)); return mockDevice; } // static void MockAudioObjects::DestroyMocks() { sDevices.clear(); } // static std::shared_ptr<MockAudioObject> MockAudioObjects::GetAudioObject(AudioObjectID inAudioObjectID) { auto device = GetAudioDeviceOrNull(inAudioObjectID); if(device) { return device; } // Devices are the only audio objects we currently mock. // Tests have to create mocks for all of the audio objects they expect the code they test to // access. They should fail if it accesses any others. throw "Mock audio object not found."; } // static std::shared_ptr<MockAudioDevice> MockAudioObjects::GetAudioDevice(AudioObjectID inAudioObjectID) { auto device = GetAudioDeviceOrNull(inAudioObjectID); if(device) { return device; } // Tests have to create mocks for all of the audio devices they expect the code they test to // access. They should fail if it accesses any others. throw "Mock audio device not found."; } // static std::shared_ptr<MockAudioDevice> MockAudioObjects::GetAudioDevice(CFStringRef inUID) { // Convert inUID to a std::string. UInt32 uidCStringLen = CACFString::GetStringByteLength(inUID) + 1; char uidCString[uidCStringLen]; CACFString::GetCString(inUID, uidCString, uidCStringLen); std::string uid = std::string(uidCString); return GetAudioDevice(uid); } // static std::shared_ptr<MockAudioDevice> MockAudioObjects::GetAudioDevice(const std::string& inUID) { auto device = sDevicesByUID.find(inUID); if(device != sDevicesByUID.end()) { return device->second; } return nullptr; } // static std::shared_ptr<MockAudioDevice> MockAudioObjects::GetAudioDeviceOrNull(AudioObjectID inAudioObjectID) { auto device = sDevices.find(inAudioObjectID); if(device != sDevices.end()) { return device->second; } return nullptr; }
3,317
C++
.cpp
97
31.113402
96
0.756418
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
4,360
MockAudioDevice.cpp
kyleneideck_BackgroundMusic/BGMApp/BGMAppTests/UnitTests/Mocks/MockAudioDevice.cpp
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // MockAudioDevice.cpp // BGMAppUnitTests // // Copyright © 2020 Kyle Neideck // // Self Include #include "MockAudioDevice.h" // BGM Includes #include "BGM_Types.h" // STL Includes #include <functional> MockAudioDevice::MockAudioDevice(const std::string& inUID) : mUID(inUID), mNominalSampleRate(44100.0), mIOBufferSize(512), MockAudioObject(static_cast<AudioObjectID>(std::hash<std::string>{}(inUID))) { } CACFString MockAudioDevice::GetPlayerBundleID() const { if(mUID != kBGMDeviceUID) { throw "Only BGMDevice has kAudioDeviceCustomPropertyMusicPlayerBundleID"; } return mPlayerBundleID; } void MockAudioDevice::SetPlayerBundleID(const CACFString& inPlayerBundleID) { if(mUID != kBGMDeviceUID) { throw "Only BGMDevice has kAudioDeviceCustomPropertyMusicPlayerBundleID"; } mPlayerBundleID = inPlayerBundleID; }
1,596
C++
.cpp
50
29.42
81
0.761564
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
4,361
Mock_CAHALAudioObject.cpp
kyleneideck_BackgroundMusic/BGMApp/BGMAppTests/UnitTests/Mocks/Mock_CAHALAudioObject.cpp
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // Mock_CAHALAudioObject.cpp // BGMAppUnitTests // // Copyright © 2016, 2020 Kyle Neideck // // Self Include #include "CAHALAudioObject.h" // Local Includes #include "MockAudioObjects.h" // BGM Includes #include "BGM_Types.h" // PublicUtility Includes #include "CACFString.h" #pragma clang diagnostic ignored "-Wunused-parameter" CAHALAudioObject::CAHALAudioObject(AudioObjectID inObjectID) : mObjectID(inObjectID) { } CAHALAudioObject::~CAHALAudioObject() { } AudioObjectID CAHALAudioObject::GetObjectID() const { return mObjectID; } void CAHALAudioObject::GetPropertyData(const AudioObjectPropertyAddress& inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32& ioDataSize, void* outData) const { switch(inAddress.mSelector) { case kAudioDeviceCustomPropertyMusicPlayerBundleID: *reinterpret_cast<CFStringRef*>(outData) = MockAudioObjects::GetAudioDevice(GetObjectID())-> GetPlayerBundleID().CopyCFString(); break; case kAudioDevicePropertyStreams: reinterpret_cast<AudioObjectID*>(outData)[0] = 1; if(inAddress.mScope == kAudioObjectPropertyScopeGlobal) { reinterpret_cast<AudioObjectID*>(outData)[1] = 2; } break; case kAudioDevicePropertyBufferFrameSize: *reinterpret_cast<UInt32*>(outData) = 512; break; case kAudioDevicePropertyDeviceIsAlive: *reinterpret_cast<UInt32*>(outData) = 1; break; case kAudioStreamPropertyVirtualFormat: { AudioStreamBasicDescription* outASBD = reinterpret_cast<AudioStreamBasicDescription*>(outData); outASBD->mSampleRate = 44100.0; outASBD->mFormatID = kAudioFormatLinearPCM; outASBD->mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked; outASBD->mBytesPerPacket = 8; outASBD->mFramesPerPacket = 1; outASBD->mBytesPerFrame = 8; outASBD->mChannelsPerFrame = 2; outASBD->mBitsPerChannel = 32; break; } default: Throw(new CAException(kAudio_UnimplementedError)); } } void CAHALAudioObject::SetPropertyData(const AudioObjectPropertyAddress& inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32 inDataSize, const void* inData) { switch(inAddress.mSelector) { case kAudioDeviceCustomPropertyMusicPlayerBundleID: MockAudioObjects::GetAudioDevice(GetObjectID())->SetPlayerBundleID( CACFString(*reinterpret_cast<const CFStringRef*>(inData), false)); break; default: break; } } UInt32 CAHALAudioObject::GetPropertyDataSize(const AudioObjectPropertyAddress& inAddress, UInt32 inQualifierDataSize, const void* inQualifierData) const { switch(inAddress.mSelector) { case kAudioDevicePropertyStreams: return (inAddress.mScope == kAudioObjectPropertyScopeGlobal ? 2 : 1) * sizeof(AudioObjectID); default: Throw(new CAException(kAudio_UnimplementedError)); } } void CAHALAudioObject::AddPropertyListener(const AudioObjectPropertyAddress& inAddress, AudioObjectPropertyListenerProc inListenerProc, void* inClientData) { MockAudioObjects::GetAudioObject(GetObjectID())-> mPropertiesWithListeners.insert(inAddress.mSelector); } void CAHALAudioObject::RemovePropertyListener(const AudioObjectPropertyAddress& inAddress, AudioObjectPropertyListenerProc inListenerProc, void* inClientData) { MockAudioObjects::GetAudioObject(GetObjectID())-> mPropertiesWithListeners.erase(inAddress.mSelector); } #pragma mark Unimplemented Methods void CAHALAudioObject::SetObjectID(AudioObjectID inObjectID) { Throw(new CAException(kAudio_UnimplementedError)); } AudioClassID CAHALAudioObject::GetClassID() const { Throw(new CAException(kAudio_UnimplementedError)); } AudioObjectID CAHALAudioObject::GetOwnerObjectID() const { Throw(new CAException(kAudio_UnimplementedError)); } CFStringRef CAHALAudioObject::CopyOwningPlugInBundleID() const { Throw(new CAException(kAudio_UnimplementedError)); } CFStringRef CAHALAudioObject::CopyName() const { Throw(new CAException(kAudio_UnimplementedError)); } CFStringRef CAHALAudioObject::CopyManufacturer() const { Throw(new CAException(kAudio_UnimplementedError)); } CFStringRef CAHALAudioObject::CopyNameForElement(AudioObjectPropertyScope inScope, AudioObjectPropertyElement inElement) const { Throw(new CAException(kAudio_UnimplementedError)); } CFStringRef CAHALAudioObject::CopyCategoryNameForElement(AudioObjectPropertyScope inScope, AudioObjectPropertyElement inElement) const { Throw(new CAException(kAudio_UnimplementedError)); } CFStringRef CAHALAudioObject::CopyNumberNameForElement(AudioObjectPropertyScope inScope, AudioObjectPropertyElement inElement) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioObject::ObjectExists(AudioObjectID inObjectID) { Throw(new CAException(kAudio_UnimplementedError)); } UInt32 CAHALAudioObject::GetNumberOwnedObjects(AudioClassID inClass) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioObject::GetAllOwnedObjects(AudioClassID inClass, UInt32& ioNumberObjects, AudioObjectID* ioObjectIDs) const { Throw(new CAException(kAudio_UnimplementedError)); } AudioObjectID CAHALAudioObject::GetOwnedObjectByIndex(AudioClassID inClass, UInt32 inIndex) { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioObject::HasProperty(const AudioObjectPropertyAddress& inAddress) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioObject::IsPropertySettable(const AudioObjectPropertyAddress& inAddress) const { Throw(new CAException(kAudio_UnimplementedError)); }
6,763
C++
.cpp
176
33.238636
181
0.757252
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
4,362
MockAudioObject.cpp
kyleneideck_BackgroundMusic/BGMApp/BGMAppTests/UnitTests/Mocks/MockAudioObject.cpp
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // MockAudioObject.cpp // BGMAppUnitTests // // Copyright © 2020 Kyle Neideck // // Self Include #include "MockAudioObject.h" MockAudioObject::MockAudioObject(AudioObjectID inAudioObjectID) : mAudioObjectID(inAudioObjectID) { } AudioObjectID MockAudioObject::GetObjectID() const { return mAudioObjectID; }
1,032
C++
.cpp
31
31.709677
75
0.775879
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
4,363
Mock_CAHALAudioDevice.cpp
kyleneideck_BackgroundMusic/BGMApp/BGMAppTests/UnitTests/Mocks/Mock_CAHALAudioDevice.cpp
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // Mock_CAHALAudioDevice.cpp // BGMAppUnitTests // // Copyright © 2020 Kyle Neideck // // Self Include #include "CAHALAudioDevice.h" // Local Includes #include "MockAudioDevice.h" #include "MockAudioObjects.h" // BGM Includes #include "BGM_Types.h" // PublicUtility Includes #include "CACFString.h" #include "CAHALAudioSystemObject.h" #include "CAPropertyAddress.h" #pragma clang diagnostic ignored "-Wunused-parameter" CAHALAudioDevice::CAHALAudioDevice(AudioObjectID inObjectID) : CAHALAudioObject(inObjectID) { } CAHALAudioDevice::CAHALAudioDevice(CFStringRef inUID) : CAHALAudioObject(CAHALAudioSystemObject().GetAudioDeviceForUID(inUID)) { } CAHALAudioDevice::~CAHALAudioDevice() { } void CAHALAudioDevice::GetCurrentVirtualFormats(bool inIsInput, UInt32& ioNumberStreams, AudioStreamBasicDescription* outFormats) const { ioNumberStreams = 1; CAPropertyAddress theAddress(kAudioStreamPropertyVirtualFormat); UInt32 theSize = sizeof(AudioStreamBasicDescription); GetPropertyData(theAddress, 0, NULL, theSize, outFormats); } UInt32 CAHALAudioDevice::GetIOBufferSize() const { return MockAudioObjects::GetAudioDevice(GetObjectID())->mIOBufferSize; } void CAHALAudioDevice::SetIOBufferSize(UInt32 inBufferSize) { MockAudioObjects::GetAudioDevice(GetObjectID())->mIOBufferSize = inBufferSize; } bool CAHALAudioDevice::IsAlive() const { return true; } AudioDeviceIOProcID CAHALAudioDevice::CreateIOProcID(AudioDeviceIOProc inIOProc, void* inClientData) { return reinterpret_cast<AudioDeviceIOProcID>(0x99990000); } void CAHALAudioDevice::DestroyIOProcID(AudioDeviceIOProcID inIOProcID) { } Float64 CAHALAudioDevice::GetNominalSampleRate() const { return MockAudioObjects::GetAudioDevice(GetObjectID())->mNominalSampleRate; } void CAHALAudioDevice::SetNominalSampleRate(Float64 inSampleRate) { MockAudioObjects::GetAudioDevice(GetObjectID())->mNominalSampleRate = inSampleRate; } CFStringRef CAHALAudioDevice::CopyDeviceUID() const { std::string uid = MockAudioObjects::GetAudioDevice(GetObjectID())->mUID; return CACFString(uid.c_str()).CopyCFString(); } #pragma mark Unimplemented Methods bool CAHALAudioDevice::HasModelUID() const { Throw(new CAException(kAudio_UnimplementedError)); } CFStringRef CAHALAudioDevice::CopyModelUID() const { Throw(new CAException(kAudio_UnimplementedError)); } CFStringRef CAHALAudioDevice::CopyConfigurationApplicationBundleID() const { Throw(new CAException(kAudio_UnimplementedError)); } CFURLRef CAHALAudioDevice::CopyIconLocation() const { Throw(new CAException(kAudio_UnimplementedError)); } UInt32 CAHALAudioDevice::GetTransportType() const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::CanBeDefaultDevice(bool inIsInput, bool inIsSystem) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::HasDevicePlugInStatus() const { Throw(new CAException(kAudio_UnimplementedError)); } OSStatus CAHALAudioDevice::GetDevicePlugInStatus() const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::IsHidden() const { Throw(new CAException(kAudio_UnimplementedError)); } pid_t CAHALAudioDevice::GetHogModeOwner() const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::IsHogModeSettable() const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::TakeHogMode() { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::ReleaseHogMode() { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::HasPreferredStereoChannels(bool inIsInput) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::GetPreferredStereoChannels(bool inIsInput, UInt32& outLeft, UInt32& outRight) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::SetPreferredStereoChannels(bool inIsInput, UInt32 inLeft, UInt32 inRight) { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::HasPreferredChannelLayout(bool inIsInput) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::GetPreferredChannelLayout(bool inIsInput, AudioChannelLayout& outChannelLayout) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::SetPreferredStereoChannels(bool inIsInput, AudioChannelLayout& inChannelLayout) { Throw(new CAException(kAudio_UnimplementedError)); } UInt32 CAHALAudioDevice::GetNumberRelatedAudioDevices() const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::GetRelatedAudioDevices(UInt32& ioNumberRelatedDevices, AudioObjectID* outRelatedDevices) const { Throw(new CAException(kAudio_UnimplementedError)); } AudioObjectID CAHALAudioDevice::GetRelatedAudioDeviceByIndex(UInt32 inIndex) const { Throw(new CAException(kAudio_UnimplementedError)); } UInt32 CAHALAudioDevice::GetNumberStreams(bool inIsInput) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::GetStreams(bool inIsInput, UInt32& ioNumberStreams, AudioObjectID* outStreamList) const { Throw(new CAException(kAudio_UnimplementedError)); } AudioObjectID CAHALAudioDevice::GetStreamByIndex(bool inIsInput, UInt32 inIndex) const { Throw(new CAException(kAudio_UnimplementedError)); } UInt32 CAHALAudioDevice::GetTotalNumberChannels(bool inIsInput) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::GetCurrentPhysicalFormats(bool inIsInput, UInt32& ioNumberStreams, AudioStreamBasicDescription* outFormats) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::IsRunning() const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::IsRunningSomewhere() const { Throw(new CAException(kAudio_UnimplementedError)); } UInt32 CAHALAudioDevice::GetLatency(bool inIsInput) const { Throw(new CAException(kAudio_UnimplementedError)); } UInt32 CAHALAudioDevice::GetSafetyOffset(bool inIsInput) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::HasClockDomain() const { Throw(new CAException(kAudio_UnimplementedError)); } UInt32 CAHALAudioDevice::GetClockDomain() const { Throw(new CAException(kAudio_UnimplementedError)); } Float64 CAHALAudioDevice::GetActualSampleRate() const { Throw(new CAException(kAudio_UnimplementedError)); } UInt32 CAHALAudioDevice::GetNumberAvailableNominalSampleRateRanges() const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::GetAvailableNominalSampleRateRanges(UInt32& ioNumberRanges, AudioValueRange* outRanges) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::GetAvailableNominalSampleRateRangeByIndex(UInt32 inIndex, Float64& outMinimum, Float64& outMaximum) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::IsValidNominalSampleRate(Float64 inSampleRate) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::IsIOBufferSizeSettable() const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::UsesVariableIOBufferSizes() const { Throw(new CAException(kAudio_UnimplementedError)); } UInt32 CAHALAudioDevice::GetMaximumVariableIOBufferSize() const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::HasIOBufferSizeRange() const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::GetIOBufferSizeRange(UInt32& outMinimum, UInt32& outMaximum) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::StartIOProc(AudioDeviceIOProcID inIOProcID) { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::StartIOProcAtTime(AudioDeviceIOProcID inIOProcID, AudioTimeStamp& ioStartTime, bool inIsInput, bool inIgnoreHardware) { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::StopIOProc(AudioDeviceIOProcID inIOProcID) { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::GetIOProcStreamUsage(AudioDeviceIOProcID inIOProcID, bool inIsInput, bool* outStreamUsage) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::SetIOProcStreamUsage(AudioDeviceIOProcID inIOProcID, bool inIsInput, const bool* inStreamUsage) { Throw(new CAException(kAudio_UnimplementedError)); } Float32 CAHALAudioDevice::GetIOCycleUsage() const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::SetIOCycleUsage(Float32 inValue) { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::GetCurrentTime(AudioTimeStamp& outTime) { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::TranslateTime(const AudioTimeStamp& inTime, AudioTimeStamp& outTime) { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::GetNearestStartTime(AudioTimeStamp& ioTime, bool inIsInput, bool inIgnoreHardware) { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::HasVolumeControl(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::VolumeControlIsSettable(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } Float32 CAHALAudioDevice::GetVolumeControlScalarValue(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } Float32 CAHALAudioDevice::GetVolumeControlDecibelValue(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::SetVolumeControlScalarValue(AudioObjectPropertyScope inScope, UInt32 inChannel, Float32 inValue) { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::SetVolumeControlDecibelValue(AudioObjectPropertyScope inScope, UInt32 inChannel, Float32 inValue) { Throw(new CAException(kAudio_UnimplementedError)); } Float32 CAHALAudioDevice::GetVolumeControlScalarForDecibelValue(AudioObjectPropertyScope inScope, UInt32 inChannel, Float32 inValue) const { Throw(new CAException(kAudio_UnimplementedError)); } Float32 CAHALAudioDevice::GetVolumeControlDecibelForScalarValue(AudioObjectPropertyScope inScope, UInt32 inChannel, Float32 inValue) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::HasSubVolumeControl(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::SubVolumeControlIsSettable(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } Float32 CAHALAudioDevice::GetSubVolumeControlScalarValue(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } Float32 CAHALAudioDevice::GetSubVolumeControlDecibelValue(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::SetSubVolumeControlScalarValue(AudioObjectPropertyScope inScope, UInt32 inChannel, Float32 inValue) { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::SetSubVolumeControlDecibelValue(AudioObjectPropertyScope inScope, UInt32 inChannel, Float32 inValue) { Throw(new CAException(kAudio_UnimplementedError)); } Float32 CAHALAudioDevice::GetSubVolumeControlScalarForDecibelValue(AudioObjectPropertyScope inScope, UInt32 inChannel, Float32 inValue) const { Throw(new CAException(kAudio_UnimplementedError)); } Float32 CAHALAudioDevice::GetSubVolumeControlDecibelForScalarValue(AudioObjectPropertyScope inScope, UInt32 inChannel, Float32 inValue) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::HasMuteControl(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::MuteControlIsSettable(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::GetMuteControlValue(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::SetMuteControlValue(AudioObjectPropertyScope inScope, UInt32 inChannel, bool inValue) { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::HasSoloControl(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::SoloControlIsSettable(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::GetSoloControlValue(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::SetSoloControlValue(AudioObjectPropertyScope inScope, UInt32 inChannel, bool inValue) { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::HasStereoPanControl(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::StereoPanControlIsSettable(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } Float32 CAHALAudioDevice::GetStereoPanControlValue(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::SetStereoPanControlValue(AudioObjectPropertyScope inScope, UInt32 inChannel, Float32 inValue) { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::GetStereoPanControlChannels(AudioObjectPropertyScope inScope, UInt32 inChannel, UInt32& outLeftChannel, UInt32& outRightChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::HasJackControl(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::GetJackControlValue(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::HasSubMuteControl(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::SubMuteControlIsSettable(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::GetSubMuteControlValue(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::SetSubMuteControlValue(AudioObjectPropertyScope inScope, UInt32 inChannel, bool inValue) { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::HasiSubOwnerControl(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::iSubOwnerControlIsSettable(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::GetiSubOwnerControlValue(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::SetiSubOwnerControlValue(AudioObjectPropertyScope inScope, UInt32 inChannel, bool inValue) { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::HasDataSourceControl(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::DataSourceControlIsSettable(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } UInt32 CAHALAudioDevice::GetCurrentDataSourceID(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::SetCurrentDataSourceByID(AudioObjectPropertyScope inScope, UInt32 inChannel, UInt32 inID) { Throw(new CAException(kAudio_UnimplementedError)); } UInt32 CAHALAudioDevice::GetNumberAvailableDataSources(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::GetAvailableDataSources(AudioObjectPropertyScope inScope, UInt32 inChannel, UInt32& ioNumberSources, UInt32* outSources) const { Throw(new CAException(kAudio_UnimplementedError)); } UInt32 CAHALAudioDevice::GetAvailableDataSourceByIndex(AudioObjectPropertyScope inScope, UInt32 inChannel, UInt32 inIndex) const { Throw(new CAException(kAudio_UnimplementedError)); } CFStringRef CAHALAudioDevice::CopyDataSourceNameForID(AudioObjectPropertyScope inScope, UInt32 inChannel, UInt32 inID) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::HasDataDestinationControl(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::DataDestinationControlIsSettable(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } UInt32 CAHALAudioDevice::GetCurrentDataDestinationID(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::SetCurrentDataDestinationByID(AudioObjectPropertyScope inScope, UInt32 inChannel, UInt32 inID) { Throw(new CAException(kAudio_UnimplementedError)); } UInt32 CAHALAudioDevice::GetNumberAvailableDataDestinations(AudioObjectPropertyScope inScope, UInt32 inChannel) const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::GetAvailableDataDestinations(AudioObjectPropertyScope inScope, UInt32 inChannel, UInt32& ioNumberDestinations, UInt32* outDestinations) const { Throw(new CAException(kAudio_UnimplementedError)); } UInt32 CAHALAudioDevice::GetAvailableDataDestinationByIndex(AudioObjectPropertyScope inScope, UInt32 inChannel, UInt32 inIndex) const { Throw(new CAException(kAudio_UnimplementedError)); } CFStringRef CAHALAudioDevice::CopyDataDestinationNameForID(AudioObjectPropertyScope inScope, UInt32 inChannel, UInt32 inID) const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::HasClockSourceControl() const { Throw(new CAException(kAudio_UnimplementedError)); } bool CAHALAudioDevice::ClockSourceControlIsSettable() const { Throw(new CAException(kAudio_UnimplementedError)); } UInt32 CAHALAudioDevice::GetCurrentClockSourceID() const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::SetCurrentClockSourceByID(UInt32 inID) { Throw(new CAException(kAudio_UnimplementedError)); } UInt32 CAHALAudioDevice::GetNumberAvailableClockSources() const { Throw(new CAException(kAudio_UnimplementedError)); } void CAHALAudioDevice::GetAvailableClockSources(UInt32& ioNumberSources, UInt32* outSources) const { Throw(new CAException(kAudio_UnimplementedError)); } UInt32 CAHALAudioDevice::GetAvailableClockSourceByIndex(UInt32 inIndex) const { Throw(new CAException(kAudio_UnimplementedError)); } CFStringRef CAHALAudioDevice::CopyClockSourceNameForID(UInt32 inID) const { Throw(new CAException(kAudio_UnimplementedError)); } UInt32 CAHALAudioDevice::GetClockSourceKindForID(UInt32 inID) const { Throw(new CAException(kAudio_UnimplementedError)); }
20,757
C++
.cpp
553
35.330922
164
0.841573
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
4,372
BGMPlayThroughRTLogger.cpp
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMPlayThroughRTLogger.cpp
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMPlayThroughRTLogger.cpp // BGMApp // // Copyright © 2020 Kyle Neideck // // Self Include #include "BGMPlayThroughRTLogger.h" // Local Includes #include "BGM_Utils.h" // PublicUtility Includes #include "CADebugMacros.h" // STL Includes #include <atomic> // System Includes #include <CoreAudio/CoreAudio.h> #include <mach/mach_init.h> #include <mach/task.h> #include <unistd.h> #pragma clang assume_nonnull begin // Track the number of messages logged when built for the unit tests. #if BGM_UnitTest #define LogSync_Debug(inFormat, ...) do { \ mNumDebugMessagesLogged++; \ DebugMsg(inFormat, ## __VA_ARGS__); \ } while (0) #else #define LogSync_Debug(inFormat, ...) DebugMsg(inFormat, ## __VA_ARGS__) #endif #pragma mark Construction/Destruction BGMPlayThroughRTLogger::BGMPlayThroughRTLogger() { // Create the semaphore we use to wake up the logging thread when it has messages to log. mWakeUpLoggingThreadSemaphore = CreateSemaphore(); // Create the logging thread last because it starts immediately and expects the other member // variables to be initialised. mLoggingThread = std::thread(&BGMPlayThroughRTLogger::LoggingThreadEntry, this); } // static semaphore_t BGMPlayThroughRTLogger::CreateSemaphore() { // TODO: Make a BGMMachSemaphore class to reduce some of this repetitive semaphore code. // Create the semaphore. semaphore_t semaphore; kern_return_t error = semaphore_create(mach_task_self(), &semaphore, SYNC_POLICY_FIFO, 0); // Check the error code. BGM_Utils::ThrowIfMachError("BGMPlayThroughRTLogger::CreateSemaphore", "semaphore_create", error); ThrowIf(semaphore == SEMAPHORE_NULL, CAException(kAudioHardwareUnspecifiedError), "BGMPlayThroughRTLogger::CreateSemaphore: Failed to create semaphore"); return semaphore; } BGMPlayThroughRTLogger::~BGMPlayThroughRTLogger() { // Stop the logging thread. mLoggingThreadShouldExit = true; kern_return_t error = semaphore_signal(mWakeUpLoggingThreadSemaphore); BGM_Utils::LogIfMachError("BGMPlayThroughRTLogger::~BGMPlayThroughRTLogger", "semaphore_signal", error); if(error == KERN_SUCCESS) { // Wait for it to stop. mLoggingThread.join(); // Destroy the semaphore. error = semaphore_destroy(mach_task_self(), mWakeUpLoggingThreadSemaphore); BGM_Utils::LogIfMachError("BGMPlayThroughRTLogger::~BGMPlayThroughRTLogger", "semaphore_destroy", error); } else { // If we couldn't tell it to wake up, it's not safe to wait for it to stop or to destroy the // semaphore. We have to detach it so its destructor doesn't cause a crash. mLoggingThread.detach(); } } #pragma mark Log Messages void BGMPlayThroughRTLogger::LogReleasingWaitingThreads() { if(!BGMDebugLoggingIsEnabled()) { return; } if(!mLogReleasingWaitingThreadsMsg.is_lock_free()) { // Modifying mLogReleasingWaitingThreadsMsg might cause the thread to lock a mutex that // isn't safe to lock on a realtime thread, so just give up. return; } // Set the flag that tells the logging thread to log the message. mLogReleasingWaitingThreadsMsg = true; // Wake the logging thread so it can log the message. WakeLoggingThread(); } void BGMPlayThroughRTLogger::LogIfMachError_ReleaseWaitingThreadsSignal(mach_error_t inError) { if(inError == KERN_SUCCESS) { // No error. return; } if(!mReleaseWaitingThreadsSignalError.is_lock_free()) { // Modifying mReleaseWaitingThreadsSignalError might cause the thread to lock a mutex that // isn't safe to lock on a realtime thread, so just give up. return; } mReleaseWaitingThreadsSignalError = inError; WakeLoggingThread(); } void BGMPlayThroughRTLogger::LogIfDroppedFrames(Float64 inFirstInputSampleTime, Float64 inLastInputSampleTime) { if(inFirstInputSampleTime == inLastInputSampleTime || !BGMDebugLoggingIsEnabled()) { // Either we didn't drop any initial frames or we don't need to log a message about it. return; } LogAsync(mDroppedFrames, [&]() { // Store the data to include in the log message. mDroppedFrames.firstInputSampleTime = inFirstInputSampleTime; mDroppedFrames.lastInputSampleTime = inLastInputSampleTime; }); } void BGMPlayThroughRTLogger::LogNoSamplesReady(CARingBuffer::SampleTime inLastInputSampleTime, CARingBuffer::SampleTime inReadHeadSampleTime, Float64 inInToOutSampleOffset) { if(!BGMDebugLoggingIsEnabled()) { return; } LogAsync(mNoSamplesReady, [&]() { // Store the data to include in the log message. mNoSamplesReady.lastInputSampleTime = inLastInputSampleTime; mNoSamplesReady.readHeadSampleTime = inReadHeadSampleTime; mNoSamplesReady.inToOutSampleOffset = inInToOutSampleOffset; }); } void BGMPlayThroughRTLogger::LogExceptionStoppingIOProc(const char* inCallerName, OSStatus inError, bool inErrorKnown) { LogAsync(mExceptionStoppingIOProc, [&]() { // Store the data to include in the log message. mExceptionStoppingIOProc.callerName = inCallerName; mExceptionStoppingIOProc.error = inError; mExceptionStoppingIOProc.errorKnown = inErrorKnown; }); } void BGMPlayThroughRTLogger::LogUnexpectedIOStateAfterStopping(const char* inCallerName, int inIOState) { LogAsync(mUnexpectedIOStateAfterStopping, [&]() { // Store the data to include in the log message. mUnexpectedIOStateAfterStopping.callerName = inCallerName; mUnexpectedIOStateAfterStopping.ioState = inIOState; }); } void BGMPlayThroughRTLogger::LogRingBufferUnavailable(const char* inCallerName, bool inGotLock) { LogAsync(mRingBufferUnavailable, [&]() { // Store the data to include in the log message. mRingBufferUnavailable.callerName = inCallerName; mRingBufferUnavailable.gotLock = inGotLock; }); } void BGMPlayThroughRTLogger::LogIfRingBufferError(CARingBufferError inError, std::atomic<CARingBufferError>& outError) { if(inError == kCARingBufferError_OK) { // No error. return; } if(!outError.is_lock_free()) { // Modifying outError might cause the thread to lock a mutex that isn't safe to lock on // a realtime thread, so just give up. return; } // Store the error. outError = inError; // Wake the logging thread so it can log the error. WakeLoggingThread(); } template <typename T, typename F> void BGMPlayThroughRTLogger::LogAsync(T& inMessageData, F&& inStoreMessageData) { if(!inMessageData.shouldLogMessage.is_lock_free()) { // Modifying shouldLogMessage might cause the thread to lock a mutex that isn't safe to // lock on a realtime thread, so just give up. return; } if(inMessageData.shouldLogMessage) { // The logging thread could be reading inMessageData. return; } // Store the data to include in the log message. // // std::forward lets the compiler treat inStoreMessageData as an rvalue if the caller gave it as // an rvalue. No idea if that actually does anything. std::forward<F>(inStoreMessageData)(); // shouldLogMessage is a std::atomic, so this store also makes sure that the non-atomic stores // in inStoreMessageData will be visible to the logger thread (since the default memory order is // memory_order_seq_cst). inMessageData.shouldLogMessage = true; WakeLoggingThread(); } void BGMPlayThroughRTLogger::LogSync_Warning(const char* inFormat, ...) { va_list args; va_start(args, inFormat); #if BGM_UnitTest mNumWarningMessagesLogged++; #endif vLogWarning(inFormat, args); va_end(args); } void BGMPlayThroughRTLogger::LogSync_Error(const char* inFormat, ...) { va_list args; va_start(args, inFormat); #if BGM_UnitTest mNumErrorMessagesLogged++; if(!mContinueOnErrorLogged) { vLogError(inFormat, args); } #else vLogError(inFormat, args); #endif va_end(args); } #pragma mark Logging Thread void BGMPlayThroughRTLogger::WakeLoggingThread() { kern_return_t error = semaphore_signal(mWakeUpLoggingThreadSemaphore); BGMAssert(error == KERN_SUCCESS, "semaphore_signal (%d)", error); // We can't do anything useful with the error in release builds. At least, not easily. (void)error; } void BGMPlayThroughRTLogger::LogMessages() { // Log the messages/errors from the realtime threads (if any). LogSync_ReleasingWaitingThreads(); LogSync_ReleaseWaitingThreadsSignalError(); LogSync_DroppedFrames(); LogSync_NoSamplesReady(); LogSync_ExceptionStoppingIOProc(); LogSync_UnexpectedIOStateAfterStopping(); LogSync_RingBufferUnavailable(); LogSync_RingBufferError(mRingBufferStoreError, "InputDeviceIOProc"); LogSync_RingBufferError(mRingBufferFetchError, "OutputDeviceIOProc"); } void BGMPlayThroughRTLogger::LogSync_ReleasingWaitingThreads() { if(mLogReleasingWaitingThreadsMsg) { LogSync_Debug("BGMPlayThrough::ReleaseThreadsWaitingForOutputToStart: " "Releasing waiting threads"); // Reset it. mLogReleasingWaitingThreadsMsg = false; } } void BGMPlayThroughRTLogger::LogSync_ReleaseWaitingThreadsSignalError() { if(mReleaseWaitingThreadsSignalError != KERN_SUCCESS) { BGM_Utils::LogIfMachError("BGMPlayThrough::ReleaseThreadsWaitingForOutputToStart", "semaphore_signal_all", mReleaseWaitingThreadsSignalError); // Reset it. mReleaseWaitingThreadsSignalError = KERN_SUCCESS; } } void BGMPlayThroughRTLogger::LogSync_DroppedFrames() { if(mDroppedFrames.shouldLogMessage) { LogSync_Debug("BGMPlayThrough::OutputDeviceIOProc: " "Dropped %f frames before output started. %s%f %s%f", (mDroppedFrames.lastInputSampleTime - mDroppedFrames.firstInputSampleTime), "mFirstInputSampleTime=", mDroppedFrames.firstInputSampleTime, "mLastInputSampleTime=", mDroppedFrames.lastInputSampleTime); mDroppedFrames.shouldLogMessage = false; } } void BGMPlayThroughRTLogger::LogSync_NoSamplesReady() { if(mNoSamplesReady.shouldLogMessage) { LogSync_Debug("BGMPlayThrough::OutputDeviceIOProc: " "No input samples ready at output sample time. %s%lld %s%lld %s%f", "lastInputSampleTime=", mNoSamplesReady.lastInputSampleTime, "readHeadSampleTime=", mNoSamplesReady.readHeadSampleTime, "mInToOutSampleOffset=", mNoSamplesReady.inToOutSampleOffset); mNoSamplesReady.shouldLogMessage = false; } } void BGMPlayThroughRTLogger::LogSync_ExceptionStoppingIOProc() { if(mExceptionStoppingIOProc.shouldLogMessage) { const char error4CC[5] = CA4CCToCString(mExceptionStoppingIOProc.error); LogSync_Error("BGMPlayThrough::UpdateIOProcState: " "Exception while stopping IOProc %s: %s (%d)", mExceptionStoppingIOProc.callerName, mExceptionStoppingIOProc.errorKnown ? error4CC : "unknown", mExceptionStoppingIOProc.error); mExceptionStoppingIOProc.shouldLogMessage = false; } } void BGMPlayThroughRTLogger::LogSync_UnexpectedIOStateAfterStopping() { if(mUnexpectedIOStateAfterStopping.shouldLogMessage) { LogSync_Warning("BGMPlayThrough::UpdateIOProcState: " "%s IO state changed since last read. state = %d", mUnexpectedIOStateAfterStopping.callerName, mUnexpectedIOStateAfterStopping.ioState); mUnexpectedIOStateAfterStopping.shouldLogMessage = false; } } void BGMPlayThroughRTLogger::LogSync_RingBufferUnavailable() { if(mRingBufferUnavailable.shouldLogMessage) { LogSync_Warning("BGMPlayThrough::%s: Ring buffer unavailable. %s", mRingBufferUnavailable.callerName, mRingBufferUnavailable.gotLock ? "No buffer currently allocated." : "Buffer locked for allocation/deallocation by another thread."); mRingBufferUnavailable.shouldLogMessage = false; } } void BGMPlayThroughRTLogger::LogSync_RingBufferError( std::atomic<CARingBufferError>& ioRingBufferError, const char* inMethodName) { CARingBufferError error = ioRingBufferError; switch(error) { case kCARingBufferError_OK: // No error. return; case kCARingBufferError_CPUOverload: // kCARingBufferError_CPUOverload might not be our fault, so just log a warning. LogSync_Warning("BGMPlayThrough::%s: Ring buffer error: " "kCARingBufferError_CPUOverload (%d)", inMethodName, error); break; default: // Other types of CARingBuffer errors should never occur. This will crash debug builds. LogSync_Error("BGMPlayThrough::%s: Ring buffer error: %s (%d)", inMethodName, (error == kCARingBufferError_TooMuch ? "kCARingBufferError_TooMuch" : "unknown error"), error); break; }; // Reset it. ioRingBufferError = kCARingBufferError_OK; } // static void* __nullable BGMPlayThroughRTLogger::LoggingThreadEntry(BGMPlayThroughRTLogger* inRefCon) { DebugMsg("BGMPlayThroughRTLogger::IOProcLoggingThreadEntry: " "Starting the IOProc logging thread"); while(!inRefCon->mLoggingThreadShouldExit) { // Log the messages, if there are any to log. inRefCon->LogMessages(); // Wait until woken up. kern_return_t error = semaphore_wait(inRefCon->mWakeUpLoggingThreadSemaphore); BGM_Utils::LogIfMachError("BGMPlayThroughRTLogger::IOProcLoggingThreadEntry", "semaphore_wait", error); } DebugMsg("BGMPlayThroughRTLogger::IOProcLoggingThreadEntry: IOProc logging thread exiting"); return nullptr; } #if BGM_UnitTest #pragma mark Test Helpers bool BGMPlayThroughRTLogger::WaitUntilLoggerThreadIdle() { int msWaited = 0; while(mLogReleasingWaitingThreadsMsg || mReleaseWaitingThreadsSignalError != KERN_SUCCESS || mDroppedFrames.shouldLogMessage || mNoSamplesReady.shouldLogMessage || mUnexpectedIOStateAfterStopping.shouldLogMessage || mRingBufferUnavailable.shouldLogMessage || mExceptionStoppingIOProc.shouldLogMessage || mRingBufferStoreError != kCARingBufferError_OK || mRingBufferFetchError != kCARingBufferError_OK) { // Poll until the logger thread has nothing left to log. (Ideally we'd use a semaphore // instead of polling, but it isn't worth the effort at this point.) usleep(10 * 1000); msWaited += 10; // Time out after 5 seconds. if(msWaited > 5000) { return false; } } return true; } #endif /* BGM_UnitTest */ #pragma clang assume_nonnull end
17,011
C++
.cpp
440
30.631818
100
0.671073
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
4,373
BGMPlayThrough.cpp
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMPlayThrough.cpp
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMPlayThrough.cpp // BGMApp // // Copyright © 2016, 2017, 2020 Kyle Neideck // // Self Include #include "BGMPlayThrough.h" // Local Includes #include "BGM_Types.h" #include "BGM_Utils.h" // PublicUtility Includes #include "CAHALAudioSystemObject.h" #include "CAPropertyAddress.h" // STL Includes #include <algorithm> // For std::max // System Includes #include <mach/mach_init.h> #include <mach/mach_time.h> #include <mach/task.h> // The number of IO cycles (roughly) to wait for our IOProcs to stop themselves before assuming something // went wrong. If that happens, we try to stop them from a non-IO thread and continue anyway. static const UInt32 kStopIOProcTimeoutInIOCycles = 600; #pragma mark Construction/Destruction BGMPlayThrough::BGMPlayThrough(BGMAudioDevice inInputDevice, BGMAudioDevice inOutputDevice) : mInputDevice(inInputDevice), mOutputDevice(inOutputDevice) { Init(inInputDevice, inOutputDevice); } BGMPlayThrough::~BGMPlayThrough() { CAMutex::Locker stateLocker(mStateMutex); BGMLogAndSwallowExceptionsMsg("BGMPlayThrough::~BGMPlayThrough", "Deactivate", [&]() { Deactivate(); }); // If one of the IOProcs failed to stop, CoreAudio could (at least in theory) still call it // after this point. This isn't a solution, but calling DeallocateBuffer instead of letting it // deallocate itself should at least make the error less likely to cause a segfault, since // DeallocateBuffer takes the buffer locks and sets mBuffer to null. // // TODO: It probably wouldn't be too hard to fix this properly by giving the IOProcs weak refs // to the BGMPlayThrough object instead of raw pointers. DeallocateBuffer(); if(mOutputDeviceIOProcSemaphore != SEMAPHORE_NULL) { kern_return_t theError = semaphore_destroy(mach_task_self(), mOutputDeviceIOProcSemaphore); BGM_Utils::LogIfMachError("BGMPlayThrough::~BGMPlayThrough", "semaphore_destroy", theError); } } void BGMPlayThrough::Init(BGMAudioDevice inInputDevice, BGMAudioDevice inOutputDevice) { BGMAssert(mInputDeviceIOProcState.is_lock_free(), "BGMPlayThrough::BGMPlayThrough: !mInputDeviceIOProcState.is_lock_free()"); BGMAssert(mOutputDeviceIOProcState.is_lock_free(), "BGMPlayThrough::BGMPlayThrough: !mOutputDeviceIOProcState.is_lock_free()"); BGMAssert(!mActive, "BGMPlayThrough::BGMPlayThrough: Can't init while active."); mInputDevice = inInputDevice; mOutputDevice = inOutputDevice; AllocateBuffer(); try { // Init the semaphore for the output IOProc. if(mOutputDeviceIOProcSemaphore == SEMAPHORE_NULL) { kern_return_t theError = semaphore_create(mach_task_self(), &mOutputDeviceIOProcSemaphore, SYNC_POLICY_FIFO, 0); BGM_Utils::ThrowIfMachError("BGMPlayThrough::BGMPlayThrough", "semaphore_create", theError); ThrowIf(mOutputDeviceIOProcSemaphore == SEMAPHORE_NULL, CAException(kAudioHardwareUnspecifiedError), "BGMPlayThrough::BGMPlayThrough: Could not create semaphore"); } } catch (...) { // Clean up. DeallocateBuffer(); throw; } } void BGMPlayThrough::Activate() { CAMutex::Locker stateLocker(mStateMutex); if(!mActive) { DebugMsg("BGMPlayThrough::Activate: Activating playthrough"); CreateIOProcIDs(); mActive = true; // TODO: This code (the next two blocks) should be in BGMDeviceControlSync. // Set BGMDevice's sample rate to match the output device. try { Float64 outputSampleRate = mOutputDevice.GetNominalSampleRate(); mInputDevice.SetNominalSampleRate(outputSampleRate); } catch (CAException e) { LogWarning("BGMPlayThrough::Activate: Failed to sync device sample rates. Error: %d", e.GetError()); } // Set BGMDevice's IO buffer size to match the output device. try { UInt32 outputBufferSize = mOutputDevice.GetIOBufferSize(); mInputDevice.SetIOBufferSize(outputBufferSize); } catch (CAException e) { LogWarning("BGMPlayThrough::Activate: Failed to sync device buffer sizes. Error: %d", e.GetError()); } DebugMsg("BGMPlayThrough::Activate: Registering for notifications from BGMDevice."); mInputDevice.AddPropertyListener(CAPropertyAddress(kAudioDevicePropertyDeviceIsRunning), &BGMPlayThrough::BGMDeviceListenerProc, this); mInputDevice.AddPropertyListener(CAPropertyAddress(kAudioDeviceProcessorOverload), &BGMPlayThrough::BGMDeviceListenerProc, this); bool isBGMDevice = true; CATry isBGMDevice = mInputDevice.IsBGMDeviceInstance(); CACatch if(isBGMDevice) { mInputDevice.AddPropertyListener(kBGMRunningSomewhereOtherThanBGMAppAddress, &BGMPlayThrough::BGMDeviceListenerProc, this); } else { LogWarning("BGMPlayThrough::Activate: Playthrough activated with an output device other " "than BGMDevice. This hasn't been tested and is almost definitely a bug."); BGMAssert(false, "BGMPlayThrough::Activate: !mInputDevice.IsBGMDeviceInstance()"); } } } void BGMPlayThrough::Deactivate() { CAMutex::Locker stateLocker(mStateMutex); if(mActive) { DebugMsg("BGMPlayThrough::Deactivate: Deactivating playthrough"); bool inputDeviceIsBGMDevice = true; CATry inputDeviceIsBGMDevice = mInputDevice.IsBGMDeviceInstance(); CACatch // Unregister notification listeners. if(inputDeviceIsBGMDevice) { // There's not much we can do if these calls throw. The docs for AudioObjectRemovePropertyListener // just say that means it failed. BGMLogAndSwallowExceptions("BGMPlayThrough::Deactivate", [&] { mInputDevice.RemovePropertyListener(CAPropertyAddress(kAudioDevicePropertyDeviceIsRunning), &BGMPlayThrough::BGMDeviceListenerProc, this); }); BGMLogAndSwallowExceptions("BGMPlayThrough::Deactivate", [&] { mInputDevice.RemovePropertyListener(CAPropertyAddress(kAudioDeviceProcessorOverload), &BGMPlayThrough::BGMDeviceListenerProc, this); }); BGMLogAndSwallowExceptions("BGMPlayThrough::Deactivate", [&] { mInputDevice.RemovePropertyListener(kBGMRunningSomewhereOtherThanBGMAppAddress, &BGMPlayThrough::BGMDeviceListenerProc, this); }); } BGMLogAndSwallowExceptions("BGMPlayThrough::Deactivate", [&] { Stop(); }); BGMLogAndSwallowExceptions("BGMPlayThrough::Deactivate", [&] { DestroyIOProcIDs(); }); mActive = false; } } void BGMPlayThrough::AllocateBuffer() { // Allocate the ring buffer that will hold the data passing between the devices UInt32 numberStreams = 1; AudioStreamBasicDescription outputFormat[1]; mOutputDevice.GetCurrentVirtualFormats(false, numberStreams, outputFormat); if(numberStreams < 1) { Throw(CAException(kAudioHardwareUnsupportedOperationError)); } // Need to lock the buffer mutexes to make sure the IOProcs aren't accessing it. The order is // important here. We always lock them in the same order to prevent deadlocks. CAMutex::Locker lockerInput(mBufferInputMutex); CAMutex::Locker lockerOutput(mBufferOutputMutex); mBuffer = std::unique_ptr<CARingBuffer>(new CARingBuffer); // The calculation for the size of the buffer is from Apple's CAPlayThrough.cpp sample code // // TODO: Test playthrough with hardware with more than 2 channels per frame, a sample (virtual) format other than // 32-bit floats and/or an IO buffer size other than 512 frames mBuffer->Allocate(outputFormat[0].mChannelsPerFrame, outputFormat[0].mBytesPerFrame, mOutputDevice.GetIOBufferSize() * 20); } void BGMPlayThrough::DeallocateBuffer() { // Need to lock the buffer mutexes to make sure the IOProcs aren't accessing it. The order is // important here. We always lock them in the same order to prevent deadlocks. CAMutex::Locker lockerInput(mBufferInputMutex); CAMutex::Locker lockerOutput(mBufferOutputMutex); mBuffer = nullptr; // Note that the buffer's destructor will deallocate it. } void BGMPlayThrough::CreateIOProcIDs() { CAMutex::Locker stateLocker(mStateMutex); BGMAssert(!mPlayingThrough, "BGMPlayThrough::CreateIOProcIDs: Tried to create IOProcs when playthrough was already running"); BGMAssert(mInputDeviceIOProcID == nullptr, "BGMPlayThrough::CreateIOProcIDs: mInputDeviceIOProcID must be destroyed first."); BGMAssert(mOutputDeviceIOProcID == nullptr, "BGMPlayThrough::CreateIOProcIDs: mOutputDeviceIOProcID must be destroyed first."); BGMAssert(CheckIOProcsAreStopped(), "BGMPlayThrough::CreateIOProcIDs: IOProcs not ready."); const bool inDeviceAlive = mInputDevice.IsAlive(); const bool outDeviceAlive = mOutputDevice.IsAlive(); if(inDeviceAlive && outDeviceAlive) { DebugMsg("BGMPlayThrough::CreateIOProcIDs: Creating IOProcs"); try { mInputDeviceIOProcID = mInputDevice.CreateIOProcID(&BGMPlayThrough::InputDeviceIOProc, this); } catch(CAException e) { LogWarning("BGMPlayThrough::CreateIOProcIDs: Failed to create input IOProc ID. mInputDevice = %d", mInputDevice.GetObjectID()); throw; } try { mOutputDeviceIOProcID = mOutputDevice.CreateIOProcID(&BGMPlayThrough::OutputDeviceIOProc, this); } catch(CAException e) { LogWarning("BGMPlayThrough::CreateIOProcIDs: Failed to create output IOProc ID. mOutputDevice = %d", mOutputDevice.GetObjectID()); DestroyIOProcIDs(); // Clean up. throw; } if(mInputDeviceIOProcID == nullptr || mOutputDeviceIOProcID == nullptr) { // Should never happen if CAHALAudioDevice::CreateIOProcID didn't throw. LogError("BGMPlayThrough::CreateIOProcIDs: Null IOProc ID returned by CreateIOProcID"); throw new CAException(kAudioHardwareIllegalOperationError); } // TODO: Try using SetIOCycleUsage to reduce latency? Our IOProcs don't really do anything except copy a small // buffer. According to this, Jack OS X considered it: // https://lists.apple.com/archives/coreaudio-api/2008/Mar/msg00043.html but from a quick look at their // code, I don't think they ended up using it. // mInputDevice->SetIOCycleUsage(0.01f); // mOutputDevice->SetIOCycleUsage(0.01f); } else { LogWarning("BGMPlayThrough::CreateIOProcIDs: Failed to create IOProcs.%s%s", (inDeviceAlive ? "" : " Input device not alive."), (outDeviceAlive ? "" : " Output device not alive.")); throw new CAException(kAudioHardwareIllegalOperationError); } } void BGMPlayThrough::DestroyIOProcIDs() { CAMutex::Locker stateLocker(mStateMutex); // In release builds, we still try to destroy the IDs if the IOProcs are running, hoping they just haven't been // stopped quite yet. The docs for AudioDeviceDestroyIOProcID don't say not to do that, but it could cause races // if one really is still running so it isn't ideal. BGMAssert(CheckIOProcsAreStopped(), "BGMPlayThrough::DestroyIOProcIDs: IOProcs not ready."); DebugMsg("BGMPlayThrough::DestroyIOProcIDs: Destroying IOProcs"); auto destroy = [](BGMAudioDevice& device, const char* deviceName, AudioDeviceIOProcID& ioProcID) { #if !DEBUG #pragma unused (deviceName) #endif if(ioProcID != nullptr) { try { device.DestroyIOProcID(ioProcID); } catch(CAException e) { if((e.GetError() == kAudioHardwareBadDeviceError) || (e.GetError() == kAudioHardwareBadObjectError)) { // This means the IOProc IDs will have already been destroyed, so there's nothing to do. DebugMsg("BGMPlayThrough::DestroyIOProcIDs: Didn't destroy IOProc ID for %s device because " "it's not connected anymore. deviceID = %d", deviceName, device.GetObjectID()); } else { ioProcID = nullptr; throw; } } ioProcID = nullptr; } }; destroy(mInputDevice, "input", mInputDeviceIOProcID); destroy(mOutputDevice, "output", mOutputDeviceIOProcID); } bool BGMPlayThrough::CheckIOProcsAreStopped() const noexcept { bool statesOK = true; if(mInputDeviceIOProcState != IOState::Stopped) { LogWarning("BGMPlayThrough::CheckIOProcsAreStopped: Input IOProc not stopped. mInputDeviceIOProcState = %d", mInputDeviceIOProcState.load()); statesOK = false; } if(mOutputDeviceIOProcState != IOState::Stopped) { LogWarning("BGMPlayThrough::CheckIOProcsAreStopped: Output IOProc not stopped. mOutputDeviceIOProcState = %d", mOutputDeviceIOProcState.load()); statesOK = false; } return statesOK; } void BGMPlayThrough::SetDevices(const BGMAudioDevice* __nullable inInputDevice, const BGMAudioDevice* __nullable inOutputDevice) { CAMutex::Locker stateLocker(mStateMutex); bool wasActive = mActive; bool wasPlayingThrough = mPlayingThrough; if(wasPlayingThrough) { BGMAssert(wasActive, "BGMPlayThrough::SetOutputDevice: wasPlayingThrough && !wasActive"); // Sanity check. } Deactivate(); mInputDevice = inInputDevice ? *inInputDevice : mInputDevice; mOutputDevice = inOutputDevice ? *inOutputDevice : mOutputDevice; // Resize and reallocate the buffer if necessary. Init(mInputDevice, mOutputDevice); if(wasActive) { Activate(); } if(wasPlayingThrough) { Start(); } } #pragma mark Control Playthrough void BGMPlayThrough::Start() { CAMutex::Locker stateLocker(mStateMutex); if(mPlayingThrough) { DebugMsg("BGMPlayThrough::Start: Already started/starting."); if(mOutputDeviceIOProcState == IOState::Running) { ReleaseThreadsWaitingForOutputToStart(); } return; } if(!mInputDevice.IsAlive() || !mOutputDevice.IsAlive()) { LogError("BGMPlayThrough::Start: %s %s", mInputDevice.IsAlive() ? "" : "!mInputDevice", mOutputDevice.IsAlive() ? "" : "!mOutputDevice"); ReleaseThreadsWaitingForOutputToStart(); throw CAException(kAudioHardwareBadDeviceError); } // Set up IOProcs and listeners if they haven't been already. Activate(); BGMAssert((mInputDeviceIOProcID != nullptr) && (mOutputDeviceIOProcID != nullptr), "BGMPlayThrough::Start: Null IOProc ID"); if((mInputDeviceIOProcState != IOState::Stopped) || (mOutputDeviceIOProcState != IOState::Stopped)) { LogWarning("BGMPlayThrough::Start: IOProc(s) not ready. Trying to start anyway. %s%d %s%d", "mInputDeviceIOProcState = ", mInputDeviceIOProcState.load(), "mOutputDeviceIOProcState = ", mOutputDeviceIOProcState.load()); } DebugMsg("BGMPlayThrough::Start: Starting playthrough"); // Start our IOProcs. try { mInputDeviceIOProcState = IOState::Starting; mInputDevice.StartIOProc(mInputDeviceIOProcID); mOutputDeviceIOProcState = IOState::Starting; mOutputDevice.StartIOProc(mOutputDeviceIOProcID); } catch(CAException e) { ReleaseThreadsWaitingForOutputToStart(); // Log an error message. OSStatus err = e.GetError(); char err4CC[5] = CA4CCToCString(err); LogError("BGMPlayThrough::Start: Failed to start %s device. Error: %d (%s)", (mOutputDeviceIOProcState == IOState::Starting ? "output" : "input"), err, err4CC); // Try to stop the IOProcs in case StartIOProc failed because one of our IOProc was already // running. I don't know if it actually does fail in that case, but the documentation // doesn't say so it's safer to assume it could. CATry mInputDevice.StopIOProc(mInputDeviceIOProcID); CACatch CATry mOutputDevice.StopIOProc(mOutputDeviceIOProcID); CACatch mInputDeviceIOProcState = IOState::Stopped; mOutputDeviceIOProcState = IOState::Stopped; throw; } mPlayingThrough = true; } OSStatus BGMPlayThrough::WaitForOutputDeviceToStart() noexcept { // Check for errors. // // Technically we should take the state mutex here, but that could cause deadlocks because // BGM_Device::StartIO (in BGMDriver) blocks on this function (via XPC). Other BGMPlayThrough // functions make requests to BGMDriver while holding the state mutex, usually to get/set // properties, but the HAL will block those requests until BGM_Device::StartIO returns. try { if(!mActive) { LogError("BGMPlayThrough::WaitForOutputDeviceToStart: !mActive"); return kAudioHardwareNotRunningError; } if(!mOutputDevice.IsAlive()) { LogError("BGMPlayThrough::WaitForOutputDeviceToStart: Device not alive"); return kAudioHardwareBadDeviceError; } } catch(const CAException& e) { BGMLogException(e); return e.GetError(); } const IOState initialState = mOutputDeviceIOProcState; const UInt64 startedAt = mach_absolute_time(); if(initialState == IOState::Running) { // Return early because the output device is already running. return kAudioHardwareNoError; } else if(initialState != IOState::Starting) { // Warn if we haven't been told to start the output device yet. Usually means we // haven't received a kAudioDevicePropertyDeviceIsRunning notification yet, which can // happen. It's most common when the user changes the output device while IO is // running. LogWarning("BGMPlayThrough::WaitForOutputDeviceToStart: Device not starting"); return kDeviceNotStarting; } // Wait for our output IOProc to start. mOutputDeviceIOProcSemaphore is reset to 0 // (semaphore_signal_all) when our IOProc is running on the output device. // // This does mean that we won't have any data the first time our IOProc is called, but I // don't know any way to wait until just before that point. (The device's IsRunning property // changes immediately after we call StartIOProc.) // // We check mOutputDeviceIOProcState every 200ms as a fault tolerance mechanism. (Though, // I'm not completely sure it's impossible to miss the signal from the IOProc because of a // spurious wake up, so it might actually be necessary.) DebugMsg("BGMPlayThrough::WaitForOutputDeviceToStart: Waiting."); kern_return_t theError; IOState state; UInt64 waitedNsec = 0; mach_timebase_info_data_t info; mach_timebase_info(&info); do { BGMAssert(mOutputDeviceIOProcSemaphore != SEMAPHORE_NULL, "BGMPlayThrough::WaitForOutputDeviceToStart: !mOutputDeviceIOProcSemaphore"); theError = semaphore_timedwait(mOutputDeviceIOProcSemaphore, (mach_timespec_t){ 0, 200 * NSEC_PER_MSEC }); // Update the total time we've been waiting and the output device's state. waitedNsec = (mach_absolute_time() - startedAt) * info.numer / info.denom; state = mOutputDeviceIOProcState; } while((theError != KERN_SUCCESS) && // Signalled from the IOProc. (state == IOState::Starting) && // IO state changed. (waitedNsec < kStartIOTimeoutNsec)); // Timed out. if(BGMDebugLoggingIsEnabled()) { UInt64 startedBy = mach_absolute_time(); struct mach_timebase_info baseInfo = { 0, 0 }; mach_timebase_info(&baseInfo); UInt64 base = baseInfo.numer / baseInfo.denom; DebugMsg("BGMPlayThrough::WaitForOutputDeviceToStart: Started %f ms after notification, %f " "ms after entering WaitForOutputDeviceToStart.", static_cast<Float64>(startedBy - mToldOutputDeviceToStartAt) * base / NSEC_PER_MSEC, static_cast<Float64>(startedBy - startedAt) * base / NSEC_PER_MSEC); } // Figure out which error code to return. switch (theError) { case KERN_SUCCESS: // Signalled from the IOProc. return kAudioHardwareNoError; // IO state changed or we timed out after case KERN_OPERATION_TIMED_OUT: // - semaphore_timedwait timed out, or case KERN_ABORTED: // - a spurious wake-up. return (state == IOState::Running) ? kAudioHardwareNoError : kAudioHardwareNotRunningError; default: BGM_Utils::LogIfMachError("BGMPlayThrough::WaitForOutputDeviceToStart", "semaphore_timedwait", theError); return kAudioHardwareUnspecifiedError; } } // Release any threads waiting for the output device to start. This function doesn't take mStateMutex // because it gets called on the IO thread, which is realtime priority. void BGMPlayThrough::ReleaseThreadsWaitingForOutputToStart() { if(mActive) { semaphore_t semaphore = mOutputDeviceIOProcSemaphore; if(semaphore != SEMAPHORE_NULL) { mRTLogger.LogReleasingWaitingThreads(); kern_return_t theError = semaphore_signal_all(semaphore); mRTLogger.LogIfMachError_ReleaseWaitingThreadsSignal(theError); } } } OSStatus BGMPlayThrough::Stop() { CAMutex::Locker stateLocker(mStateMutex); // TODO: Tell the waiting threads what happened so they can return an error? ReleaseThreadsWaitingForOutputToStart(); if(mActive && mPlayingThrough) { DebugMsg("BGMPlayThrough::Stop: Stopping playthrough"); bool inputDeviceAlive = false; bool outputDeviceAlive = false; CATry inputDeviceAlive = CAHALAudioObject::ObjectExists(mInputDevice) && mInputDevice.IsAlive(); CACatch CATry outputDeviceAlive = CAHALAudioObject::ObjectExists(mOutputDevice) && mOutputDevice.IsAlive(); CACatch mInputDeviceIOProcState = inputDeviceAlive ? IOState::Stopping : IOState::Stopped; mOutputDeviceIOProcState = outputDeviceAlive ? IOState::Stopping : IOState::Stopped; // Wait for the IOProcs to stop themselves. This is so the IOProcs don't get called after the BGMPlayThrough instance // (pointed to by the client data they get from the HAL) is deallocated. // // From Jeff Moore on the Core Audio mailing list: // Note that there is no guarantee about how many times your IOProc might get called after AudioDeviceStop() returns // when you make the call from outside of your IOProc. However, if you call AudioDeviceStop() from inside your IOProc, // you do get the guarantee that your IOProc will not get called again after the IOProc has returned. UInt64 totalWaitNs = 0; BGM_Utils::LogAndSwallowExceptions(BGMDbgArgs, [&]() { Float64 expectedInputCycleNs = 0; if(inputDeviceAlive) { expectedInputCycleNs = mInputDevice.GetIOBufferSize() * (1 / mInputDevice.GetNominalSampleRate()) * NSEC_PER_SEC; } Float64 expectedOutputCycleNs = 0; if(outputDeviceAlive) { expectedOutputCycleNs = mOutputDevice.GetIOBufferSize() * (1 / mOutputDevice.GetNominalSampleRate()) * NSEC_PER_SEC; } UInt64 expectedMaxCycleNs = static_cast<UInt64>(std::max(expectedInputCycleNs, expectedOutputCycleNs)); while((mInputDeviceIOProcState == IOState::Stopping || mOutputDeviceIOProcState == IOState::Stopping) && (totalWaitNs < kStopIOProcTimeoutInIOCycles * expectedMaxCycleNs)) { // TODO: If playthrough is started again while we're waiting in this loop we could drop frames. Wait on a // semaphore instead of sleeping? That way Start() could also signal it, before waiting on the state mutex, // as a way of cancelling the stop operation. struct timespec rmtp; int err = nanosleep((const struct timespec[]){{0, NSEC_PER_MSEC}}, &rmtp); totalWaitNs += NSEC_PER_MSEC - (err == -1 ? rmtp.tv_nsec : 0); } }); // Clean up if the IOProcs didn't stop themselves if(mInputDeviceIOProcState == IOState::Stopping && mInputDeviceIOProcID != nullptr) { LogError("BGMPlayThrough::Stop: The input IOProc didn't stop itself in time. Stopping " "it from outside of the IO thread."); BGMLogUnexpectedExceptions("BGMPlayThrough::Stop", [&]() { mInputDevice.StopIOProc(mInputDeviceIOProcID); }); mInputDeviceIOProcState = IOState::Stopped; } if(mOutputDeviceIOProcState == IOState::Stopping && mOutputDeviceIOProcID != nullptr) { LogError("BGMPlayThrough::Stop: The output IOProc didn't stop itself in time. Stopping " "it from outside of the IO thread."); BGMLogUnexpectedExceptions("BGMPlayThrough::Stop", [&]() { mOutputDevice.StopIOProc(mOutputDeviceIOProcID); }); mOutputDeviceIOProcState = IOState::Stopped; } mPlayingThrough = false; } mFirstInputSampleTime = -1; mLastInputSampleTime = -1; mLastOutputSampleTime = -1; return noErr; // TODO: Why does this return anything and why always noErr? } void BGMPlayThrough::StopIfIdle() { // To save CPU time, we stop playthrough when no clients are doing IO. This should reduce the coreaudiod and BGMApp // processes' idle CPU use to virtually none. If this isn't working for you, a client might be running IO without // being audible. VLC does that when you have a file paused, for example. CAMutex::Locker stateLocker(mStateMutex); BGMAssert(mInputDevice.IsBGMDeviceInstance(), "BGMDevice not set as input device. StopIfIdle can't tell if other devices are idle."); if(!IsRunningSomewhereOtherThanBGMApp(mInputDevice)) { mLastNotifiedIOStoppedOnBGMDevice = mach_absolute_time(); // Wait a bit before stopping playthrough. // // This keeps us from starting and stopping IO too rapidly, which wastes CPU, and gives BGMDriver time to update // kAudioDeviceCustomPropertyDeviceAudibleState, which it can only do while IO is running. (The wait duration is // more or less arbitrary, except that it has to be longer than kDeviceAudibleStateMinChangedFramesForUpdate.) // 1 / sample rate = seconds per frame Float64 nsecPerFrame = (1.0 / mInputDevice.GetNominalSampleRate()) * NSEC_PER_SEC; UInt64 waitNsec = static_cast<UInt64>(20 * kDeviceAudibleStateMinChangedFramesForUpdate * nsecPerFrame); UInt64 queuedAt = mLastNotifiedIOStoppedOnBGMDevice; DebugMsg("BGMPlayThrough::StopIfIdle: Will dispatch stop-if-idle block in %llu ns. %s%llu", waitNsec, "queuedAt=", queuedAt); dispatch_after(dispatch_time(DISPATCH_TIME_NOW, waitNsec), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // Check the BGMPlayThrough instance hasn't been destructed since it queued this block if(mActive) { // The "2" is just to avoid shadowing the other locker CAMutex::Locker stateLocker2(mStateMutex); // Don't stop playthrough if IO has started running again or if // kAudioDeviceCustomPropertyDeviceIsRunningSomewhereOtherThanBGMApp has changed since // this block was queued if(mPlayingThrough && !IsRunningSomewhereOtherThanBGMApp(mInputDevice) && queuedAt == mLastNotifiedIOStoppedOnBGMDevice) { DebugMsg("BGMPlayThrough::StopIfIdle: BGMDevice is only running IO for BGMApp. " "Stopping playthrough."); Stop(); } } }); } } #pragma mark BGMDevice Listener // TODO: Listen for changes to the sample rate and IO buffer size of the output device and update the input device to match // static OSStatus BGMPlayThrough::BGMDeviceListenerProc(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress* __nonnull inAddresses, void* __nullable inClientData) { // refCon (reference context) is the instance that registered the listener proc BGMPlayThrough* refCon = static_cast<BGMPlayThrough*>(inClientData); // If the input device isn't BGMDevice, this listener proc shouldn't be registered ThrowIf(inObjectID != refCon->mInputDevice.GetObjectID(), CAException(kAudioHardwareBadObjectError), "BGMPlayThrough::BGMDeviceListenerProc: notified about audio object other than BGMDevice"); for(int i = 0; i < inNumberAddresses; i++) { switch(inAddresses[i].mSelector) { case kAudioDeviceProcessorOverload: // These warnings are common when you use the UI if you're running a debug build or have "Debug executable" // checked. You shouldn't be seeing them otherwise. DebugMsg("BGMPlayThrough::BGMDeviceListenerProc: WARNING! Got kAudioDeviceProcessorOverload notification"); LogWarning("Background Music: CPU overload reported\n"); break; // Start playthrough when a client starts IO on BGMDevice and stop when BGMApp (i.e. playthrough itself) is // the only client left doing IO. // // These cases are dispatched to avoid causing deadlocks by triggering one of the following notifications in // the process of handling one. Deadlocks could happen if these were handled synchronously when: // - the first BGMDeviceListenerProc call takes the state mutex, then requests some data from the HAL and // waits for it to return, // - the request triggers the HAL to send notifications, which it sends on a different thread, // - the HAL waits for the second BGMDeviceListenerProc call to return before it returns the data // requested by the first BGMDeviceListenerProc call, and // - the second BGMDeviceListenerProc call waits for the first to unlock the state mutex. case kAudioDevicePropertyDeviceIsRunning: // Received on the IO thread before our IOProc is called HandleBGMDeviceIsRunning(refCon); break; case kAudioDeviceCustomPropertyDeviceIsRunningSomewhereOtherThanBGMApp: HandleBGMDeviceIsRunningSomewhereOtherThanBGMApp(refCon); break; default: // We might get properties we didn't ask for, so we just ignore them. break; } } // From AudioHardware.h: "The return value is currently unused and should always be 0." return 0; } // static void BGMPlayThrough::HandleBGMDeviceIsRunning(BGMPlayThrough* refCon) { DebugMsg("BGMPlayThrough::HandleBGMDeviceIsRunning: Got notification"); // This is dispatched because it can block and // - we might be on a real-time thread, or // - BGMXPCListener::startPlayThroughSyncWithReply might get called on the same thread just // before this and time out waiting for this to run. // // TODO: We should find a way to do this without dispatching because dispatching isn't actually // real-time safe. dispatch_async(BGMGetDispatchQueue_PriorityUserInteractive(), ^{ if(refCon->mActive) { CAMutex::Locker stateLocker(refCon->mStateMutex); // Set to true initially because if we fail to get this property from BGMDevice we want to // try to start playthrough anyway. bool isRunningSomewhereOtherThanBGMApp = true; BGMLogAndSwallowExceptions("HandleBGMDeviceIsRunning", [&]() { // IsRunning doesn't always return true when IO is starting. Using // RunningSomewhereOtherThanBGMApp instead seems to be working so far. isRunningSomewhereOtherThanBGMApp = IsRunningSomewhereOtherThanBGMApp(refCon->mInputDevice); }); DebugMsg("BGMPlayThrough::HandleBGMDeviceIsRunning: " "BGMDevice is %srunning somewhere other than BGMApp", isRunningSomewhereOtherThanBGMApp ? "" : " not"); if(isRunningSomewhereOtherThanBGMApp) { refCon->mToldOutputDeviceToStartAt = mach_absolute_time(); // TODO: Handle expected exceptions (mostly CAExceptions from PublicUtility classes) in Start. // For any that can't be handled sensibly in Start, catch them here and retry a few // times (with a very short delay) before handling them by showing an unobtrusive error // message or something. Then try a different device or just set the system device back // to the real device. BGMLogAndSwallowExceptions("HandleBGMDeviceIsRunning", [&refCon]() { refCon->Start(); }); } } }); } // static void BGMPlayThrough::HandleBGMDeviceIsRunningSomewhereOtherThanBGMApp(BGMPlayThrough* refCon) { DebugMsg("BGMPlayThrough::HandleBGMDeviceIsRunningSomewhereOtherThanBGMApp: Got notification"); // These notifications don't need to be handled quickly, so we can always dispatch. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // TODO: Handle expected exceptions (mostly CAExceptions from PublicUtility classes) in StopIfIdle. BGMLogUnexpectedExceptions("HandleBGMDeviceIsRunningSomewhereOtherThanBGMApp", [&refCon]() { if(refCon->mActive) { refCon->StopIfIdle(); } }); }); } // static bool BGMPlayThrough::IsRunningSomewhereOtherThanBGMApp(const BGMAudioDevice& inBGMDevice) { return CFBooleanGetValue( static_cast<CFBooleanRef>( inBGMDevice.GetPropertyData_CFType(kBGMRunningSomewhereOtherThanBGMAppAddress))); } #pragma mark IOProcs // Note that the IOProcs will very likely not run on the same thread and that they intentionally // only lock mutexes around their use of mBuffer. // static OSStatus BGMPlayThrough::InputDeviceIOProc(AudioObjectID inDevice, const AudioTimeStamp* inNow, const AudioBufferList* inInputData, const AudioTimeStamp* inInputTime, AudioBufferList* outOutputData, const AudioTimeStamp* inOutputTime, void* __nullable inClientData) { #pragma unused (inDevice, inNow, outOutputData, inOutputTime) // refCon (reference context) is the instance that created the IOProc BGMPlayThrough* const refCon = static_cast<BGMPlayThrough*>(inClientData); IOState state; UpdateIOProcState("InputDeviceIOProc", refCon->mRTLogger, refCon->mInputDeviceIOProcState, refCon->mInputDeviceIOProcID, refCon->mInputDevice, state); if(state == IOState::Stopped || state == IOState::Stopping) { // Return early, since we just asked to stop. (Or something really weird is going on.) return noErr; } BGMAssert(state == IOState::Running, "BGMPlayThrough::InputDeviceIOProc: Unexpected state"); if(refCon->mFirstInputSampleTime == -1) { refCon->mFirstInputSampleTime = inInputTime->mSampleTime; } UInt32 framesToStore = inInputData->mBuffers[0].mDataByteSize / (SizeOf32(Float32) * 2); // See the comments in OutputDeviceIOProc where it locks mBufferOutputMutex. CAMutex::Tryer tryer(refCon->mBufferInputMutex); // Disable a warning about accessing mBuffer without holding both mBufferInputMutex and // mBufferOutputMutex. Explained further in OutputDeviceIOProc. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wthread-safety" if(tryer.HasLock() && refCon->mBuffer) { CARingBufferError err = refCon->mBuffer->Store(inInputData, framesToStore, static_cast<CARingBuffer::SampleTime>( inInputTime->mSampleTime)); #pragma clang diagnostic pop refCon->mRTLogger.LogIfRingBufferError_Store(err); refCon->mLastInputSampleTime = inInputTime->mSampleTime; } else { refCon->mRTLogger.LogRingBufferUnavailable("InputDeviceIOProc", tryer.HasLock()); } return noErr; } // static OSStatus BGMPlayThrough::OutputDeviceIOProc(AudioObjectID inDevice, const AudioTimeStamp* inNow, const AudioBufferList* inInputData, const AudioTimeStamp* inInputTime, AudioBufferList* outOutputData, const AudioTimeStamp* inOutputTime, void* __nullable inClientData) { #pragma unused (inDevice, inNow, inInputData, inInputTime) // refCon (reference context) is the instance that created the IOProc BGMPlayThrough* const refCon = static_cast<BGMPlayThrough*>(inClientData); IOState state; const bool didChangeState = UpdateIOProcState("OutputDeviceIOProc", refCon->mRTLogger, refCon->mOutputDeviceIOProcState, refCon->mOutputDeviceIOProcID, refCon->mOutputDevice, state); if(state == IOState::Stopped || state == IOState::Stopping) { // Return early, since we just asked to stop. (Or something really weird is going on.) FillWithSilence(outOutputData); return noErr; } BGMAssert(state == IOState::Running, "BGMPlayThrough::OutputDeviceIOProc: Unexpected state"); if(didChangeState) { // We just changed state from Starting to Running, which means this is the first time this IOProc // has been called since the output device finished starting up, so now we can wake any threads // waiting in WaitForOutputDeviceToStart. BGMAssert(refCon->mLastOutputSampleTime == -1, "BGMPlayThrough::OutputDeviceIOProc: mLastOutputSampleTime not reset"); refCon->ReleaseThreadsWaitingForOutputToStart(); } if(refCon->mLastInputSampleTime == -1) { // Return early, since we don't have any data to output yet. FillWithSilence(outOutputData); return noErr; } // If this is the first time this IOProc has been called since starting playthrough... if(refCon->mLastOutputSampleTime == -1) { // Calculate the number of frames between the read and write heads refCon->mInToOutSampleOffset = inOutputTime->mSampleTime - refCon->mLastInputSampleTime; // Log if we dropped frames refCon->mRTLogger.LogIfDroppedFrames(refCon->mFirstInputSampleTime, refCon->mLastInputSampleTime); } CARingBuffer::SampleTime readHeadSampleTime = static_cast<CARingBuffer::SampleTime>(inOutputTime->mSampleTime - refCon->mInToOutSampleOffset); CARingBuffer::SampleTime lastInputSampleTime = static_cast<CARingBuffer::SampleTime>(refCon->mLastInputSampleTime); UInt32 framesToOutput = outOutputData->mBuffers[0].mDataByteSize / (SizeOf32(Float32) * 2); // When the input and output devices are set, during start up or because the user changed the // output device, this class (re)allocates the ring buffer (mBuffer). We try to take this // lock before accessing the buffer to make sure it's allocated. // // If we don't get the lock, another thread must be allocating or deallocating it, so we just // give up. We can't avoid audio glitches while changing devices anyway. This class tries to // make sure the IOProcs aren't running when it allocates the buffer, but it can't guarantee // that. // // Note that this is only realtime safe because we only try to lock the mutex. If another // thread has the mutex, it will be a non-realtime thread, so we can't wait for it. CAMutex::Tryer tryer(refCon->mBufferOutputMutex); // Disable a warning about accessing mBuffer without holding both mBufferInputMutex and // mBufferOutputMutex. The input IOProc always writes ahead of where the output IOProc will read // in a given IO cycle, so it's safe for them to read and write at the same time. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wthread-safety" if(tryer.HasLock() && refCon->mBuffer) { // Very occasionally (at least for me) our read head gets ahead of input, i.e. we haven't // received any new input since this IOProc was last called, and we have to recalculate its // position. I figure this might be caused by clock drift but I'm really not sure. It also // happens if the input or output sample times are restarted from zero. // // We also recalculate the offset if the read head is outside of the ring buffer. This // happens for example when you plug in or unplug headphones, which causes the output sample // times to be restarted from zero. // // The vast majority of the time, just using lastInputSampleTime as the read head time // instead of the one we calculate would work fine (and would also account for the above). SInt64 bufferStartTime, bufferEndTime; CARingBufferError err = refCon->mBuffer->GetTimeBounds(bufferStartTime, bufferEndTime); bool outOfBounds = false; if(err == kCARingBufferError_OK) { outOfBounds = (readHeadSampleTime < bufferStartTime) || (readHeadSampleTime - framesToOutput > bufferEndTime); } if(lastInputSampleTime < readHeadSampleTime || outOfBounds) { refCon->mRTLogger.LogNoSamplesReady(lastInputSampleTime, readHeadSampleTime, refCon->mInToOutSampleOffset); // Recalculate the in-to-out offset and read head. refCon->mInToOutSampleOffset = inOutputTime->mSampleTime - lastInputSampleTime; readHeadSampleTime = static_cast<CARingBuffer::SampleTime>( inOutputTime->mSampleTime - refCon->mInToOutSampleOffset); } // Copy the frames from the ring buffer. err = refCon->mBuffer->Fetch(outOutputData, framesToOutput, readHeadSampleTime); refCon->mRTLogger.LogIfRingBufferError_Fetch(err); if(err != kCARingBufferError_OK) { FillWithSilence(outOutputData); } } else { refCon->mRTLogger.LogRingBufferUnavailable("OutputDeviceIOProc", tryer.HasLock()); FillWithSilence(outOutputData); } #pragma clang diagnostic pop refCon->mLastOutputSampleTime = inOutputTime->mSampleTime; return noErr; } // static inline void BGMPlayThrough::FillWithSilence(AudioBufferList* ioBuffer) { for(UInt32 i = 0; i < ioBuffer->mNumberBuffers; i++) { memset(ioBuffer->mBuffers[i].mData, 0, ioBuffer->mBuffers[i].mDataByteSize); } } // static bool BGMPlayThrough::UpdateIOProcState(const char* inCallerName, BGMPlayThroughRTLogger& inRTLogger, std::atomic<IOState>& inState, AudioDeviceIOProcID __nullable inIOProcID, BGMAudioDevice& inDevice, IOState& outNewState) { BGMAssert(inIOProcID != nullptr, "BGMPlayThrough::UpdateIOProcState: !inIOProcID"); // Change this IOProc's state to Running if this is the first time it's been called since we // started playthrough. // // compare_exchange_strong will return true iff it changed inState from Starting to Running. // Otherwise it will set prevState to the current value of inState. // // TODO: We probably don't actually need memory_order_seq_cst (the default). Would it be worth // changing? Might be worth checking for the other atomics/barriers in this class, too. IOState prevState = IOState::Starting; bool didChangeState = inState.compare_exchange_strong(prevState, IOState::Running); if(didChangeState) { BGMAssert(prevState == IOState::Starting, "BGMPlayThrough::UpdateIOProcState: ?!"); outNewState = IOState::Running; } else { // Return the current value of inState to the caller. outNewState = prevState; if(outNewState != IOState::Running) { // The IOProc isn't Starting or Running, so it must be Stopping. That is, it's been // told to stop itself. BGMAssert(outNewState == IOState::Stopping, "BGMPlayThrough::UpdateIOProcState: Unexpected state: %d", outNewState); bool stoppedSuccessfully = false; try { inDevice.StopIOProc(inIOProcID); // StopIOProc didn't throw, so the IOProc won't be called again until the next // time playthrough is started. stoppedSuccessfully = true; } catch(CAException e) { inRTLogger.LogExceptionStoppingIOProc(inCallerName, e.GetError()); } catch(...) { inRTLogger.LogExceptionStoppingIOProc(inCallerName); } if(stoppedSuccessfully) { // Change inState to Stopped. // // If inState has been changed since we last read it, we don't know if we called // StopIOProc before or after the thread that changed it called StartIOProc (if it // did). However, inState is only changed here (in the IOProc), in Start and in // Stop. // // Stop won't return until the IOProc has changed inState to Stopped, unless it // times out, so Stop should still be waiting. And since Start and Stop are // mutually exclusive, this should be safe. // // But if Stop has timed out and inState has changed, we leave it in its new // state (unless there's some ABA problem thing happening), which I suspect is // the safest option. didChangeState = inState.compare_exchange_strong(outNewState, IOState::Stopped); if(didChangeState) { outNewState = IOState::Stopped; } else { inRTLogger.LogUnexpectedIOStateAfterStopping(inCallerName, static_cast<int>(outNewState)); } } } } return didChangeState; }
52,176
C++
.cpp
1,044
38.25
130
0.640023
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
4,376
BGMVolumeChangeListener.cpp
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMVolumeChangeListener.cpp
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMVolumeChangeListener.cpp // BGMApp // // Copyright © 2019 Kyle Neideck // // Self Include #include "BGMVolumeChangeListener.h" // Local Includes #import "BGM_Utils.h" #import "BGMAudioDevice.h" // PublicUtility Includes #import "CAException.h" #import "CAPropertyAddress.h" #pragma clang assume_nonnull begin #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wexit-time-destructors" const static std::vector<CAPropertyAddress> kVolumeChangeProperties = { // Output volume changes CAPropertyAddress(kAudioDevicePropertyVolumeScalar, kAudioObjectPropertyScopeOutput), // Mute/unmute CAPropertyAddress(kAudioDevicePropertyMute, kAudioObjectPropertyScopeOutput), // Received when controls are added to or removed from the device. CAPropertyAddress(kAudioObjectPropertyControlList), // Received when the device has changed and "clients should re-evaluate everything they need // to know about the device, particularly the layout and values of the controls". CAPropertyAddress(kAudioDevicePropertyDeviceHasChanged) }; #pragma clang diagnostic pop BGMVolumeChangeListener::BGMVolumeChangeListener(BGMAudioDevice device, std::function<void(void)> handler) : mDevice(device) { // Register a listener that will update the slider when the user changes the volume or // mutes/unmutes their audio. mListenerBlock = Block_copy(^(UInt32 inNumberAddresses, const AudioObjectPropertyAddress* inAddresses) { // The docs for AudioObjectPropertyListenerBlock say inAddresses will always contain // at least one property the block is listening to, so there's no need to check it. (void)inNumberAddresses; (void)inAddresses; // Call the callback. handler(); }); // Register for a number of properties that might indicate that clients need to update. For // example, the mute property changing means UI elements that display the volume will need to be // updated, even though it's not strictly a change in volume. for(CAPropertyAddress property : kVolumeChangeProperties) { // Instead of swallowing exceptions here, we could try again later, but I doubt it would be // worth the effort. And the documentation doesn't actually explain what could cause this // call to fail. BGM_Utils::LogAndSwallowExceptions(BGMDbgArgs, [&] { mDevice.AddPropertyListenerBlock(property, dispatch_get_main_queue(), mListenerBlock); }); } } BGMVolumeChangeListener::~BGMVolumeChangeListener() { // Deregister and release the listener block. for(CAPropertyAddress property : kVolumeChangeProperties) { BGM_Utils::LogAndSwallowExceptions(BGMDbgArgs, [&] { mDevice.RemovePropertyListenerBlock(property, dispatch_get_main_queue(), mListenerBlock); }); } Block_release(mListenerBlock); } #pragma clang assume_nonnull end
3,893
C++
.cpp
86
38.55814
100
0.709728
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
4,377
BGMDeviceControlsList.cpp
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMDeviceControlsList.cpp
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMDeviceControlsList.cpp // BGMApp // // Copyright © 2017 Kyle Neideck // // Self Include #include "BGMDeviceControlsList.h" // Local Includes #include "BGM_Types.h" #include "BGM_Utils.h" // PublicUtility Includes #include "CAPropertyAddress.h" #include "CACFArray.h" #pragma clang assume_nonnull begin static const SInt64 kToggleDeviceInitialDelay = 50 * NSEC_PER_MSEC; static const SInt64 kToggleDeviceBackDelay = 500 * NSEC_PER_MSEC; static const SInt64 kDisableNullDeviceDelay = 500 * NSEC_PER_MSEC; static const SInt64 kDisableNullDeviceTimeout = 5000 * NSEC_PER_MSEC; #pragma mark Construction/Destruction BGMDeviceControlsList::BGMDeviceControlsList(AudioObjectID inBGMDevice, CAHALAudioSystemObject inAudioSystem) : mBGMDevice(inBGMDevice), mAudioSystem(inAudioSystem) { BGMAssert((mBGMDevice.IsBGMDevice() || mBGMDevice.GetObjectID() == kAudioObjectUnknown), "BGMDeviceControlsList::BGMDeviceControlsList: Given device is not BGMDevice"); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpartial-availability" mCanToggleDeviceOnSystem = (&dispatch_block_wait && &dispatch_block_cancel && &dispatch_block_testcancel && &dispatch_queue_attr_make_with_qos_class); #pragma clang diagnostic pop } BGMDeviceControlsList::~BGMDeviceControlsList() { CAMutex::Locker locker(mMutex); if(!mDeviceTogglingInitialised) { return; } if(mListenerQueue && mListenerBlock) { BGMLogAndSwallowExceptions("BGMDeviceControlsList::~BGMDeviceControlsList", ([&] { mAudioSystem.RemovePropertyListenerBlock( CAPropertyAddress(kAudioHardwarePropertyDevices), mListenerQueue, mListenerBlock); })); } // If we're in the middle of toggling the default device, block until we've finished. if(mDisableNullDeviceBlock && mDeviceToggleState != ToggleState::NotToggling) { DebugMsg("BGMDeviceControlsList::~BGMDeviceControlsList: Waiting for device toggle"); // Copy the reference so we can unlock the mutex and allow any remaining blocks to run. dispatch_block_t disableNullDeviceBlock = mDisableNullDeviceBlock; CAMutex::Unlocker unlocker(mMutex); // Note that if mDisableNullDeviceBlock is currently running this will return after it // finishes and if it's already run this will return immediately. So we don't have to // worry about ending up waiting for mDisableNullDeviceBlock when it isn't queued. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpartial-availability" long timedOut = dispatch_block_wait(disableNullDeviceBlock, kDisableNullDeviceTimeout); #pragma clang diagnostic pop if(timedOut) { LogWarning("BGMDeviceControlsList::~BGMDeviceControlsList: Device toggle timed out"); } } mDeviceToggleState = ToggleState::NotToggling; DestroyBlock(mDeviceToggleBlock); DestroyBlock(mDeviceToggleBackBlock); DestroyBlock(mDisableNullDeviceBlock); if(mListenerBlock) { Block_release(mListenerBlock); } if(mListenerQueue) { dispatch_release(BGM_Utils::NN(mListenerQueue)); } } #pragma mark Accessors void BGMDeviceControlsList::SetBGMDevice(AudioObjectID inBGMDeviceID) { CAMutex::Locker locker(mMutex); mBGMDevice = inBGMDeviceID; BGMAssert(mBGMDevice.IsBGMDevice(), "BGMDeviceControlsList::SetBGMDevice: Given device is not BGMDevice"); } #pragma mark Update Controls List bool BGMDeviceControlsList::MatchControlsListOf(AudioObjectID inDeviceID) { CAMutex::Locker locker(mMutex); if(!mBGMDevice.IsBGMDevice()) { LogWarning("BGMDeviceControlsList::MatchControlsListOf: BGMDevice ID not set"); return false; } // If the output device doesn't have a control that BGMDevice does, disable it on BGMDevice so // the system's audio UI isn't confusing. // No need to change input controls. AudioObjectPropertyScope inScope = kAudioObjectPropertyScopeOutput; // Check which of BGMDevice's controls are currently enabled. We need to know whether we're // actually enabling/disabling any controls so we know whether we need to call // PropagateControlListChange afterward. CFTypeRef __nullable enabledControlsRef = mBGMDevice.GetPropertyData_CFType(kBGMEnabledOutputControlsAddress); ThrowIf(!enabledControlsRef || (CFGetTypeID(enabledControlsRef) != CFArrayGetTypeID()), CAException(kAudioHardwareIllegalOperationError), "BGMDeviceControlsList::MatchControlsListOf: Expected a CFArray for " "kAudioDeviceCustomPropertyEnabledOutputControls"); CACFArray enabledControls(static_cast<CFArrayRef>(enabledControlsRef), true); BGMAssert(enabledControls.GetNumberItems() == 2, "BGMDeviceControlsList::MatchControlsListOf: Expected 2 array elements for " "kAudioDeviceCustomPropertyEnabledOutputControls"); bool volumeEnabled; bool didGetBool = enabledControls.GetBool(kBGMEnabledOutputControlsIndex_Volume, volumeEnabled); ThrowIf(!didGetBool, CAException(kAudioHardwareIllegalOperationError), "BGMDeviceControlsList::MatchControlsListOf: Expected volume element of " "kAudioDeviceCustomPropertyEnabledOutputControls to be a CFBoolean"); bool muteEnabled; didGetBool = enabledControls.GetBool(kBGMEnabledOutputControlsIndex_Mute, muteEnabled); ThrowIf(!didGetBool, CAException(kAudioHardwareIllegalOperationError), "BGMDeviceControlsList::MatchControlsListOf: Expected mute element of " "kAudioDeviceCustomPropertyEnabledOutputControls to be a CFBoolean"); DebugMsg("BGMDeviceControlsList::MatchControlsListOf: BGMDevice has volume %s, mute %s", (volumeEnabled ? "enabled" : "disabled"), (muteEnabled ? "enabled" : "disabled")); // Check which controls the other device has. BGMAudioDevice device(inDeviceID); bool hasMute = device.HasSettableMasterMute(inScope); bool hasVolume = device.HasSettableMasterVolume(inScope) || device.HasSettableVirtualMasterVolume(inScope); if(!hasVolume) { // Check for per-channel volume controls. UInt32 numChannels = device.GetTotalNumberChannels(inScope == kAudioObjectPropertyScopeInput); for(UInt32 channel = 1; channel <= numChannels; channel++) { BGMLogAndSwallowExceptionsMsg("BGMDeviceControlsList::MatchControlsListOf", "Checking for channel volume controls", ([&] { hasVolume = (device.HasVolumeControl(inScope, channel) && device.VolumeControlIsSettable(inScope, channel)); })); if(hasVolume) { break; } } } // Tell BGMDevice to enable/disable its controls to match the output device. bool deviceUpdated = false; CACFArray newEnabledControls; newEnabledControls.SetCFMutableArrayFromCopy(enabledControls.GetCFArray()); // Update volume. if(volumeEnabled != hasVolume) { DebugMsg("BGMDeviceControlsList::MatchControlsListOf: %s BGMDevice volume control.", hasVolume ? "Enabling" : "Disabling"); newEnabledControls.SetBool(kBGMEnabledOutputControlsIndex_Volume, hasVolume); deviceUpdated = true; } // Update mute. if(muteEnabled != hasMute) { DebugMsg("BGMDeviceControlsList::MatchControlsListOf: %s BGMDevice mute control.", hasMute ? "Enabling" : "Disabling"); newEnabledControls.SetBool(kBGMEnabledOutputControlsIndex_Mute, hasMute); deviceUpdated = true; } if(deviceUpdated) { mBGMDevice.SetPropertyData_CFType(kBGMEnabledOutputControlsAddress, newEnabledControls.GetCFMutableArray()); } return deviceUpdated; } void BGMDeviceControlsList::PropagateControlListChange() { CAMutex::Locker locker(mMutex); if((mBGMDevice == kAudioObjectUnknown) || !mCanToggleDeviceOnSystem) { return; } InitDeviceToggling(); // Leave the default device alone if the user has changed it since launching BGMApp. bool bgmDeviceIsDefault = true; BGMLogAndSwallowExceptions("BGMDeviceControlsList::PropagateControlListChange", ([&] { bgmDeviceIsDefault = (mBGMDevice.GetObjectID() == mAudioSystem.GetDefaultAudioDevice(false, false)); })); if(bgmDeviceIsDefault) { mDeviceToggleState = ToggleState::SettingNullDeviceAsDefault; // We'll get a notification from the HAL after the Null Device is enabled. Then we can // temporarily make it the default device, which gets other programs to notice that // BGMDevice's controls have changed. try { CAMutex::Unlocker unlocker(mMutex); SetNullDeviceEnabled(true); } catch (...) { mDeviceToggleState = ToggleState::NotToggling; LogError("BGMDeviceControlsList::PropagateControlListChange: Could not enable the Null " "Device"); throw; } } } #pragma mark Implementation void BGMDeviceControlsList::InitDeviceToggling() { CAMutex::Locker locker(mMutex); if(mDeviceTogglingInitialised || !mCanToggleDeviceOnSystem) { return; } BGMAssert(mBGMDevice.IsBGMDevice(), "BGMDeviceControlsList::InitDeviceToggling: mBGMDevice device is not set to " "BGMDevice's ID"); // Register a listener to find out when the Null Device becomes available/unavailable. See // ToggleDefaultDevice. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpartial-availability" dispatch_queue_attr_t attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_DEFAULT, 0); #pragma clang diagnostic pop mListenerQueue = dispatch_queue_create("com.bearisdriving.BGM.BGMDeviceControlsList", attr); auto listenerBlock = ^(UInt32 inNumberAddresses, const AudioObjectPropertyAddress* inAddresses) { // Ignore the notification if we're not toggling the default device, which would just mean // the default device has been changed for an unrelated reason. if(mDeviceToggleState == ToggleState::NotToggling) { return; } for(int i = 0; i < inNumberAddresses; i++) { switch(inAddresses[i].mSelector) { case kAudioHardwarePropertyDevices: { CAMutex::Locker innerLocker(mMutex); DebugMsg("BGMDeviceControlsList::InitDeviceToggling: Got " "kAudioHardwarePropertyDevices"); // Cancel the previous block in case it hasn't run yet. DestroyBlock(mDeviceToggleBlock); mDeviceToggleBlock = CreateDeviceToggleBlock(); // Changing the default device too quickly after enabling the Null Device // seems to cause problems with some programs. Not sure why. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpartial-availability" if(mDeviceToggleBlock) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kToggleDeviceInitialDelay), dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), BGM_Utils::NN(mDeviceToggleBlock)); } #pragma clang diagnostic pop } break; default: break; } } }; mListenerBlock = Block_copy(listenerBlock); BGMLogAndSwallowExceptions("BGMDeviceControlsList::InitDeviceToggling", [&] { mAudioSystem.AddPropertyListenerBlock(CAPropertyAddress(kAudioHardwarePropertyDevices), mListenerQueue, mListenerBlock); }); mDeviceTogglingInitialised = true; } void BGMDeviceControlsList::ToggleDefaultDevice() { // Set the Null Device as the OS X default device. AudioObjectID nullDeviceID = mAudioSystem.GetAudioDeviceForUID(CFSTR(kBGMNullDeviceUID)); if(nullDeviceID == kAudioObjectUnknown) { // It's unlikely, but we might have been notified about an unrelated device so just log a // warning. LogWarning("BGMDeviceControlsList::ToggleDefaultDevice: Null Device not found"); return; } DebugMsg("BGMDeviceControlsList::ToggleDefaultDevice: Setting Null Device as default. " "nullDeviceID = %u", nullDeviceID); mAudioSystem.SetDefaultAudioDevice(false, false, nullDeviceID); mDeviceToggleState = ToggleState::SettingBGMDeviceAsDefault; // A small number of apps (e.g. Firefox) seem to have trouble with the default device being // changed back immediately, so for now we insert a short delay here and before disabling the // Null Device. // Cancel the previous block in case it hasn't run yet. DestroyBlock(mDeviceToggleBackBlock); mDeviceToggleBackBlock = CreateDeviceToggleBackBlock(); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpartial-availability" if(mDeviceToggleBackBlock) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kToggleDeviceBackDelay), dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), BGM_Utils::NN(mDeviceToggleBackBlock)); } #pragma clang diagnostic pop } void BGMDeviceControlsList::SetNullDeviceEnabled(bool inEnabled) { DebugMsg("BGMDeviceControlsList::SetNullDeviceEnabled: %s the null device", inEnabled ? "Enabling" : "Disabling"); // Get the audio object for BGMDriver, which is the object the Null Device belongs to. AudioObjectID bgmDriverID = mAudioSystem.GetAudioPlugInForBundleID(CFSTR(kBGMDriverBundleID)); if(bgmDriverID == kAudioObjectUnknown) { LogError("BGMDeviceControlsList::SetNullDeviceEnabled: BGMDriver plug-in audio object not " "found"); throw CAException(kAudioHardwareUnspecifiedError); } CAHALAudioObject bgmDriver(bgmDriverID); bgmDriver.SetPropertyData_CFType(CAPropertyAddress(kAudioPlugInCustomPropertyNullDeviceActive), (inEnabled ? kCFBooleanTrue : kCFBooleanFalse)); } dispatch_block_t __nullable BGMDeviceControlsList::CreateDeviceToggleBlock() { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpartial-availability" dispatch_block_t __nullable toggleBlock = dispatch_block_create((dispatch_block_flags_t)0, ^{ #pragma clang diagnostic pop CAMutex::Locker locker(mMutex); if(mDeviceToggleState == ToggleState::SettingNullDeviceAsDefault) { BGMLogAndSwallowExceptions("BGMDeviceControlsList::CreateDeviceToggleBlock", ([&] { ToggleDefaultDevice(); })); } }); if(!toggleBlock) { // Pretty sure this should never happen, but the docs aren't completely clear. LogError("BGMDeviceControlsList::CreateDeviceToggleBlock: !toggleBlock"); } return toggleBlock; } dispatch_block_t __nullable BGMDeviceControlsList::CreateDeviceToggleBackBlock() { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpartial-availability" dispatch_block_t __nullable toggleBackBlock = dispatch_block_create((dispatch_block_flags_t)0, ^{ #pragma clang diagnostic pop CAMutex::Locker locker(mMutex); if(mDeviceToggleState != ToggleState::SettingBGMDeviceAsDefault) { return; } // Set BGMDevice back as the default device. DebugMsg("BGMDeviceControlsList::ToggleDefaultDevice: Setting BGMDevice as default"); BGMLogAndSwallowExceptions("BGMDeviceControlsList::CreateDeviceToggleBackBlock", ([&] { mAudioSystem.SetDefaultAudioDevice(false, false, mBGMDevice.GetObjectID()); })); mDeviceToggleState = ToggleState::DisablingNullDevice; // Cancel the previous block in case it hasn't run yet. DestroyBlock(mDisableNullDeviceBlock); mDisableNullDeviceBlock = CreateDisableNullDeviceBlock(); #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpartial-availability" if(mDisableNullDeviceBlock) { dispatch_after(dispatch_time(DISPATCH_TIME_NOW, kDisableNullDeviceDelay), dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), BGM_Utils::NN(mDisableNullDeviceBlock)); } #pragma clang diagnostic pop }); if(!toggleBackBlock) { // Pretty sure this should never happen, but the docs aren't completely clear. LogError("BGMDeviceControlsList::CreateDeviceToggleBackBlock: !toggleBackBlock"); } return toggleBackBlock; } dispatch_block_t __nullable BGMDeviceControlsList::CreateDisableNullDeviceBlock() { #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpartial-availability" dispatch_block_t __nullable disableNullDeviceBlock = dispatch_block_create((dispatch_block_flags_t)0, ^{ #pragma clang diagnostic pop CAMutex::Locker locker(mMutex); if(mDeviceToggleState != ToggleState::DisablingNullDevice) { return; } mDeviceToggleState = ToggleState::NotToggling; BGMLogAndSwallowExceptions("BGMDeviceControlsList::CreateDisableNullDeviceBlock", ([&] { CAMutex::Unlocker unlocker(mMutex); // Hide the null device from the user again. SetNullDeviceEnabled(false); })); BGMAssert(mBGMDevice.IsBGMDevice(), "BGMDevice's AudioObjectID changed"); }); if(!disableNullDeviceBlock) { // Pretty sure this should never happen, but the docs aren't completely clear. LogError("BGMDeviceControlsList::CreateDisableNullDeviceBlock: !disableNullDeviceBlock"); } return disableNullDeviceBlock; } void BGMDeviceControlsList::DestroyBlock(dispatch_block_t __nullable & block) { if(!block) { return; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpartial-availability" dispatch_block_t& blockNN = (dispatch_block_t&)block; if(!dispatch_block_testcancel(blockNN)) { // Stop the block from running if it's currently queued. dispatch_block_cancel(blockNN); // Make sure the block isn't currently running. That should almost never be the case. while(!dispatch_block_testcancel(blockNN)) { CAMutex::Unlocker unlocker(mMutex); usleep(10); } Block_release(block); block = nullptr; } #pragma clang diagnostic pop } #pragma clang assume_nonnull end
20,366
C++
.cpp
458
35.779476
101
0.685987
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
true
false
true
false
4,381
BGM_XPCHelper.h
kyleneideck_BackgroundMusic/BGMDriver/BGMDriver/BGM_XPCHelper.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGM_XPCHelper.h // BGMDriver // // Copyright © 2016 Kyle Neideck // #ifndef BGMDriver__BGM_XPCHelper #define BGMDriver__BGM_XPCHelper // System Includes #include <MacTypes.h> #if defined(__cplusplus) extern "C" { #endif // On failure, returns one of the kBGMXPC_* error codes, or the error code received from BGMXPCHelper. Returns kBGMXPC_Success otherwise. UInt64 StartBGMAppPlayThroughSync(bool inIsForUISoundsDevice); #if defined(__cplusplus) } #endif #endif /* BGMDriver__BGM_XPCHelper */
1,212
C++
.h
33
35.484848
137
0.772844
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,393
BGM_Clients.h
kyleneideck_BackgroundMusic/BGMDriver/BGMDriver/DeviceClients/BGM_Clients.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGM_Clients.h // BGMDriver // // Copyright © 2016 Kyle Neideck // #ifndef __BGMDriver__BGM_Clients__ #define __BGMDriver__BGM_Clients__ // Local Includes #include "BGM_Client.h" #include "BGM_ClientMap.h" // PublicUtility Includes #include "CAVolumeCurve.h" #include "CAMutex.h" #include "CACFArray.h" // System Includes #include <CoreAudio/AudioServerPlugIn.h> // Forward Declations class BGM_ClientTasks; #pragma clang assume_nonnull begin //================================================================================================== // BGM_Clients // // Holds information about the clients (of the host) of the BGMDevice, i.e. the apps registered // with the HAL, generally so they can do IO at some point. BGMApp and the music player are special // case clients. // // Methods whose names end with "RT" should only be called from real-time threads. //================================================================================================== class BGM_Clients { friend class BGM_ClientTasks; public: BGM_Clients(AudioObjectID inOwnerDeviceID, BGM_TaskQueue* inTaskQueue); ~BGM_Clients() = default; // Disallow copying. (It could make sense to implement these in future, but we don't need them currently.) BGM_Clients(const BGM_Clients&) = delete; BGM_Clients& operator=(const BGM_Clients&) = delete; void AddClient(BGM_Client inClient); void RemoveClient(const UInt32 inClientID); private: // Only BGM_TaskQueue is allowed to call these (through the BGM_ClientTasks interface). We get notifications // from the HAL when clients start/stop IO and they have to be processed in the order we receive them to // avoid race conditions. If these methods could be called directly those calls would skip any queued calls. bool StartIONonRT(UInt32 inClientID); bool StopIONonRT(UInt32 inClientID); public: bool ClientsRunningIO() const; bool ClientsOtherThanBGMAppRunningIO() const; private: void SendIORunningNotifications(bool sendIsRunningNotification, bool sendIsRunningSomewhereOtherThanBGMAppNotification) const; public: bool IsBGMApp(UInt32 inClientID) const { return inClientID == mBGMAppClientID; } bool BGMAppHasClientRegistered() const { return mBGMAppClientID != -1; } inline pid_t GetMusicPlayerProcessIDProperty() const { return mMusicPlayerProcessIDProperty; } inline CFStringRef CopyMusicPlayerBundleIDProperty() const { return mMusicPlayerBundleIDProperty.CopyCFString(); } // Returns true if the PID was changed bool SetMusicPlayer(const pid_t inPID); // Returns true if the bundle ID was changed bool SetMusicPlayer(const CACFString inBundleID); bool IsMusicPlayerRT(const UInt32 inClientID) const; Float32 GetClientRelativeVolumeRT(UInt32 inClientID) const; SInt32 GetClientPanPositionRT(UInt32 inClientID) const; // Copies the current and past clients into an array in the format expected for // kAudioDeviceCustomPropertyAppVolumes. (Except that CACFArray and CACFDictionary are used instead // of unwrapped CFArray and CFDictionary refs.) CACFArray CopyClientRelativeVolumesAsAppVolumes() const { return mClientMap.CopyClientRelativeVolumesAsAppVolumes(mRelativeVolumeCurve); }; // inAppVolumes is an array of dicts with the keys kBGMAppVolumesKey_ProcessID, // kBGMAppVolumesKey_BundleID and optionally kBGMAppVolumesKey_RelativeVolume and // kBGMAppVolumesKey_PanPosition. This method finds the client for // each app by PID or bundle ID, sets the volume and applies mRelativeVolumeCurve to it. // // Returns true if any clients' relative volumes were changed. bool SetClientsRelativeVolumes(const CACFArray inAppVolumes); private: AudioObjectID mOwnerDeviceID; BGM_ClientMap mClientMap; // Counters for the number of clients that are doing IO. These are used to tell whether any clients // are currently doing IO without having to check every client's mDoingIO. // // We need to reference count this rather than just using a bool because the HAL might (but usually // doesn't) call our StartIO/StopIO functions for clients other than the first to start and last to // stop. UInt64 mStartCount = 0; UInt64 mStartCountExcludingBGMApp = 0; CAMutex mMutex { "Clients" }; SInt64 mBGMAppClientID = -1; // The value of the kAudioDeviceCustomPropertyMusicPlayerProcessID property, or 0 if it's unset/null. // We store this separately because the music player might not always be a client, but could be added // as one at a later time. pid_t mMusicPlayerProcessIDProperty = 0; // The value of the kAudioDeviceCustomPropertyMusicPlayerBundleID property, or the empty string if it's // unset/null. UTF8 encoding. // // As with mMusicPlayerProcessID, we keep a copy of the bundle ID the user sets for the music player // because there might be no client with that bundle ID. In that case we need to be able to give the // property's value if the HAL asks for it, and to recognise the music player if it's added a client. CACFString mMusicPlayerBundleIDProperty { "" }; // The volume curve we apply to raw client volumes before they're used CAVolumeCurve mRelativeVolumeCurve; }; #pragma clang assume_nonnull end #endif /* __BGMDriver__BGM_Clients__ */
7,058
C++
.h
117
55
169
0.643976
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,396
CADebugMacros.h
kyleneideck_BackgroundMusic/BGMDriver/PublicUtility/CADebugMacros.h
/* File: CADebugMacros.h Abstract: Part of CoreAudio Utility Classes Version: 1.0.1 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2013 Apple Inc. All Rights Reserved. */ #if !defined(__CADebugMacros_h__) #define __CADebugMacros_h__ //============================================================================= // Includes //============================================================================= #if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) #include <CoreAudio/CoreAudioTypes.h> #else #include "CoreAudioTypes.h" #endif //============================================================================= // CADebugMacros //============================================================================= //#define CoreAudio_StopOnFailure 1 //#define CoreAudio_TimeStampMessages 1 //#define CoreAudio_ThreadStampMessages 1 //#define CoreAudio_FlushDebugMessages 1 #if TARGET_RT_BIG_ENDIAN #define CA4CCToCString(the4CC) { ((char*)&the4CC)[0], ((char*)&the4CC)[1], ((char*)&the4CC)[2], ((char*)&the4CC)[3], 0 } #define CACopy4CCToCString(theCString, the4CC) { theCString[0] = ((char*)&the4CC)[0]; theCString[1] = ((char*)&the4CC)[1]; theCString[2] = ((char*)&the4CC)[2]; theCString[3] = ((char*)&the4CC)[3]; theCString[4] = 0; } #else #define CA4CCToCString(the4CC) { ((char*)&the4CC)[3], ((char*)&the4CC)[2], ((char*)&the4CC)[1], ((char*)&the4CC)[0], 0 } #define CACopy4CCToCString(theCString, the4CC) { theCString[0] = ((char*)&the4CC)[3]; theCString[1] = ((char*)&the4CC)[2]; theCString[2] = ((char*)&the4CC)[1]; theCString[3] = ((char*)&the4CC)[0]; theCString[4] = 0; } #endif // This is a macro that does a sizeof and casts the result to a UInt32. This is useful for all the // places where -wshorten64-32 catches assigning a sizeof expression to a UInt32. // For want of a better place to park this, we'll park it here. #define SizeOf32(X) ((UInt32)sizeof(X)) // This is a macro that does a offsetof and casts the result to a UInt32. This is useful for all the // places where -wshorten64-32 catches assigning an offsetof expression to a UInt32. // For want of a better place to park this, we'll park it here. #define OffsetOf32(X, Y) ((UInt32)offsetof(X, Y)) // This macro casts the expression to a UInt32. It is called out specially to allow us to track casts // that have been added purely to avert -wshorten64-32 warnings on 64 bit platforms. // For want of a better place to park this, we'll park it here. #define ToUInt32(X) ((UInt32)(X)) #define ToSInt32(X) ((SInt32)(X)) #pragma mark Basic Definitions #if DEBUG || CoreAudio_Debug // can be used to break into debugger immediately, also see CADebugger #define BusError() { long* p=NULL; *p=0; } // basic debugging print routines #if TARGET_OS_MAC && !TARGET_API_MAC_CARBON extern void DebugStr(const unsigned char* debuggerMsg); #define DebugMessage(msg) DebugStr("\p"msg) #define DebugMessageN1(msg, N1) #define DebugMessageN2(msg, N1, N2) #define DebugMessageN3(msg, N1, N2, N3) #else #include "CADebugPrintf.h" #if (CoreAudio_FlushDebugMessages && !CoreAudio_UseSysLog) || defined(CoreAudio_UseSideFile) #define FlushRtn ,fflush(DebugPrintfFile) #else #define FlushRtn #endif #if CoreAudio_ThreadStampMessages #include <pthread.h> #include "CAHostTimeBase.h" #if TARGET_RT_64_BIT #define DebugPrintfThreadIDFormat "%16p" #else #define DebugPrintfThreadIDFormat "%8p" #endif #define DebugMsg(inFormat, ...) DebugPrintf("%17qd: " DebugPrintfThreadIDFormat " " inFormat, CAHostTimeBase::GetCurrentTimeInNanos(), pthread_self(), ## __VA_ARGS__) FlushRtn #elif CoreAudio_TimeStampMessages #include "CAHostTimeBase.h" #define DebugMsg(inFormat, ...) DebugPrintf("%17qd: " inFormat, CAHostTimeBase::GetCurrentTimeInNanos(), ## __VA_ARGS__) FlushRtn #else #define DebugMsg(inFormat, ...) DebugPrintf(inFormat, ## __VA_ARGS__) FlushRtn #endif #endif void DebugPrint(const char *fmt, ...); // can be used like printf #ifndef DEBUGPRINT #define DEBUGPRINT(msg) DebugPrint msg // have to double-parenthesize arglist (see Debugging.h) #endif #if VERBOSE #define vprint(msg) DEBUGPRINT(msg) #else #define vprint(msg) #endif // Original macro keeps its function of turning on and off use of CADebuggerStop() for both asserts and throws. // For backwards compat, it overrides any setting of the two sub-macros. #if CoreAudio_StopOnFailure #include "CADebugger.h" #undef CoreAudio_StopOnAssert #define CoreAudio_StopOnAssert 1 #undef CoreAudio_StopOnThrow #define CoreAudio_StopOnThrow 1 #define STOP CADebuggerStop() #else #define STOP #endif #if CoreAudio_StopOnAssert #if !CoreAudio_StopOnFailure #include "CADebugger.h" #define STOP #endif #define __ASSERT_STOP CADebuggerStop() #else #define __ASSERT_STOP #endif #if CoreAudio_StopOnThrow #if !CoreAudio_StopOnFailure #include "CADebugger.h" #define STOP #endif #define __THROW_STOP CADebuggerStop() #else #define __THROW_STOP #endif #else #define DebugMsg(inFormat, ...) #ifndef DEBUGPRINT #define DEBUGPRINT(msg) #endif #define vprint(msg) #define STOP #define __ASSERT_STOP #define __THROW_STOP #endif // Old-style numbered DebugMessage calls are implemented in terms of DebugMsg() now #define DebugMessage(msg) DebugMsg(msg) #define DebugMessageN1(msg, N1) DebugMsg(msg, N1) #define DebugMessageN2(msg, N1, N2) DebugMsg(msg, N1, N2) #define DebugMessageN3(msg, N1, N2, N3) DebugMsg(msg, N1, N2, N3) #define DebugMessageN4(msg, N1, N2, N3, N4) DebugMsg(msg, N1, N2, N3, N4) #define DebugMessageN5(msg, N1, N2, N3, N4, N5) DebugMsg(msg, N1, N2, N3, N4, N5) #define DebugMessageN6(msg, N1, N2, N3, N4, N5, N6) DebugMsg(msg, N1, N2, N3, N4, N5, N6) #define DebugMessageN7(msg, N1, N2, N3, N4, N5, N6, N7) DebugMsg(msg, N1, N2, N3, N4, N5, N6, N7) #define DebugMessageN8(msg, N1, N2, N3, N4, N5, N6, N7, N8) DebugMsg(msg, N1, N2, N3, N4, N5, N6, N7, N8) #define DebugMessageN9(msg, N1, N2, N3, N4, N5, N6, N7, N8, N9) DebugMsg(msg, N1, N2, N3, N4, N5, N6, N7, N8, N9) // BGM edit: Added __printflike. void LogError(const char *fmt, ...) __printflike(1, 2); // writes to syslog (and stderr if debugging) void LogWarning(const char *fmt, ...) __printflike(1, 2); // writes to syslog (and stderr if debugging) #define NO_ACTION (void)0 #if DEBUG || CoreAudio_Debug #pragma mark Debug Macros #define Assert(inCondition, inMessage) \ if(!(inCondition)) \ { \ DebugMessage(inMessage); \ __ASSERT_STOP; \ } #define AssertFileLine(inCondition, inMessage) \ if(!(inCondition)) \ { \ DebugMessageN3("%s, line %d: %s", __FILE__, __LINE__, inMessage); \ __ASSERT_STOP; \ } #define AssertNoError(inError, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ char __4CC[5] = CA4CCToCString(__Err); \ DebugMessageN2(inMessage ", Error: %d (%s)", (int)__Err, __4CC); \ __ASSERT_STOP; \ } \ } #define AssertNoKernelError(inError, inMessage) \ { \ unsigned int __Err = (unsigned int)(inError); \ if(__Err != 0) \ { \ DebugMessageN1(inMessage ", Error: 0x%X", __Err); \ __ASSERT_STOP; \ } \ } #define AssertNotNULL(inPtr, inMessage) \ { \ if((inPtr) == NULL) \ { \ DebugMessage(inMessage); \ __ASSERT_STOP; \ } \ } #define FailIf(inCondition, inHandler, inMessage) \ if(inCondition) \ { \ DebugMessage(inMessage); \ STOP; \ goto inHandler; \ } #define FailWithAction(inCondition, inAction, inHandler, inMessage) \ if(inCondition) \ { \ DebugMessage(inMessage); \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfNULL(inPointer, inAction, inHandler, inMessage) \ if((inPointer) == NULL) \ { \ DebugMessage(inMessage); \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfKernelError(inKernelError, inAction, inHandler, inMessage) \ { \ unsigned int __Err = (inKernelError); \ if(__Err != 0) \ { \ DebugMessageN1(inMessage ", Error: 0x%X", __Err); \ STOP; \ { inAction; } \ goto inHandler; \ } \ } #define FailIfError(inError, inAction, inHandler, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ char __4CC[5] = CA4CCToCString(__Err); \ DebugMessageN2(inMessage ", Error: %ld (%s)", (long int)__Err, __4CC); \ STOP; \ { inAction; } \ goto inHandler; \ } \ } #define FailIfNoMessage(inCondition, inHandler, inMessage) \ if(inCondition) \ { \ STOP; \ goto inHandler; \ } #define FailWithActionNoMessage(inCondition, inAction, inHandler, inMessage) \ if(inCondition) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfNULLNoMessage(inPointer, inAction, inHandler, inMessage) \ if((inPointer) == NULL) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfKernelErrorNoMessage(inKernelError, inAction, inHandler, inMessage) \ { \ unsigned int __Err = (inKernelError); \ if(__Err != 0) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } \ } #define FailIfErrorNoMessage(inError, inAction, inHandler, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } \ } #if defined(__cplusplus) #define Throw(inException) __THROW_STOP; throw (inException) #define ThrowIf(inCondition, inException, inMessage) \ if(inCondition) \ { \ DebugMessage(inMessage); \ Throw(inException); \ } #define ThrowIfNULL(inPointer, inException, inMessage) \ if((inPointer) == NULL) \ { \ DebugMessage(inMessage); \ Throw(inException); \ } #define ThrowIfKernelError(inKernelError, inException, inMessage) \ { \ int __Err = (inKernelError); \ if(__Err != 0) \ { \ DebugMessageN1(inMessage ", Error: 0x%X", __Err); \ Throw(inException); \ } \ } #define ThrowIfError(inError, inException, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ char __4CC[5] = CA4CCToCString(__Err); \ DebugMessageN2(inMessage ", Error: %d (%s)", (int)__Err, __4CC); \ Throw(inException); \ } \ } #if TARGET_OS_WIN32 #define ThrowIfWinError(inError, inException, inMessage) \ { \ HRESULT __Err = (inError); \ if(FAILED(__Err)) \ { \ DebugMessageN2(inMessage ", Code: %d, Facility: 0x%X", HRESULT_CODE(__Err), HRESULT_FACILITY(__Err)); \ Throw(inException); \ } \ } #endif #define SubclassResponsibility(inMethodName, inException) \ { \ DebugMessage(inMethodName": Subclasses must implement this method"); \ Throw(inException); \ } #endif // defined(__cplusplus) #else #pragma mark Release Macros #define Assert(inCondition, inMessage) \ if(!(inCondition)) \ { \ __ASSERT_STOP; \ } #define AssertFileLine(inCondition, inMessage) Assert(inCondition, inMessage) #define AssertNoError(inError, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ __ASSERT_STOP; \ } \ } #define AssertNoKernelError(inError, inMessage) \ { \ unsigned int __Err = (unsigned int)(inError); \ if(__Err != 0) \ { \ __ASSERT_STOP; \ } \ } #define AssertNotNULL(inPtr, inMessage) \ { \ if((inPtr) == NULL) \ { \ __ASSERT_STOP; \ } \ } #define FailIf(inCondition, inHandler, inMessage) \ if(inCondition) \ { \ STOP; \ goto inHandler; \ } #define FailWithAction(inCondition, inAction, inHandler, inMessage) \ if(inCondition) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfNULL(inPointer, inAction, inHandler, inMessage) \ if((inPointer) == NULL) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfKernelError(inKernelError, inAction, inHandler, inMessage) \ if((inKernelError) != 0) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfError(inError, inAction, inHandler, inMessage) \ if((inError) != 0) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfNoMessage(inCondition, inHandler, inMessage) \ if(inCondition) \ { \ STOP; \ goto inHandler; \ } #define FailWithActionNoMessage(inCondition, inAction, inHandler, inMessage) \ if(inCondition) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfNULLNoMessage(inPointer, inAction, inHandler, inMessage) \ if((inPointer) == NULL) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfKernelErrorNoMessage(inKernelError, inAction, inHandler, inMessage) \ { \ unsigned int __Err = (inKernelError); \ if(__Err != 0) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } \ } #define FailIfErrorNoMessage(inError, inAction, inHandler, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } \ } #if defined(__cplusplus) #define Throw(inException) __THROW_STOP; throw (inException) #define ThrowIf(inCondition, inException, inMessage) \ if(inCondition) \ { \ Throw(inException); \ } #define ThrowIfNULL(inPointer, inException, inMessage) \ if((inPointer) == NULL) \ { \ Throw(inException); \ } // BGM edit: Changed "unsigned int" to "int" to silence -Wsign-conversion. #define ThrowIfKernelError(inKernelError, inException, inMessage) \ { \ int __Err = (inKernelError); \ if(__Err != 0) \ { \ Throw(inException); \ } \ } #define ThrowIfError(inError, inException, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ Throw(inException); \ } \ } #if TARGET_OS_WIN32 #define ThrowIfWinError(inError, inException, inMessage) \ { \ HRESULT __Err = (inError); \ if(FAILED(__Err)) \ { \ Throw(inException); \ } \ } #endif #define SubclassResponsibility(inMethodName, inException) \ { \ Throw(inException); \ } #endif // defined(__cplusplus) #endif // DEBUG || CoreAudio_Debug #endif
20,219
C++
.h
503
36.518887
218
0.542359
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,408
CADebugger.h
kyleneideck_BackgroundMusic/BGMDriver/PublicUtility/CADebugger.h
/* File: CADebugger.h Abstract: Part of CoreAudio Utility Classes Version: 1.1 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2014 Apple Inc. All Rights Reserved. */ #if !defined(__CADebugger_h__) #define __CADebugger_h__ //============================================================================= // Includes //============================================================================= #if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) #include <CoreAudio/CoreAudioTypes.h> #else #include <CoreAudioTypes.h> #endif //============================================================================= // CADebugger //============================================================================= #if TARGET_API_MAC_OSX extern bool CAIsDebuggerAttached(void); #endif extern void CADebuggerStop(void); #endif
3,108
C++
.h
58
51.5
79
0.721398
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
4,410
CABitOperations.h
kyleneideck_BackgroundMusic/BGMDriver/PublicUtility/CABitOperations.h
/* File: CABitOperations.h Abstract: Part of CoreAudio Utility Classes Version: 1.1 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2014 Apple Inc. All Rights Reserved. */ #ifndef _CABitOperations_h_ #define _CABitOperations_h_ #if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) //#include <CoreServices/../Frameworks/CarbonCore.framework/Headers/MacTypes.h> #include <CoreFoundation/CFBase.h> #else // #include <MacTypes.h> #include "CFBase.h" #endif #include <TargetConditionals.h> // return whether a number is a power of two inline UInt32 IsPowerOfTwo(UInt32 x) { return (x & (x-1)) == 0; } // count the leading zeros in a word // Metrowerks Codewarrior. powerpc native count leading zeros instruction: // I think it's safe to remove this ... //#define CountLeadingZeroes(x) ((int)__cntlzw((unsigned int)x)) inline UInt32 CountLeadingZeroes(UInt32 arg) { // GNUC / LLVM have a builtin #if defined(__GNUC__) || defined(__llvm___) #if (TARGET_CPU_X86 || TARGET_CPU_X86_64) if (arg == 0) return 32; #endif // TARGET_CPU_X86 || TARGET_CPU_X86_64 return __builtin_clz(arg); #elif TARGET_OS_WIN32 UInt32 tmp; __asm{ bsr eax, arg mov ecx, 63 cmovz eax, ecx xor eax, 31 mov tmp, eax // this moves the result in tmp to return. } return tmp; #else #error "Unsupported architecture" #endif // defined(__GNUC__) } // Alias (with different spelling) #define CountLeadingZeros CountLeadingZeroes inline UInt32 CountLeadingZeroesLong(UInt64 arg) { // GNUC / LLVM have a builtin #if defined(__GNUC__) || defined(__llvm___) #if (TARGET_CPU_X86 || TARGET_CPU_X86_64) if (arg == 0) return 64; #endif // TARGET_CPU_X86 || TARGET_CPU_X86_64 return __builtin_clzll(arg); #elif TARGET_OS_WIN32 UInt32 x = CountLeadingZeroes((UInt32)(arg >> 32)); if(x < 32) return x; else return 32+CountLeadingZeroes((UInt32)arg); #else #error "Unsupported architecture" #endif // defined(__GNUC__) } #define CountLeadingZerosLong CountLeadingZeroesLong // count trailing zeroes inline UInt32 CountTrailingZeroes(UInt32 x) { return 32 - CountLeadingZeroes(~x & (x-1)); } // count leading ones inline UInt32 CountLeadingOnes(UInt32 x) { return CountLeadingZeroes(~x); } // count trailing ones inline UInt32 CountTrailingOnes(UInt32 x) { return 32 - CountLeadingZeroes(x & (~x-1)); } // number of bits required to represent x. inline UInt32 NumBits(UInt32 x) { return 32 - CountLeadingZeroes(x); } // base 2 log of next power of two greater or equal to x inline UInt32 Log2Ceil(UInt32 x) { return 32 - CountLeadingZeroes(x - 1); } // base 2 log of next power of two less or equal to x inline UInt32 Log2Floor(UInt32 x) { return 32 - CountLeadingZeroes(x) - 1; } // next power of two greater or equal to x inline UInt32 NextPowerOfTwo(UInt32 x) { return 1 << Log2Ceil(x); } // counting the one bits in a word inline UInt32 CountOnes(UInt32 x) { // secret magic algorithm for counting bits in a word. x = x - ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); return (((x + (x >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24; } // counting the zero bits in a word inline UInt32 CountZeroes(UInt32 x) { return CountOnes(~x); } // return the bit position (0..31) of the least significant bit inline UInt32 LSBitPos(UInt32 x) { return CountTrailingZeroes(x & -(SInt32)x); } // isolate the least significant bit inline UInt32 LSBit(UInt32 x) { return x & -(SInt32)x; } // return the bit position (0..31) of the most significant bit inline UInt32 MSBitPos(UInt32 x) { return 31 - CountLeadingZeroes(x); } // isolate the most significant bit inline UInt32 MSBit(UInt32 x) { return 1 << MSBitPos(x); } // Division optimized for power of 2 denominators inline UInt32 DivInt(UInt32 numerator, UInt32 denominator) { if(IsPowerOfTwo(denominator)) return numerator >> (31 - CountLeadingZeroes(denominator)); else return numerator/denominator; } #endif
6,196
C++
.h
179
32.810056
83
0.765541
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
4,411
CADebugPrintf.h
kyleneideck_BackgroundMusic/BGMDriver/PublicUtility/CADebugPrintf.h
/* File: CADebugPrintf.h Abstract: Part of CoreAudio Utility Classes Version: 1.0.1 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2013 Apple Inc. All Rights Reserved. */ #if !defined(__CADebugPrintf_h__) #define __CADebugPrintf_h__ //============================================================================= // Includes //============================================================================= #if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) #include <CoreAudio/CoreAudioTypes.h> #else #include "CoreAudioTypes.h" #endif //============================================================================= // Macros to redirect debugging output to various logging services //============================================================================= //#define CoreAudio_UseSysLog 1 //#define CoreAudio_UseSideFile "/CoreAudio-%d.txt" #if DEBUG || CoreAudio_Debug #if TARGET_OS_WIN32 #if defined(__cplusplus) extern "C" #endif extern int CAWin32DebugPrintf(char* inFormat, ...); #define DebugPrintfRtn CAWin32DebugPrintf #define DebugPrintfFile #define DebugPrintfLineEnding "\n" #define DebugPrintfFileComma #else #if CoreAudio_UseSysLog #include <sys/syslog.h> #define DebugPrintfRtn syslog #define DebugPrintfFile LOG_NOTICE #define DebugPrintfLineEnding "" #define DebugPrintfFileComma DebugPrintfFile, #elif defined(CoreAudio_UseSideFile) #include <stdio.h> #if defined(__cplusplus) extern "C" #endif void OpenDebugPrintfSideFile(); extern FILE* sDebugPrintfSideFile; #define DebugPrintfRtn fprintf #define DebugPrintfFile ((sDebugPrintfSideFile != NULL) ? sDebugPrintfSideFile : stderr) #define DebugPrintfLineEnding "\n" #define DebugPrintfFileComma DebugPrintfFile, #else #include <stdio.h> #define DebugPrintfRtn fprintf #define DebugPrintfFile stderr #define DebugPrintfLineEnding "\n" #define DebugPrintfFileComma DebugPrintfFile, #endif #endif #define DebugPrintf(inFormat, ...) DebugPrintfRtn(DebugPrintfFileComma inFormat DebugPrintfLineEnding, ## __VA_ARGS__) #else #define DebugPrintfRtn #define DebugPrintfFile #define DebugPrintfLineEnding #define DebugPrintfFileComma #define DebugPrintf(inFormat, ...) #endif #endif
4,598
C++
.h
100
42.87
119
0.732886
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
4,414
BGM_TestUtils.h
kyleneideck_BackgroundMusic/SharedSource/BGM_TestUtils.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGM_TestUtils.h // SharedSource // // Copyright © 2016, 2021 Kyle Neideck // #ifndef __SharedSource__BGM_TestUtils__ #define __SharedSource__BGM_TestUtils__ // Test Framework #import <XCTest/XCTest.h> #if defined(__cplusplus) // STL Includes #include <functional> // Fails the test if f doesn't throw ExpectedException when run. // (The "self" argument is required by XCTFail, presumably so it can report the context.) template<typename ExpectedException> void BGMShouldThrow(XCTestCase* self, const std::function<void()>& f) { #pragma unused (self) try { f(); XCTFail(); } catch (ExpectedException) { } } #endif /* defined(__cplusplus) */ #endif /* __SharedSource__BGM_TestUtils__ */
1,442
C++
.h
43
31.465116
89
0.736501
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,415
BGM_Utils.h
kyleneideck_BackgroundMusic/SharedSource/BGM_Utils.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGM_Utils.h // SharedSource // // Copyright © 2016-2020 Kyle Neideck // #ifndef SharedSource__BGM_Utils #define SharedSource__BGM_Utils // PublicUtility Includes #include "CADebugMacros.h" #if defined(__cplusplus) #include "CAException.h" // STL Includes #include <functional> #endif /* defined(__cplusplus) */ // System Includes #include <mach/error.h> #include <dispatch/dispatch.h> #pragma mark Macros // The Assert macro from CADebugMacros with support for format strings and line numbers added. #if DEBUG #define BGMAssert(inCondition, inMessage, ...) \ if(!(inCondition)) \ { \ DebugMsg("%s:%d:%s: " inMessage, \ __FILE__, \ __LINE__, \ __FUNCTION__, \ ## __VA_ARGS__); \ __ASSERT_STOP; \ } #else #define BGMAssert(inCondition, inMessage, ...) #endif /* DEBUG */ #define BGMAssertNonNull(expression) \ BGMAssertNonNull2((expression), #expression) #define BGMAssertNonNull2(expression, expressionStr) \ BGMAssert((expression), \ "%s:%d:%s: '%s' is null", \ __FILE__, \ __LINE__, \ __FUNCTION__, \ expressionStr); // Used to give the first 3 arguments of BGM_Utils::LogAndSwallowExceptions and // BGM_Utils::LogUnexpectedExceptions (and probably others in future). Mainly so we can call those // functions directly instead of using the macro wrappers. #define BGMDbgArgs __FILE__, __LINE__, __FUNCTION__ #pragma mark Objective-C Macros #if defined(__OBJC__) #if __has_feature(objc_generics) // This trick is from https://gist.github.com/robb/d55b72d62d32deaee5fa @interface BGMNonNullCastHelper<__covariant T> - (nonnull T) asNonNull; @end // Explicitly casts expressions from nullable to non-null. Only works with expressions that // evaluate to Objective-C objects. Use BGM_Utils::NN for other types. // // TODO: Replace existing non-null casts with this. #define BGMNN(expression) ({ \ __typeof((expression)) value = (expression); \ BGMAssertNonNull2(value, #expression); \ BGMNonNullCastHelper<__typeof((expression))>* helper; \ (__typeof(helper.asNonNull) __nonnull)value; \ }) #else /* __has_feature(objc_generics) */ #define BGMNN(expression) ({ \ id value = (expression); \ BGMAssertNonNull2(value, #expression); \ value; \ }) #endif /* __has_feature(objc_generics) */ #endif /* defined(__OBJC__) */ #pragma mark C++ Macros #if defined(__cplusplus) #define BGMLogException(exception) \ BGM_Utils::LogException(__FILE__, __LINE__, __FUNCTION__, exception) #define BGMLogExceptionIn(callerName, exception) \ BGM_Utils::LogException(__FILE__, __LINE__, callerName, exception) #define BGMLogAndSwallowExceptions(callerName, function) \ BGM_Utils::LogAndSwallowExceptions(__FILE__, __LINE__, callerName, function) #define BGMLogAndSwallowExceptionsMsg(callerName, message, function) \ BGM_Utils::LogAndSwallowExceptions(__FILE__, __LINE__, callerName, message, function) #define BGMLogUnexpectedException() \ BGM_Utils::LogUnexpectedException(__FILE__, __LINE__, __FUNCTION__) #define BGMLogUnexpectedExceptionIn(callerName) \ BGM_Utils::LogUnexpectedException(__FILE__, __LINE__, callerName) #define BGMLogUnexpectedExceptions(callerName, function) \ BGM_Utils::LogUnexpectedExceptions(__FILE__, __LINE__, callerName, function) #define BGMLogUnexpectedExceptionsMsg(callerName, message, function) \ BGM_Utils::LogUnexpectedExceptions(__FILE__, __LINE__, callerName, message, function) #endif /* defined(__cplusplus) */ #pragma clang assume_nonnull begin #pragma mark C Utility Functions dispatch_queue_t BGMGetDispatchQueue_PriorityUserInteractive(void); #if defined(__cplusplus) #pragma mark C++ Utility Functions namespace BGM_Utils { // Used to explicitly cast from nullable to non-null. For Objective-C objects, use the BGMNN // macro (above). template <typename T> inline T __nonnull NN(T __nullable v) { BGMAssertNonNull(v); return static_cast<T __nonnull>(v); } // Log (and swallow) errors returned by Mach functions. Returns false if there was an error. bool LogIfMachError(const char* callerName, const char* errorReturnedBy, mach_error_t error); // Similar to ThrowIfKernelError from CADebugMacros.h, but also logs (in debug builds) the // Mach error string that corresponds to the error. void ThrowIfMachError(const char* callerName, const char* errorReturnedBy, mach_error_t error); // If function throws an exception, log an error and continue. // // Fails/stops debug builds. It's likely that if we log an error for an exception in release // builds, even if it's expected (i.e. not a bug in Background Music), we'd want to know if // it gets thrown during testing/debugging. OSStatus LogAndSwallowExceptions(const char* __nullable fileName, int lineNumber, const char* callerName, const std::function<void(void)>& function); OSStatus LogAndSwallowExceptions(const char* __nullable fileName, int lineNumber, const char* callerName, const char* __nullable message, const std::function<void(void)>& function); void LogException(const char* __nullable fileName, int lineNumber, const char* callerName, const CAException& e); void LogUnexpectedException(const char* __nullable fileName, int lineNumber, const char* callerName); OSStatus LogUnexpectedExceptions(const char* callerName, const std::function<void(void)>& function); OSStatus LogUnexpectedExceptions(const char* __nullable fileName, int lineNumber, const char* callerName, const std::function<void(void)>& function); // Log unexpected exceptions and continue. // // Generally, you don't want to use this unless the alternative is to crash. And even then // crashing is often the better option. (Especially if we've added crash reporting by the // time you're reading this.) // // Fails/stops debug builds. // // TODO: Allow a format string and args for the message. OSStatus LogUnexpectedExceptions(const char* __nullable fileName, int lineNumber, const char* callerName, const char* __nullable message, const std::function<void(void)>& function); } #endif /* defined(__cplusplus) */ #pragma clang assume_nonnull end #endif /* SharedSource__BGM_Utils */
8,464
C++
.h
173
40.121387
98
0.605732
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,416
BGMXPCProtocols.h
kyleneideck_BackgroundMusic/SharedSource/BGMXPCProtocols.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMXPCProtocols.h // SharedSource // // Copyright © 2016, 2017 Kyle Neideck // // Local Includes #include "BGM_Types.h" // System Includes #import <Foundation/Foundation.h> #pragma clang assume_nonnull begin static NSString* kBGMXPCHelperMachServiceName = @kBGMXPCHelperBundleID; // The protocol that BGMXPCHelper will vend as its XPC API. @protocol BGMXPCHelperXPCProtocol // Tells BGMXPCHelper that the caller is BGMApp and passes a listener endpoint that BGMXPCHelper can use to create connections to BGMApp. // BGMXPCHelper may also pass the endpoint on to BGMDriver so it can do the same. - (void) registerAsBGMAppWithListenerEndpoint:(NSXPCListenerEndpoint*)endpoint reply:(void (^)(void))reply; - (void) unregisterAsBGMApp; // BGMDriver calls this remote method when it wants BGMApp to start IO. BGMXPCHelper passes the message along and then passes the response // back. This allows BGMDriver to wait for the audio hardware to start up, which means it can let the HAL know when it's safe to start // sending us audio data from the client. // // If BGMApp can be reached, the error it returns will be passed the reply block. Otherwise, the reply block will be passed an error with // one of the kBGMXPC_* error codes. It may have an underlying error using one of the NSXPCConnection* error codes from FoundationErrors.h. - (void) startBGMAppPlayThroughSyncWithReply:(void (^)(NSError*))reply forUISoundsDevice:(BOOL)isUI; // BGMXPCHelper will set the system's default output device to deviceID if it loses its connection // to BGMApp and BGMApp has left BGMDevice as the default device. It waits for a short time first to // give BGMApp a chance to fix the connection. // // This is so BGMDevice isn't left as the default device if BGMApp crashes or otherwise terminates // abnormally. If audio is played to BGMDevice and BGMApp isn't running, the user won't hear it. - (void) setOutputDeviceToMakeDefaultOnAbnormalTermination:(AudioObjectID)deviceID; @end // The protocol that BGMApp will vend as its XPC API. @protocol BGMAppXPCProtocol - (void) startPlayThroughSyncWithReply:(void (^)(NSError*))reply forUISoundsDevice:(BOOL)isUI; @end #pragma clang assume_nonnull end
2,911
C++
.h
52
54.576923
139
0.79105
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,419
MockAudioObject.h
kyleneideck_BackgroundMusic/BGMApp/BGMAppTests/UnitTests/Mocks/MockAudioObject.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // MockAudioObject.h // BGMAppUnitTests // // Copyright © 2020 Kyle Neideck // #ifndef BGMAppUnitTests__MockAudioObject #define BGMAppUnitTests__MockAudioObject // PublicUtility Includes #include "CACFString.h" // STL Includes #include <set> // System Includes #include <CoreAudio/CoreAudio.h> /*! * The base class for mock audio objects in our mock CoreAudio HAL. Maps to kAudioObjectClassID * (AudioHardwareBase.h) in the HAL's API class hierarchy. */ class MockAudioObject { public: MockAudioObject(AudioObjectID inAudioObjectID); virtual ~MockAudioObject() = default; AudioObjectID GetObjectID() const; /*! * The properties that callers have added listeners for (and haven't since removed). See * CAHALAudioObject::AddPropertyListener and CAHALAudioObject::RemovePropertyListener. */ std::set<AudioObjectPropertySelector> mPropertiesWithListeners; private: AudioObjectID mAudioObjectID; }; #endif /* BGMAppUnitTests__MockAudioObject */
1,704
C++
.h
47
34.06383
95
0.776628
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,420
MockAudioDevice.h
kyleneideck_BackgroundMusic/BGMApp/BGMAppTests/UnitTests/Mocks/MockAudioDevice.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // MockAudioObject.h // BGMAppUnitTests // // Copyright © 2020 Kyle Neideck // #ifndef BGMAppUnitTests__MockAudioDevice #define BGMAppUnitTests__MockAudioDevice // Superclass Includes #include "MockAudioObject.h" // STL Includes #include <string> /*! * A mock audio device in our mock CoreAudio HAL. In the HAL's API class hierarchy, the base class * for audio devices, kAudioDeviceClassID, is the audio objects class, kAudioObjectClassID. * * The unit tests generally use instances of this class to verify the HAL is being queried correctly * and to control the responses that the code they're testing will receive from the mock HAL. */ class MockAudioDevice : public MockAudioObject { public: MockAudioDevice(const std::string& inUID); /*! * @return This device's music player bundle ID property. * @throws If this device isn't a mock of BGMDevice. */ CACFString GetPlayerBundleID() const; /*! * Set this device's music player bundle ID property. * @throws If this device isn't a mock of BGMDevice. */ void SetPlayerBundleID(const CACFString& inPlayerBundleID); /*! * The device's UID. The UID is a persistent token used to identify a particular audio device * across boot sessions. */ const std::string mUID; Float64 mNominalSampleRate; UInt32 mIOBufferSize; private: CACFString mPlayerBundleID { "" }; }; #endif /* BGMAppUnitTests__MockAudioDevice */
2,175
C++
.h
60
33.383333
100
0.747859
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,421
MockAudioObjects.h
kyleneideck_BackgroundMusic/BGMApp/BGMAppTests/UnitTests/Mocks/MockAudioObjects.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // MockAudioObjects.h // BGMAppUnitTests // // Copyright © 2020 Kyle Neideck // #ifndef BGMAppUnitTests__MockAudioObjects #define BGMAppUnitTests__MockAudioObjects // Local Includes #include "MockAudioObject.h" #include "MockAudioDevice.h" // STL Includes #include <map> #include <memory> #include <string> // System Includes #include <CoreAudio/CoreAudio.h> class MockAudioObjects { public: /*! * Create a mock audio device in the mock CoreAudio HAL. * * The mock device will then be accessible using GetAudioObject and GetAudioDevice. The * Mock_CAHAL* implementations will access the mock device when they query the mock HAL. * * Unit tests can check the mock device to verify the code they're testing has called the mocked * CAHAL classes correctly. They can also modify the mock device to control the Mock_CAHAL* * implementations, e.g. to have CAHALAudioDevice::IsAlive return false so the test can cover * the case where a device is being removed from the system. * * @param inUID The UID string to give the device. The UID is a persistent token used to * identify a particular audio device across boot sessions. * @return The mock device. */ static std::shared_ptr<MockAudioDevice> CreateMockDevice(const std::string& inUID); /*! * Remove all mock audio objects from the mock HAL. (Currently, mock devices are the only mock * objects that can be created.) */ static void DestroyMocks(); /*! Get a mock audio object by its ID. */ static std::shared_ptr<MockAudioObject> GetAudioObject(AudioObjectID inAudioObjectID); /*! Get a mock audio device by its ID. */ static std::shared_ptr<MockAudioDevice> GetAudioDevice(AudioObjectID inAudioDeviceID); /*! Get a mock audio device by its UID. */ static std::shared_ptr<MockAudioDevice> GetAudioDevice(const std::string& inUID); /*! Get a mock audio device by its UID. */ static std::shared_ptr<MockAudioDevice> GetAudioDevice(CFStringRef inUID); private: typedef std::map<AudioObjectID, std::shared_ptr<MockAudioDevice>> MockDeviceMap; typedef std::map<std::string, std::shared_ptr<MockAudioDevice>> MockDeviceMapByUID; static std::shared_ptr<MockAudioDevice> GetAudioDeviceOrNull(AudioObjectID inAudioDeviceID); /*! Maps IDs to mocked audio devices. */ static MockDeviceMap sDevices; /*! Maps UIDs (ID strings) to mocked audio devices. */ static MockDeviceMapByUID sDevicesByUID; }; #endif /* BGMAppUnitTests__MockAudioObjects */
3,280
C++
.h
73
41.493151
100
0.744828
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,422
BGMApp.h
kyleneideck_BackgroundMusic/BGMApp/BGMAppTests/UITests/BGMApp.h
/* * BGMApp.h * * Generated with * sdef "/Applications/Background Music.app" | sdp -fh --basename BGMApp */ #import <AppKit/AppKit.h> #import <ScriptingBridge/ScriptingBridge.h> @class BGMAppOutputDevice, BGMAppApplication; /* * Background Music */ // A hardware device that can play audio @interface BGMAppOutputDevice : SBObject @property (copy, readonly) NSString *name; // The name of the output device. @property BOOL selected; // Is this the device to be used for audio output? @end // The application program @interface BGMAppApplication : SBApplication - (SBElementArray<BGMAppOutputDevice *> *) outputDevices; @property (copy) BGMAppOutputDevice *selectedOutputDevice; // The device to be used for audio output @end
749
C++
.h
22
32.090909
101
0.778401
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,423
BGMXPCListenerDelegate.h
kyleneideck_BackgroundMusic/BGMApp/BGMXPCHelper/BGMXPCListenerDelegate.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMXPCListenerDelegate.h // BGMXPCHelper // // Copyright © 2016 Kyle Neideck // // System Includes #import <Foundation/Foundation.h> #pragma clang assume_nonnull begin @interface BGMXPCListenerDelegate : NSObject <NSXPCListenerDelegate> // The UID of the _coreaudiod user, which BGMDriver runs under. This is used in debug builds, usually to warn if a remote method is // called by BGMApp when it's only meant to be called by BGMDriver, or vice versa. + (uid_t) _coreaudiodUID; - (BOOL) listener:(NSXPCListener*)listener shouldAcceptNewConnection:(NSXPCConnection*)newConnection; @end #pragma clang assume_nonnull end
1,343
C++
.h
30
43.3
131
0.78137
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,424
BGMXPCHelperService.h
kyleneideck_BackgroundMusic/BGMApp/BGMXPCHelper/BGMXPCHelperService.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMXPCHelperService.h // BGMXPCHelper // // Copyright © 2016 Kyle Neideck // // Local Includes #import "BGMXPCProtocols.h" // System Includes #import <Foundation/Foundation.h> // This object implements the protocol which we have defined. It provides the actual behavior for the service. It is // 'exported' by the service to make it available to the process hosting the service over an NSXPCConnection. @interface BGMXPCHelperService : NSObject <BGMXPCHelperXPCProtocol> - (id) initWithConnection:newConnection; @end
1,236
C++
.h
29
41.344828
116
0.781485
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,425
CADebugMacros.h
kyleneideck_BackgroundMusic/BGMApp/PublicUtility/CADebugMacros.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // CADebugMacros.h // PublicUtility // // Copyright (C) 2014 Apple Inc. All Rights Reserved. // Copyright © 2016, 2020 Kyle Neideck // // Original license header follows. // /* File: CADebugMacros.h Abstract: Part of CoreAudio Utility Classes Version: 1.1 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2014 Apple Inc. All Rights Reserved. */ #if !defined(__CADebugMacros_h__) #define __CADebugMacros_h__ //============================================================================= // Includes //============================================================================= #if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) #include <CoreAudio/CoreAudioTypes.h> #else #include "CoreAudioTypes.h" #endif #include "CADebugPrintf.h" #include <stdarg.h> //============================================================================= // CADebugMacros //============================================================================= //#define CoreAudio_StopOnFailure 1 //#define CoreAudio_TimeStampMessages 1 //#define CoreAudio_ThreadStampMessages 1 //#define CoreAudio_FlushDebugMessages 1 #if TARGET_RT_BIG_ENDIAN #define CA4CCToCString(the4CC) { ((char*)&the4CC)[0], ((char*)&the4CC)[1], ((char*)&the4CC)[2], ((char*)&the4CC)[3], 0 } #define CACopy4CCToCString(theCString, the4CC) { theCString[0] = ((char*)&the4CC)[0]; theCString[1] = ((char*)&the4CC)[1]; theCString[2] = ((char*)&the4CC)[2]; theCString[3] = ((char*)&the4CC)[3]; theCString[4] = 0; } #else #define CA4CCToCString(the4CC) { ((char*)&the4CC)[3], ((char*)&the4CC)[2], ((char*)&the4CC)[1], ((char*)&the4CC)[0], 0 } #define CACopy4CCToCString(theCString, the4CC) { theCString[0] = ((char*)&the4CC)[3]; theCString[1] = ((char*)&the4CC)[2]; theCString[2] = ((char*)&the4CC)[1]; theCString[3] = ((char*)&the4CC)[0]; theCString[4] = 0; } #endif // This is a macro that does a sizeof and casts the result to a UInt32. This is useful for all the // places where -wshorten64-32 catches assigning a sizeof expression to a UInt32. // For want of a better place to park this, we'll park it here. #define SizeOf32(X) ((UInt32)sizeof(X)) // This is a macro that does a offsetof and casts the result to a UInt32. This is useful for all the // places where -wshorten64-32 catches assigning an offsetof expression to a UInt32. // For want of a better place to park this, we'll park it here. #define OffsetOf32(X, Y) ((UInt32)offsetof(X, Y)) // This macro casts the expression to a UInt32. It is called out specially to allow us to track casts // that have been added purely to avert -wshorten64-32 warnings on 64 bit platforms. // For want of a better place to park this, we'll park it here. #define ToUInt32(X) ((UInt32)(X)) #define ToSInt32(X) ((SInt32)(X)) #pragma mark Basic Definitions // basic debugging print routines #if TARGET_OS_MAC && !TARGET_API_MAC_CARBON extern void DebugStr(const unsigned char* debuggerMsg); #define DebugMessage(msg) DebugStr("\p"msg) #define DebugMessageN1(msg, N1) #define DebugMessageN2(msg, N1, N2) #define DebugMessageN3(msg, N1, N2, N3) #else #if (CoreAudio_FlushDebugMessages && !CoreAudio_UseSysLog) || defined(CoreAudio_UseSideFile) #define FlushRtn ,fflush(DebugPrintfFile) #else #define FlushRtn #endif #if CoreAudio_ThreadStampMessages #include <pthread.h> #include "CAHostTimeBase.h" #if TARGET_RT_64_BIT #define DebugPrintfThreadIDFormat "%16p" #else #define DebugPrintfThreadIDFormat "%8p" #endif #define DebugMsg(inFormat, ...) DebugPrintf("%17qd: " DebugPrintfThreadIDFormat " " inFormat, CAHostTimeBase::GetCurrentTimeInNanos(), pthread_self(), ## __VA_ARGS__) FlushRtn #elif CoreAudio_TimeStampMessages #include "CAHostTimeBase.h" #define DebugMsg(inFormat, ...) DebugPrintf("%17qd: " inFormat, CAHostTimeBase::GetCurrentTimeInNanos(), ## __VA_ARGS__) FlushRtn #else #define DebugMsg(inFormat, ...) DebugPrintf(inFormat, ## __VA_ARGS__) FlushRtn #endif #endif #if DEBUG || CoreAudio_Debug // can be used to break into debugger immediately, also see CADebugger #define BusError() { long* p=NULL; *p=0; } void DebugPrint(const char *fmt, ...); // can be used like printf #ifndef DEBUGPRINT #define DEBUGPRINT(msg) DebugPrint msg // have to double-parenthesize arglist (see Debugging.h) #endif #if VERBOSE #define vprint(msg) DEBUGPRINT(msg) #else #define vprint(msg) #endif // Original macro keeps its function of turning on and off use of CADebuggerStop() for both asserts and throws. // For backwards compat, it overrides any setting of the two sub-macros. #if CoreAudio_StopOnFailure #include "CADebugger.h" #undef CoreAudio_StopOnAssert #define CoreAudio_StopOnAssert 1 #undef CoreAudio_StopOnThrow #define CoreAudio_StopOnThrow 1 #define STOP CADebuggerStop() #else #define STOP #endif #if CoreAudio_StopOnAssert #if !CoreAudio_StopOnFailure #include "CADebugger.h" #define STOP #endif #define __ASSERT_STOP CADebuggerStop() #else #define __ASSERT_STOP #endif #if CoreAudio_StopOnThrow #if !CoreAudio_StopOnFailure #include "CADebugger.h" #define STOP #endif #define __THROW_STOP CADebuggerStop() #else #define __THROW_STOP #endif #else #ifndef DEBUGPRINT #define DEBUGPRINT(msg) #endif #define vprint(msg) #define STOP #define __ASSERT_STOP #define __THROW_STOP #endif // Old-style numbered DebugMessage calls are implemented in terms of DebugMsg() now #define DebugMessage(msg) DebugMsg(msg) #define DebugMessageN1(msg, N1) DebugMsg(msg, N1) #define DebugMessageN2(msg, N1, N2) DebugMsg(msg, N1, N2) #define DebugMessageN3(msg, N1, N2, N3) DebugMsg(msg, N1, N2, N3) #define DebugMessageN4(msg, N1, N2, N3, N4) DebugMsg(msg, N1, N2, N3, N4) #define DebugMessageN5(msg, N1, N2, N3, N4, N5) DebugMsg(msg, N1, N2, N3, N4, N5) #define DebugMessageN6(msg, N1, N2, N3, N4, N5, N6) DebugMsg(msg, N1, N2, N3, N4, N5, N6) #define DebugMessageN7(msg, N1, N2, N3, N4, N5, N6, N7) DebugMsg(msg, N1, N2, N3, N4, N5, N6, N7) #define DebugMessageN8(msg, N1, N2, N3, N4, N5, N6, N7, N8) DebugMsg(msg, N1, N2, N3, N4, N5, N6, N7, N8) #define DebugMessageN9(msg, N1, N2, N3, N4, N5, N6, N7, N8, N9) DebugMsg(msg, N1, N2, N3, N4, N5, N6, N7, N8, N9) // BGM edit: Added __printflike and va_list versions. void LogError(const char *fmt, ...) __printflike(1, 2); // writes to syslog (and stderr if debugging) void vLogError(const char *fmt, va_list args); void LogWarning(const char *fmt, ...) __printflike(1, 2); // writes to syslog (and stderr if debugging) void vLogWarning(const char *fmt, va_list args); #define NO_ACTION (void)0 #if DEBUG || CoreAudio_Debug #pragma mark Debug Macros #define Assert(inCondition, inMessage) \ if(!(inCondition)) \ { \ DebugMessage(inMessage); \ __ASSERT_STOP; \ } #define AssertFileLine(inCondition, inMessage) \ if(!(inCondition)) \ { \ DebugMessageN3("%s, line %d: %s", __FILE__, __LINE__, inMessage); \ __ASSERT_STOP; \ } #define AssertNoError(inError, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ char __4CC[5] = CA4CCToCString(__Err); \ DebugMessageN2(inMessage ", Error: %d (%s)", (int)__Err, __4CC); \ __ASSERT_STOP; \ } \ } #define AssertNoKernelError(inError, inMessage) \ { \ unsigned int __Err = (unsigned int)(inError); \ if(__Err != 0) \ { \ DebugMessageN1(inMessage ", Error: 0x%X", __Err); \ __ASSERT_STOP; \ } \ } #define AssertNotNULL(inPtr, inMessage) \ { \ if((inPtr) == NULL) \ { \ DebugMessage(inMessage); \ __ASSERT_STOP; \ } \ } #define FailIf(inCondition, inHandler, inMessage) \ if(inCondition) \ { \ DebugMessage(inMessage); \ STOP; \ goto inHandler; \ } #define FailWithAction(inCondition, inAction, inHandler, inMessage) \ if(inCondition) \ { \ DebugMessage(inMessage); \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfNULL(inPointer, inAction, inHandler, inMessage) \ if((inPointer) == NULL) \ { \ DebugMessage(inMessage); \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfKernelError(inKernelError, inAction, inHandler, inMessage) \ { \ unsigned int __Err = (inKernelError); \ if(__Err != 0) \ { \ DebugMessageN1(inMessage ", Error: 0x%X", __Err); \ STOP; \ { inAction; } \ goto inHandler; \ } \ } #define FailIfError(inError, inAction, inHandler, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ char __4CC[5] = CA4CCToCString(__Err); \ DebugMessageN2(inMessage ", Error: %ld (%s)", (long int)__Err, __4CC); \ STOP; \ { inAction; } \ goto inHandler; \ } \ } #define FailIfNoMessage(inCondition, inHandler, inMessage) \ if(inCondition) \ { \ STOP; \ goto inHandler; \ } #define FailWithActionNoMessage(inCondition, inAction, inHandler, inMessage) \ if(inCondition) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfNULLNoMessage(inPointer, inAction, inHandler, inMessage) \ if((inPointer) == NULL) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfKernelErrorNoMessage(inKernelError, inAction, inHandler, inMessage) \ { \ unsigned int __Err = (inKernelError); \ if(__Err != 0) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } \ } #define FailIfErrorNoMessage(inError, inAction, inHandler, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } \ } #if defined(__cplusplus) #define Throw(inException) __THROW_STOP; throw (inException) #define ThrowIf(inCondition, inException, inMessage) \ if(inCondition) \ { \ DebugMessage(inMessage); \ Throw(inException); \ } #define ThrowIfNULL(inPointer, inException, inMessage) \ if((inPointer) == NULL) \ { \ DebugMessage(inMessage); \ Throw(inException); \ } #define ThrowIfKernelError(inKernelError, inException, inMessage) \ { \ int __Err = (inKernelError); \ if(__Err != 0) \ { \ DebugMessageN1(inMessage ", Error: 0x%X", __Err); \ Throw(inException); \ } \ } #define ThrowIfError(inError, inException, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ char __4CC[5] = CA4CCToCString(__Err); \ DebugMessageN2(inMessage ", Error: %d (%s)", (int)__Err, __4CC); \ Throw(inException); \ } \ } #if TARGET_OS_WIN32 #define ThrowIfWinError(inError, inException, inMessage) \ { \ HRESULT __Err = (inError); \ if(FAILED(__Err)) \ { \ DebugMessageN2(inMessage ", Code: %d, Facility: 0x%X", HRESULT_CODE(__Err), HRESULT_FACILITY(__Err)); \ Throw(inException); \ } \ } #endif #define SubclassResponsibility(inMethodName, inException) \ { \ DebugMessage(inMethodName": Subclasses must implement this method"); \ Throw(inException); \ } #endif // defined(__cplusplus) #else #pragma mark Release Macros #define Assert(inCondition, inMessage) \ if(!(inCondition)) \ { \ __ASSERT_STOP; \ } #define AssertFileLine(inCondition, inMessage) Assert(inCondition, inMessage) #define AssertNoError(inError, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ __ASSERT_STOP; \ } \ } #define AssertNoKernelError(inError, inMessage) \ { \ unsigned int __Err = (unsigned int)(inError); \ if(__Err != 0) \ { \ __ASSERT_STOP; \ } \ } #define AssertNotNULL(inPtr, inMessage) \ { \ if((inPtr) == NULL) \ { \ __ASSERT_STOP; \ } \ } #define FailIf(inCondition, inHandler, inMessage) \ if(inCondition) \ { \ STOP; \ goto inHandler; \ } #define FailWithAction(inCondition, inAction, inHandler, inMessage) \ if(inCondition) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfNULL(inPointer, inAction, inHandler, inMessage) \ if((inPointer) == NULL) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfKernelError(inKernelError, inAction, inHandler, inMessage) \ if((inKernelError) != 0) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfError(inError, inAction, inHandler, inMessage) \ if((inError) != 0) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfNoMessage(inCondition, inHandler, inMessage) \ if(inCondition) \ { \ STOP; \ goto inHandler; \ } #define FailWithActionNoMessage(inCondition, inAction, inHandler, inMessage) \ if(inCondition) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfNULLNoMessage(inPointer, inAction, inHandler, inMessage) \ if((inPointer) == NULL) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } #define FailIfKernelErrorNoMessage(inKernelError, inAction, inHandler, inMessage) \ { \ unsigned int __Err = (inKernelError); \ if(__Err != 0) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } \ } #define FailIfErrorNoMessage(inError, inAction, inHandler, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ STOP; \ { inAction; } \ goto inHandler; \ } \ } #if defined(__cplusplus) #define Throw(inException) __THROW_STOP; throw (inException) #define ThrowIf(inCondition, inException, inMessage) \ if(inCondition) \ { \ Throw(inException); \ } #define ThrowIfNULL(inPointer, inException, inMessage) \ if((inPointer) == NULL) \ { \ Throw(inException); \ } #define ThrowIfKernelError(inKernelError, inException, inMessage) \ { \ int __Err = (inKernelError); \ if(__Err != 0) \ { \ Throw(inException); \ } \ } #define ThrowIfError(inError, inException, inMessage) \ { \ SInt32 __Err = (inError); \ if(__Err != 0) \ { \ Throw(inException); \ } \ } #if TARGET_OS_WIN32 #define ThrowIfWinError(inError, inException, inMessage) \ { \ HRESULT __Err = (inError); \ if(FAILED(__Err)) \ { \ Throw(inException); \ } \ } #endif #define SubclassResponsibility(inMethodName, inException) \ { \ Throw(inException); \ } #endif // defined(__cplusplus) #endif // DEBUG || CoreAudio_Debug #endif
21,026
C++
.h
527
36.487666
218
0.554614
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,428
BGMDebugLogging.h
kyleneideck_BackgroundMusic/BGMApp/PublicUtility/BGMDebugLogging.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMDebugLogging.h // PublicUtility // // Copyright © 2020 Kyle Neideck // // Functions to globally enable/disable debug logging, i.e. more detailed logging to help diagnose // bugs. If debug logging is enabled, the DebugMsg macro from CADebugMacros.h (and possibly others) // will log messages. If not, it won't do anything. // // If the preprocessor macro CoreAudio_UseSysLog is true, which is currently the case for all build // variants (see BGMApp/BGMApp.xcodeproj/project.pbxproj and // BGMDriver/BGMDriver.xcodeproj/project.pbxproj), those messages will be logged using syslog and // can be read using Console.app. Try searching for "background music", "bgm" or "coreaudiod". // // Debug logging is enabled by default in debug builds, but in release builds you have to enable it // by option-clicking the status bar icon and then checking the Debug Logging menu item. Enabling // debug logging probably won't cause glitches, but we don't try to guarantee that and it's not // well tested. // #ifndef PublicUtility__BGMDebugLogging #define PublicUtility__BGMDebugLogging #pragma clang assume_nonnull begin /*! * @return Non-zero if debug logging is globally enabled. (Probably -- it's not synchronised.) * Real-time safe. */ #if defined(__cplusplus) extern "C" #endif int BGMDebugLoggingIsEnabled(void); /*! * @param inEnabled Non-zero to globally enable debug logging, zero to disable it. The change might * not be visible to other threads immediately. */ #if defined(__cplusplus) extern "C" #endif void BGMSetDebugLoggingEnabled(int inEnabled); #pragma clang assume_nonnull end #endif /* PublicUtility__BGMDebugLogging */
2,390
C++
.h
55
42.2
100
0.764504
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,431
CADebugger.h
kyleneideck_BackgroundMusic/BGMApp/PublicUtility/CADebugger.h
/* File: CADebugger.h Abstract: Part of CoreAudio Utility Classes Version: 1.1 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2014 Apple Inc. All Rights Reserved. */ #if !defined(__CADebugger_h__) #define __CADebugger_h__ //============================================================================= // Includes //============================================================================= #if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) #include <CoreAudio/CoreAudioTypes.h> #else #include <CoreAudioTypes.h> #endif //============================================================================= // CADebugger //============================================================================= // BGM edit: Added extern "C" so CADebugger (and headers that include it) can be used in Obj-C. #ifdef __cplusplus extern "C" { #endif #if TARGET_API_MAC_OSX extern bool CAIsDebuggerAttached(void); #endif extern void CADebuggerStop(void); #ifdef __cplusplus } #endif #endif
3,276
C++
.h
65
48.4
95
0.721178
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
4,434
CADebugPrintf.h
kyleneideck_BackgroundMusic/BGMApp/PublicUtility/CADebugPrintf.h
/* File: CADebugPrintf.h Abstract: Part of CoreAudio Utility Classes Version: 1.1 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2014 Apple Inc. All Rights Reserved. */ #if !defined(__CADebugPrintf_h__) #define __CADebugPrintf_h__ //============================================================================= // Includes //============================================================================= #if !defined(__COREAUDIO_USE_FLAT_INCLUDES__) #include <CoreAudio/CoreAudioTypes.h> #else #include "CoreAudioTypes.h" #endif #include "BGMDebugLogging.h" //============================================================================= // Macros to redirect debugging output to various logging services //============================================================================= //#define CoreAudio_UseSysLog 1 //#define CoreAudio_UseSideFile "/CoreAudio-%d.txt" #if TARGET_OS_WIN32 #if defined(__cplusplus) extern "C" #endif extern int CAWin32DebugPrintf(char* inFormat, ...); #define DebugPrintfRtn CAWin32DebugPrintf #define DebugPrintfFile #define DebugPrintfLineEnding "\n" #define DebugPrintfFileComma #else #if CoreAudio_UseSysLog #include <sys/syslog.h> #define DebugPrintfRtn syslog #define DebugPrintfFile LOG_NOTICE #define DebugPrintfLineEnding "" #define DebugPrintfFileComma DebugPrintfFile, #elif defined(CoreAudio_UseSideFile) #include <stdio.h> #if defined(__cplusplus) extern "C" #endif void OpenDebugPrintfSideFile(); extern FILE* sDebugPrintfSideFile; #define DebugPrintfRtn fprintf #define DebugPrintfFile ((sDebugPrintfSideFile != NULL) ? sDebugPrintfSideFile : stderr) #define DebugPrintfLineEnding "\n" #define DebugPrintfFileComma DebugPrintfFile, #else #include <stdio.h> #define DebugPrintfRtn fprintf #define DebugPrintfFile stderr #define DebugPrintfLineEnding "\n" #define DebugPrintfFileComma DebugPrintfFile, #endif #endif #define DebugPrintf(inFormat, ...) \ do { \ if (BGMDebugLoggingIsEnabled()) { \ DebugPrintfRtn(DebugPrintfFileComma inFormat DebugPrintfLineEnding, ## __VA_ARGS__); \ } \ } while (0) #endif
4,438
C++
.h
98
42.816327
102
0.736976
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
4,435
BGMBackgroundMusicDevice.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMBackgroundMusicDevice.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMBackgroundMusicDevice.h // BGMApp // // Copyright © 2017 Kyle Neideck // // The interface to BGMDevice, the main virtual device published by BGMDriver, and the second // instance of that device, which handles UI-related audio. In most cases, users of this class // should be able to think of it as representing a single device. // // BGMDevice is the device that appears as "Background Music" in programs that list the output // devices, e.g. System Preferences. It receives the system's audio, processes it and sends it to // BGMApp by publishing an input stream. BGMApp then plays the audio on the user's real output // device. // // See BGMDriver/BGMDriver/BGM_Device.h. // #ifndef BGMApp__BGMBackgroundMusicDevice #define BGMApp__BGMBackgroundMusicDevice // Superclass Includes #include "BGMAudioDevice.h" // Local Includes #include "BGM_Types.h" // PublicUtility Includes #include "CACFString.h" // STL Includes #include <vector> #pragma clang assume_nonnull begin class BGMBackgroundMusicDevice : public BGMAudioDevice { #pragma mark Construction/Destruction public: /*! @throws CAException If BGMDevice is not found or the HAL returns an error when queried for BGMDevice's current Audio Object ID. */ BGMBackgroundMusicDevice(); virtual ~BGMBackgroundMusicDevice(); #pragma mark Systemwide Default Device public: /*! Set BGMDevice as the default audio device for all processes. @throws CAException If the HAL responds with an error. */ void SetAsOSDefault(); /*! Replace BGMDevice as the default device with the output device. @throws CAException If the HAL responds with an error. */ void UnsetAsOSDefault(AudioDeviceID inOutputDeviceID); #pragma mark App Volumes public: /*! @return The current value of BGMDevice's kAudioDeviceCustomPropertyAppVolumes property. See BGM_Types.h. @throws CAException If the HAL returns an error or a non-array type. Callers are responsible for validating and type-checking the values contained in the array. */ CFArrayRef GetAppVolumes() const; /*! @param inVolume A value between kAppRelativeVolumeMinRawValue and kAppRelativeVolumeMaxRawValue from BGM_Types.h. See kBGMAppVolumesKey_RelativeVolume in BGM_Types.h. @param inAppProcessID The ID of app's main process (or the process it uses to play audio, if you've managed to figure that out). If an app has multiple audio processes, you can just set the volume for each of them. Pass -1 to omit this param. @param inAppBundleID The app's bundle ID. Pass null to omit this param. @throws CAException If the HAL returns an error when this function sends the volume change to BGMDevice. */ void SetAppVolume(SInt32 inVolume, pid_t inAppProcessID, CFStringRef __nullable inAppBundleID); /*! @param inPanPosition A value between kAppPanLeftRawValue and kAppPanRightRawValue from BGM_Types.h. A negative value has a higher proportion of left channel, and a positive value has a higher proportion of right channel. @param inAppProcessID The ID of app's main process (or the process it uses to play audio, if you've managed to figure that out). If an app has multiple audio processes, you can just set the pan position for each of them. Pass -1 to omit this param. @param inAppBundleID The app's bundle ID. Pass null to omit this param. @throws CAException If the HAL returns an error when this function sends the pan position change to BGMDevice. */ void SetAppPanPosition(SInt32 inPanPosition, pid_t inAppProcessID, CFStringRef __nullable inAppBundleID); private: void SendAppVolumeOrPanToBGMDevice(SInt32 inNewValue, CFStringRef inVolumeTypeKey, pid_t inAppProcessID, CFStringRef __nullable inAppBundleID); static std::vector<CACFString> ResponsibleBundleIDsOf(CACFString inParentBundleID); #pragma mark Audible State public: /*! @return BGMDevice's current "audible state", which can be either silent, silent except for the user's music player or audible, meaning a program other than the music player is playing audio. @throws CAException If the HAL returns an error or invalid data when queried. @see kAudioDeviceCustomPropertyDeviceAudibleState in BGM_Types.h. */ BGMDeviceAudibleState GetAudibleState() const; #pragma mark Music Player public: /*! @return The value of BGMDevice's property for the selected music player's process ID. Zero if the property is unset. (We assume kernel_task will never be the user's music player.) @throws CAException If the HAL returns an error or an invalid PID when queried. @see kAudioDeviceCustomPropertyMusicPlayerProcessID in BGM_Types.h. */ virtual pid_t GetMusicPlayerProcessID() const; /*! Set the value of BGMDevice's property for the selected music player's process ID. Pass zero to unset the property. Setting this property will unset the bundle ID version of the property. @throws CAException If the HAL returns an error. @see kAudioDeviceCustomPropertyMusicPlayerProcessID in BGM_Types.h. */ virtual void SetMusicPlayerProcessID(CFNumberRef inProcessID) { SetPropertyData_CFType(kBGMMusicPlayerProcessIDAddress, inProcessID); } /*! @return The value of BGMDevice's property for the selected music player's bundle ID. The empty string if the property is unset. @throws CAException If the HAL returns an error or an invalid bundle ID when queried. @see kAudioDeviceCustomPropertyMusicPlayerBundleID in BGM_Types.h. */ virtual CFStringRef GetMusicPlayerBundleID() const; /*! Set the value of BGMDevice's property for the selected music player's bundle ID. Pass the empty string to unset the property. Setting this property will unset the process ID version of the property. @throws CAException If the HAL returns an error. @see kAudioDeviceCustomPropertyMusicPlayerBundleID in BGM_Types.h. */ virtual void SetMusicPlayerBundleID(CFStringRef inBundleID) { SetPropertyData_CFString(kBGMMusicPlayerBundleIDAddress, inBundleID); } #pragma mark UI Sounds Instance public: /*! @return The instance of BGMDevice that handles UI sounds. */ BGMAudioDevice GetUISoundsBGMDeviceInstance() { return mUISoundsBGMDevice; } private: /*! The instance of BGMDevice that handles UI sounds. */ BGMAudioDevice mUISoundsBGMDevice; }; #pragma clang assume_nonnull end #endif /* BGMApp__BGMBackgroundMusicDevice */
8,167
C++
.h
164
41.530488
100
0.682976
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,436
BGMStatusBarItem.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMStatusBarItem.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMStatusBarItem.h // BGMApp // // Copyright © 2019, 2020 Kyle Neideck // // The button in the system status bar (the bar with volume, battery, clock, etc.) to show the main // menu for the app. These are called "menu bar extras" in the Human Interface Guidelines. // // Local Includes #import "BGMAudioDeviceManager.h" #import "BGMDebugLoggingMenuItem.h" // System Includes #import <Cocoa/Cocoa.h> // Forward Declarations @class BGMUserDefaults; #pragma clang assume_nonnull begin typedef NS_ENUM(NSInteger, BGMStatusBarIcon) { BGMFermataStatusBarIcon = 0, BGMVolumeStatusBarIcon }; static BGMStatusBarIcon const kBGMStatusBarIconMinValue = BGMFermataStatusBarIcon; static BGMStatusBarIcon const kBGMStatusBarIconMaxValue = BGMVolumeStatusBarIcon; static BGMStatusBarIcon const kBGMStatusBarIconDefaultValue = BGMFermataStatusBarIcon; @interface BGMStatusBarItem : NSObject - (instancetype) initWithMenu:(NSMenu*)bgmMenu audioDevices:(BGMAudioDeviceManager*)devices userDefaults:(BGMUserDefaults*)defaults; // Set this to BGMFermataStatusBarIcon to change the icon to the Background Music logo. // // Set this to BGMFermataStatusBarIcon to change the icon to a volume icon. This icon has the // advantage of indicating the volume level, but we can't make it the default because it looks the // same as the icon for the macOS volume status bar item. @property BGMStatusBarIcon icon; // If the user holds down the option key when they click the status bar icon, this menu item will be // shown in the main menu. - (void) setDebugLoggingMenuItem:(BGMDebugLoggingMenuItem*)menuItem; @end #pragma clang assume_nonnull end
2,396
C++
.h
53
43.132075
100
0.784364
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,437
BGMOutputVolumeMenuItem.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMOutputVolumeMenuItem.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMOutputVolumeMenuItem.h // BGMApp // // Copyright © 2017 Kyle Neideck // // Local Includes #import "BGMAudioDeviceManager.h" // System Includes #import <Cocoa/Cocoa.h> #pragma clang assume_nonnull begin @interface BGMOutputVolumeMenuItem : NSMenuItem // A menu item with a slider for controlling the volume of the output device. Similar to the one in // macOS's Volume menu extra. // // view, slider and deviceLabel are the UI elements from MainMenu.xib. - (instancetype) initWithAudioDevices:(BGMAudioDeviceManager*)devices view:(NSView*)view slider:(NSSlider*)slider deviceLabel:(NSTextField*)label; - (void) outputDeviceDidChange; @end #pragma clang assume_nonnull end
1,486
C++
.h
37
36.432432
99
0.734353
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,438
BGMAppDelegate.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMAppDelegate.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMAppDelegate.h // BGMApp // // Copyright © 2016, 2017, 2020 Kyle Neideck // Copyright © 2021 Marcus Wu // // Sets up and tears down the app. // // Local Includes #import "BGMAudioDeviceManager.h" #import "BGMAppVolumesController.h" // System Includes #import <Cocoa/Cocoa.h> // Tags for UI elements in MainMenu.xib static NSInteger const kVolumesHeadingMenuItemTag = 3; static NSInteger const kSeparatorBelowVolumesMenuItemTag = 4; @interface BGMAppDelegate : NSObject <NSApplicationDelegate, NSMenuDelegate> @property (weak) IBOutlet NSMenu* bgmMenu; @property (weak) IBOutlet NSView* outputVolumeView; @property (weak) IBOutlet NSTextField* outputVolumeLabel; @property (weak) IBOutlet NSSlider* outputVolumeSlider; @property (weak) IBOutlet NSView* systemSoundsView; @property (weak) IBOutlet NSSlider* systemSoundsSlider; @property (weak) IBOutlet NSView* appVolumeView; @property (weak) IBOutlet NSPanel* aboutPanel; @property (unsafe_unretained) IBOutlet NSTextView* aboutPanelLicenseView; @property (weak) IBOutlet NSMenuItem* autoPauseMenuItemUnwrapped; @property (weak) IBOutlet NSMenuItem* debugLoggingMenuItemUnwrapped; @property (readonly) BGMAudioDeviceManager* audioDevices; @property BGMAppVolumesController* appVolumes; @end
1,972
C++
.h
46
41.5
76
0.801467
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,439
BGMOutputDeviceMenuSection.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMOutputDeviceMenuSection.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMOutputDeviceMenuSection.h // BGMApp // // Copyright © 2016, 2018 Kyle Neideck // // Local Includes #import "BGMAudioDeviceManager.h" #import "BGMPreferredOutputDevices.h" // System Includes #import <AppKit/AppKit.h> #pragma clang assume_nonnull begin @interface BGMOutputDeviceMenuSection : NSObject - (instancetype) initWithBGMMenu:(NSMenu*)inBGMMenu audioDevices:(BGMAudioDeviceManager*)inAudioDevices preferredDevices:(BGMPreferredOutputDevices*)inPreferredDevices; // To be called when BGMApp has been set to use a different output device. For example, when a new // device is connected and BGMPreferredOutputDevices decides BGMApp should switch to it. - (void) outputDeviceDidChange; @end #pragma clang assume_nonnull end
1,488
C++
.h
35
40.171429
98
0.777393
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,440
BGMPlayThrough.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMPlayThrough.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMPlayThrough.h // BGMApp // // Copyright © 2016, 2017, 2020 Kyle Neideck // // Reads audio from an input device and immediately writes it to an output device. We currently use this class with the input // device always set to BGMDevice and the output device set to the one selected in the preferences menu. // // Apple's CAPlayThrough sample code (https://developer.apple.com/library/mac/samplecode/CAPlayThrough/Introduction/Intro.html) // has a similar class, but I couldn't get it fast enough to use here. Soundflower also has a similar class // (https://github.com/mattingalls/Soundflower/blob/master/SoundflowerBed/AudioThruEngine.h) that seems to be based on Apple // sample code from 2004. This class's main addition is pausing playthrough when idle to save CPU. // // Playing audio with this class uses more CPU, mostly in the coreaudiod process, than playing audio normally because we need // an input IOProc as well as an output one, and BGMDriver is running in addition to the output device's driver. For me, it // usually adds around 1-2% (as a percentage of total usage -- it doesn't seem to be relative to the CPU used when playing // audio normally). // // This class will hopefully not be needed after CoreAudio's aggregate devices get support for controls, which is planned for // a future release. // #ifndef BGMApp__BGMPlayThrough #define BGMApp__BGMPlayThrough // Local Includes #include "BGMAudioDevice.h" #include "BGMPlayThroughRTLogger.h" // PublicUtility Includes #include "CAMutex.h" #include "CARingBuffer.h" #include "BGMThreadSafetyAnalysis.h" // STL Includes #include <atomic> #include <algorithm> #include <memory> // System Includes #include <mach/semaphore.h> #pragma clang assume_nonnull begin class BGMPlayThrough { public: // Error codes static const OSStatus kDeviceNotStarting = 100; public: BGMPlayThrough(BGMAudioDevice inInputDevice, BGMAudioDevice inOutputDevice); ~BGMPlayThrough(); // Disallow copying BGMPlayThrough(const BGMPlayThrough&) = delete; BGMPlayThrough& operator=(const BGMPlayThrough&) = delete; #ifdef __OBJC__ // Only intended as a convenience (hack) for Objective-C instance vars. Call // SetDevices to initialise the instance before using it. BGMPlayThrough() { } #endif private: /*! @throws CAException */ void Init(BGMAudioDevice inInputDevice, BGMAudioDevice inOutputDevice) REQUIRES(mStateMutex); public: /*! @throws CAException */ void Activate(); /*! @throws CAException */ void Deactivate(); private: void AllocateBuffer() REQUIRES(mStateMutex); void DeallocateBuffer(); /*! @throws CAException */ void CreateIOProcIDs(); /*! @throws CAException */ void DestroyIOProcIDs(); /*! @return True if both IOProcs are stopped. @nonthreadsafe */ bool CheckIOProcsAreStopped() const noexcept REQUIRES(mStateMutex); public: /*! Pass null for either param to only change one of the devices. @throws CAException */ void SetDevices(const BGMAudioDevice* __nullable inInputDevice, const BGMAudioDevice* __nullable inOutputDevice); /*! @throws CAException */ void Start(); // Blocks until the output device has started our IOProc. Returns one of the error constants // from AudioHardwareBase.h (e.g. kAudioHardwareNoError). OSStatus WaitForOutputDeviceToStart() noexcept; private: /*! Real-time safe. */ void ReleaseThreadsWaitingForOutputToStart(); public: OSStatus Stop(); void StopIfIdle(); private: static OSStatus BGMDeviceListenerProc(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress* inAddresses, void* __nullable inClientData); static void HandleBGMDeviceIsRunning(BGMPlayThrough* refCon); static void HandleBGMDeviceIsRunningSomewhereOtherThanBGMApp(BGMPlayThrough* refCon); static bool IsRunningSomewhereOtherThanBGMApp(const BGMAudioDevice& inBGMDevice); static OSStatus InputDeviceIOProc(AudioObjectID inDevice, const AudioTimeStamp* inNow, const AudioBufferList* inInputData, const AudioTimeStamp* inInputTime, AudioBufferList* outOutputData, const AudioTimeStamp* inOutputTime, void* __nullable inClientData); static OSStatus OutputDeviceIOProc(AudioObjectID inDevice, const AudioTimeStamp* inNow, const AudioBufferList* inInputData, const AudioTimeStamp* inInputTime, AudioBufferList* outOutputData, const AudioTimeStamp* inOutputTime, void* __nullable inClientData); /*! Fills the given ABL with zeroes to make it silent. */ static inline void FillWithSilence(AudioBufferList* ioBuffer); // The state of an IOProc. Used by the IOProc to tell other threads when it's finished starting. Used by other // threads to tell the IOProc to stop itself. (Probably used for other things as well.) enum class IOState { Stopped, Starting, Running, Stopping }; // The IOProcs call this to update their IOState member. Also stops the IOProc if its state has been set to Stopping. // Returns true if it changes the state. static bool UpdateIOProcState(const char* inCallerName, BGMPlayThroughRTLogger& inRTLogger, std::atomic<IOState>& inState, AudioDeviceIOProcID __nullable inIOProcID, BGMAudioDevice& inDevice, IOState& outNewState); private: std::unique_ptr<CARingBuffer> mBuffer PT_GUARDED_BY(mBufferInputMutex) PT_GUARDED_BY(mBufferOutputMutex) { nullptr }; AudioDeviceIOProcID __nullable mInputDeviceIOProcID { nullptr }; AudioDeviceIOProcID __nullable mOutputDeviceIOProcID { nullptr }; BGMAudioDevice mInputDevice { kAudioObjectUnknown }; BGMAudioDevice mOutputDevice { kAudioObjectUnknown }; // mStateMutex is the general purpose mutex. mBufferInputMutex and mBufferOutputMutex are // just used to make sure mBuffer, the ring buffer, is allocated when the IOProcs access it. See // the comments in the IOProcs for details. // // If a thread might lock more than one of these mutexes, it *must* take them in this order: // 1. mStateMutex // 2. mBufferInputMutex // 3. mBufferOutputMutex // // The ACQUIRED_BEFORE annotations don't do anything yet. From clang's docs: "ACQUIRED_BEFORE(…) // and ACQUIRED_AFTER(…) are currently unimplemented. To be fixed in a future update." After // they've fixed that, the compiler will enforce the ordering statically. // // TODO: We can't use std::shared_lock because we're still on C++11, but we could use std::lock // to help ensure the locks are always taken in the right order. // TODO: It would be better to have a separate class for the buffer and its mutexes. CAMutex mStateMutex ACQUIRED_BEFORE(mBufferInputMutex) ACQUIRED_BEFORE(mBufferOutputMutex) { "Playthrough state" }; CAMutex mBufferInputMutex ACQUIRED_BEFORE(mBufferOutputMutex) { "Playthrough ring buffer input" }; CAMutex mBufferOutputMutex { "Playthrough ring buffer output" }; // Signalled when the output IOProc runs. We use it to tell BGMDriver when the output device is ready to receive audio data. semaphore_t mOutputDeviceIOProcSemaphore { SEMAPHORE_NULL }; bool mActive = false; bool mPlayingThrough = false; UInt64 mLastNotifiedIOStoppedOnBGMDevice { 0 }; std::atomic<IOState> mInputDeviceIOProcState { IOState::Stopped }; std::atomic<IOState> mOutputDeviceIOProcState { IOState::Stopped }; // For debug logging. UInt64 mToldOutputDeviceToStartAt { 0 }; // IOProc vars. (Should only be used inside IOProcs.) // The earliest/latest sample times seen by the IOProcs since starting playthrough. -1 for unset. Float64 mFirstInputSampleTime = -1; Float64 mLastInputSampleTime = -1; Float64 mLastOutputSampleTime = -1; // Subtract this from the output time to get the input time. Float64 mInToOutSampleOffset { 0.0 }; BGMPlayThroughRTLogger mRTLogger; }; #pragma clang assume_nonnull end #endif /* BGMApp__BGMPlayThrough */
10,525
C++
.h
193
44.373057
128
0.633898
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,441
BGMUserDefaults.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMUserDefaults.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMUserDefaults.h // BGMApp // // Copyright © 2016-2019 Kyle Neideck // // A simple wrapper around our use of NSUserDefaults. Used to store the preferences/state that only // apply to BGMApp. The others are stored by BGMDriver. // // Private data will be stored in the user's keychain instead of user defaults. // // Local Includes #import "BGMStatusBarItem.h" // System Includes #import <Cocoa/Cocoa.h> #pragma clang assume_nonnull begin @interface BGMUserDefaults : NSObject // If inDefaults is nil, settings are not loaded from or saved to disk, which is useful for testing. - (instancetype) initWithDefaults:(NSUserDefaults* __nullable)inDefaults; // The musicPlayerID (see BGMMusicPlayer.h), as a string, of the music player selected by the user. // Must be either null or a string that can be parsed by NSUUID. @property NSString* __nullable selectedMusicPlayerID; @property BOOL autoPauseMusicEnabled; // The UIDs of the output devices most recently selected by the user. The most-recently selected // device is at index 0. See BGMPreferredOutputDevices. @property NSArray<NSString*>* preferredDeviceUIDs; // The (type of) icon to show in the button in the status bar. (The button the user clicks to open // BGMApp's main menu.) @property BGMStatusBarIcon statusBarIcon; // The auth code we're required to send when connecting to GPMDP. Stored in the keychain. Reading // this property is thread-safe, but writing it isn't. // // Returns nil if no code is found or if reading fails. If writing fails, an error is logged, but no // exception is thrown. @property NSString* __nullable googlePlayMusicDesktopPlayerPermanentAuthCode; @end #pragma clang assume_nonnull end
2,404
C++
.h
51
45.843137
100
0.780582
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,442
BGMAutoPauseMenuItem.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMAutoPauseMenuItem.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMAutoPauseMenuItem.h // BGMApp // // Copyright © 2016 Kyle Neideck // // Local Includes #import "BGMAutoPauseMusic.h" #import "BGMMusicPlayers.h" #import "BGMUserDefaults.h" // System Includes #import <Cocoa/Cocoa.h> #pragma clang assume_nonnull begin @interface BGMAutoPauseMenuItem : NSObject - (instancetype) initWithMenuItem:(NSMenuItem*)item autoPauseMusic:(BGMAutoPauseMusic*)autoPause musicPlayers:(BGMMusicPlayers*)players userDefaults:(BGMUserDefaults*)defaults; // Handle events passed along by the delegate (NSMenuDelegate) of the menu containing this menu item. - (void) parentMenuNeedsUpdate; - (void) parentMenuItemWillHighlight:(NSMenuItem* __nullable)item; @end #pragma clang assume_nonnull end
1,496
C++
.h
37
37.486486
101
0.758978
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,443
BGMAppVolumes.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMAppVolumes.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMAppVolumes.h // BGMApp // // Copyright © 2016, 2017 Kyle Neideck // Copyright © 2021 Marcus Wu // // Local Includes #import "BGMAppVolumesController.h" // System Includes #import <Cocoa/Cocoa.h> #pragma clang assume_nonnull begin @interface BGMAppVolumes : NSObject - (id) initWithController:(BGMAppVolumesController*)inController bgmMenu:(NSMenu*)inMenu appVolumeView:(NSView*)inView; // Pass -1 for initialVolume or kAppPanNoValue for initialPan to leave the volume/pan at its default level. - (void) insertMenuItemForApp:(NSRunningApplication*)app initialVolume:(int)volume initialPan:(int)pan; - (void) removeMenuItemForApp:(NSRunningApplication*)app; - (void) removeAllAppVolumeMenuItems; - (BGMAppVolumeAndPan) getVolumeAndPanForApp:(NSRunningApplication*)app; - (void) setVolumeAndPan:(BGMAppVolumeAndPan)volumeAndPan forApp:(NSRunningApplication*)app; @end // Protocol for the UI custom classes @protocol BGMAppVolumeMenuItemSubview <NSObject> - (void) setUpWithApp:(NSRunningApplication*)app context:(BGMAppVolumes*)ctx controller:(BGMAppVolumesController*)ctrl menuItem:(NSMenuItem*)item; @end // Custom classes for the UI elements in the app volume menu items @interface BGMAVM_AppIcon : NSImageView <BGMAppVolumeMenuItemSubview> @end @interface BGMAVM_AppNameLabel : NSTextField <BGMAppVolumeMenuItemSubview> @end @interface BGMAVM_ShowMoreControlsButton : NSButton <BGMAppVolumeMenuItemSubview> @end @interface BGMAVM_VolumeSlider : NSSlider <BGMAppVolumeMenuItemSubview> - (void) setRelativeVolume:(int)relativeVolume; @end @interface BGMAVM_PanSlider : NSSlider <BGMAppVolumeMenuItemSubview> - (void) setPanPosition:(int)panPosition; @end #pragma clang assume_nonnull end
2,535
C++
.h
60
39.016667
107
0.777414
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,444
BGMPreferredOutputDevices.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMPreferredOutputDevices.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMPreferredOutputDevices.h // BGMApp // // Copyright © 2018 Kyle Neideck // // Tries to change BGMApp's output device when the user plugs in or unplugs an audio device, in the // same way macOS would change its default device if Background Music wasn't running. // // For example, if you plug in some USB headphones, make them your default device and then unplug // them, macOS will change its default device to the previous default device. Then, if you plug // them back in, macOS will make them the default device again. // // This class isn't always able to figure out what macOS would do, in which case it leaves BGMApp's // output device as it is. // // Local Includes #import "BGMAudioDeviceManager.h" #import "BGMUserDefaults.h" // System Includes #import <CoreAudio/AudioHardwareBase.h> #import <Foundation/Foundation.h> #pragma clang assume_nonnull begin @interface BGMPreferredOutputDevices : NSObject // Starts responding to device connections/disconnections immediately. Stops if/when the instance is // deallocated. - (instancetype) initWithDevices:(BGMAudioDeviceManager*)devices userDefaults:(BGMUserDefaults*)userDefaults; // Returns the most-preferred device that's currently connected. If no preferred devices are // connected, returns the current output device. If the current output device has been disconnected, // returns an arbitrary device. // // If none of the connected devices can be used as the output device, or if it can't find a device // to use because the HAL returned errors when queried, returns kAudioObjectUnknown. - (AudioObjectID) findPreferredDevice; - (void) userChangedOutputDeviceTo:(AudioObjectID)device; @end #pragma clang assume_nonnull end
2,438
C++
.h
52
45.269231
100
0.780539
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,445
BGMAutoPauseMusic.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMAutoPauseMusic.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMAutoPauseMusic.h // BGMApp // // Copyright © 2016 Kyle Neideck // // When enabled, BGMAutoPauseMusic listens for notifications from BGMDevice to tell when music is playing and // pauses the music player if other audio starts. // // Local Includes #import "BGMAudioDeviceManager.h" #import "BGMMusicPlayers.h" // System Includes #import <Foundation/Foundation.h> #pragma clang assume_nonnull begin @interface BGMAutoPauseMusic : NSObject - (id) initWithAudioDevices:(BGMAudioDeviceManager*)inAudioDevices musicPlayers:(BGMMusicPlayers*)inMusicPlayers; - (void) enable; - (void) disable; @end #pragma clang assume_nonnull end
1,351
C++
.h
35
37.285714
113
0.783908
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,446
BGMDeviceControlsList.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMDeviceControlsList.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMDeviceControlsList.h // BGMApp // // Copyright © 2017 Kyle Neideck // #ifndef BGMApp__BGMDeviceControlsList #define BGMApp__BGMDeviceControlsList // Local Includes #include "BGMAudioDevice.h" // PublicUtility Includes #include "CAHALAudioDevice.h" #include "CAHALAudioSystemObject.h" #include "CAMutex.h" // System Includes #include <dispatch/dispatch.h> #include <AudioToolbox/AudioServices.h> #pragma clang assume_nonnull begin class BGMDeviceControlsList { #pragma mark Construction/Destruction public: BGMDeviceControlsList(AudioObjectID inBGMDevice, CAHALAudioSystemObject inAudioSystem = CAHALAudioSystemObject()); ~BGMDeviceControlsList(); // Disallow copying BGMDeviceControlsList(const BGMDeviceControlsList&) = delete; BGMDeviceControlsList& operator=(const BGMDeviceControlsList&) = delete; #pragma mark Accessors /*! @param inBGMDeviceID The ID of BGMDevice. */ void SetBGMDevice(AudioObjectID inBGMDeviceID); #pragma mark Update Controls List /*! Enable the BGMDevice controls (volume and mute currently) that can be matched to controls of the given device, and disable the ones that can't. @param inDeviceID The ID of the device. @return True if BGMDevice's list of controls was updated. @throws CAException if an error is received from either device. */ bool MatchControlsListOf(AudioObjectID inDeviceID); /*! After updating BGMDevice's controls list, we need to change the default device so programs (including OS X's audio UI) will update themselves. We could just change to the real output device and change back, but that could have side effects the user wouldn't expect. For example, an app the user has muted might be unmuted for a short period. Instead we tell BGMDriver to enable the Null Device -- a device that does nothing -- so we can use it to toggle the default device. The Null Device is normally disabled so it can be hidden from the user. OS X won't let us make a hidden device temporarily visible or set a hidden device as the default, so we have to completely remove the Null Device from the system while we're not using it. @throws CAException if it fails to enable the Null Device. */ void PropagateControlListChange(); #pragma mark Implementation private: /*! Lazily initialises the fields used to toggle the default device. */ void InitDeviceToggling(); /*! Changes the OS X default audio device to the Null Device and then back to BGMDevice. */ void ToggleDefaultDevice(); /*! Enable or disable the Null Device. See PropagateControlListChange and BGM_NullDevice in BGMDriver. @throws CAException if we can't get the BGMDriver plug-in audio object from the HAL or the HAL returns an error when setting kAudioPlugInCustomPropertyNullDeviceActive. */ void SetNullDeviceEnabled(bool inEnabled); dispatch_block_t __nullable CreateDeviceToggleBlock(); dispatch_block_t __nullable CreateDeviceToggleBackBlock(); dispatch_block_t __nullable CreateDisableNullDeviceBlock(); void DestroyBlock(dispatch_block_t __nullable & block); private: CAMutex mMutex { "Device Controls List" }; bool mDeviceTogglingInitialised = false; // OS X 10.9 doesn't have the functions we use for PropagateControlListChange. bool mCanToggleDeviceOnSystem; BGMAudioDevice mBGMDevice; CAHALAudioSystemObject mAudioSystem; // Not guarded by the mutex. enum ToggleState { NotToggling, SettingNullDeviceAsDefault, SettingBGMDeviceAsDefault, DisablingNullDevice }; BGMDeviceControlsList::ToggleState mDeviceToggleState = ToggleState::NotToggling; dispatch_block_t __nullable mDeviceToggleBlock = nullptr; dispatch_block_t __nullable mDeviceToggleBackBlock = nullptr; dispatch_block_t __nullable mDisableNullDeviceBlock = nullptr; // These will only ever be null after construction on 10.9, since toggling will be disabled. dispatch_queue_t __nullable mListenerQueue = nullptr; AudioObjectPropertyListenerBlock __nullable mListenerBlock = nullptr; }; #pragma clang assume_nonnull end #endif /* BGMApp__BGMDeviceControlsList */
5,340
C++
.h
106
44.433962
100
0.711949
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,447
BGMSystemSoundsVolume.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMSystemSoundsVolume.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMSystemSoundsVolume.h // BGMApp // // Copyright © 2017 Kyle Neideck // // The menu item with the volume slider that controls system-related sounds. The slider is used to // set the volume of the instance of BGMDevice that system sounds are played on, i.e. the audio // device returned by BGMBackgroundMusicDevice::GetUISoundsBGMDeviceInstance. // // System sounds are any sounds played using the audio device macOS is set to use as the device // "for system related sound from the alert sound to digital call progress". See // kAudioHardwarePropertyDefaultSystemOutputDevice in AudioHardware.h. They can be played by any // app, though most apps use systemsoundserverd to play their system sounds, which means BGMDriver // can't tell which app is actually playing the sounds. // // Local Includes #import "BGMAudioDevice.h" // System Includes #import <Cocoa/Cocoa.h> #pragma clang assume_nonnull begin @interface BGMSystemSoundsVolume : NSObject // The volume level of uiSoundsDevice will be used to set the slider's initial position and will be // updated when the user moves the slider. view and slider are the UI elements from MainMenu.xib. - (instancetype) initWithUISoundsDevice:(BGMAudioDevice)uiSoundsDevice view:(NSView*)view slider:(NSSlider*)slider; // The menu item with the volume slider for system sounds. @property (readonly) NSMenuItem* menuItem; @end #pragma clang assume_nonnull end
2,200
C++
.h
45
46.133333
99
0.762593
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,448
BGMDeviceControlSync.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMDeviceControlSync.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMDeviceControlSync.h // BGMApp // // Copyright © 2016, 2017 Kyle Neideck // // Synchronises BGMDevice's controls (just volume and mute currently) with the output device's // controls. This allows the user to control the output device normally while BGMDevice is set as // the default device. // // BGMDeviceControlSync disables any BGMDevice controls that the output device doesn't also have. // When the value of one of BGMDevice's controls is changed, BGMDeviceControlSync copies the new // value to the output device. // // Thread safe. // #ifndef BGMApp__BGMDeviceControlSync #define BGMApp__BGMDeviceControlSync // Local Includes #include "BGMAudioDevice.h" #include "BGMDeviceControlsList.h" // PublicUtility Includes #include "CAHALAudioSystemObject.h" #include "CAMutex.h" // System Includes #include <AudioToolbox/AudioServices.h> #pragma clang assume_nonnull begin class BGMDeviceControlSync { #pragma mark Construction/Destruction public: BGMDeviceControlSync(AudioObjectID inBGMDevice, AudioObjectID inOutputDevice, CAHALAudioSystemObject inAudioSystem = CAHALAudioSystemObject()); ~BGMDeviceControlSync(); // Disallow copying BGMDeviceControlSync(const BGMDeviceControlSync&) = delete; BGMDeviceControlSync& operator=(const BGMDeviceControlSync&) = delete; #ifdef __OBJC__ // Only intended as a convenience for Objective-C instance vars BGMDeviceControlSync() : BGMDeviceControlSync(kAudioObjectUnknown, kAudioObjectUnknown) { }; #endif /*! Begin synchronising BGMDevice's controls with the output device's. @throws BGM_DeviceNotSetException if BGMDevice isn't set. @throws CAException if the HAL or one of the devices returns an error when this function registers for device property notifications or when it copies the current values of the output device's controls to BGMDevice. This BGMDeviceControlSync will remain inactive if this function throws. */ void Activate(); /*! Stop synchronising BGMDevice's controls with the output device's. */ void Deactivate(); #pragma mark Accessors /*! Set the IDs of BGMDevice and the output device to synchronise with. @throws BGM_DeviceNotSetException if BGMDevice isn't set. @throws CAException if the HAL or one of the new devices returns an error while restarting synchronisation. This BGMDeviceControlSync will be deactivated if this function throws, but its devices will still be set. */ void SetDevices(AudioObjectID inBGMDevice, AudioObjectID inOutputDevice); #pragma mark Listener Procs private: /*! Receives HAL notifications about the BGMDevice properties this class listens to. */ static OSStatus BGMDeviceListenerProc(AudioObjectID inObjectID, UInt32 inNumberAddresses, const AudioObjectPropertyAddress* inAddresses, void* __nullable inClientData); private: CAMutex mMutex { "Device Control Sync" }; bool mActive = false; CAHALAudioSystemObject mAudioSystem; BGMAudioDevice mBGMDevice { (AudioObjectID)kAudioObjectUnknown }; BGMAudioDevice mOutputDevice { (AudioObjectID)kAudioObjectUnknown }; BGMDeviceControlsList mBGMDeviceControlsList; }; #pragma clang assume_nonnull end #endif /* BGMApp__BGMDeviceControlSync */
4,648
C++
.h
95
40.178947
98
0.672578
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,449
BGMAppVolumesController.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMAppVolumesController.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMAppVolumesController.h // BGMApp // // Copyright © 2017 Kyle Neideck // Copyright © 2021 Marcus Wu // // Local Includes #import "BGMAudioDeviceManager.h" // System Includes #import <Cocoa/Cocoa.h> #pragma clang assume_nonnull begin typedef struct BGMAppVolumeAndPan { int volume; int pan; } BGMAppVolumeAndPan; @interface BGMAppVolumesController : NSObject - (id) initWithMenu:(NSMenu*)menu appVolumeView:(NSView*)view audioDevices:(BGMAudioDeviceManager*)audioDevices; // See BGMBackgroundMusicDevice::SetAppVolume. - (void) setVolume:(SInt32)volume forAppWithProcessID:(pid_t)processID bundleID:(NSString* __nullable)bundleID; // See BGMBackgroundMusicDevice::SetPanVolume. - (void) setPanPosition:(SInt32)pan forAppWithProcessID:(pid_t)processID bundleID:(NSString* __nullable)bundleID; - (BGMAppVolumeAndPan) getVolumeAndPanForApp:(NSRunningApplication *)app; - (void) setVolumeAndPan:(BGMAppVolumeAndPan)volumeAndPan forApp:(NSRunningApplication*)app; @end #pragma clang assume_nonnull end
1,777
C++
.h
46
36.173913
92
0.774927
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,450
BGMTermination.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMTermination.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMTermination.h // BGMApp // // Copyright © 2017 Kyle Neideck // // Cleans up if BGMApp crashes because of an uncaught C++ or Objective-C exception, or is sent // SIGINT/SIGTERM/SIGQUIT. Currently, it just changes the default output device from BGMDevice to // the real output device and records debug info for some types of crashes. // // BGMXPCHelper also changes the default device if BGMApp disconnects and leaves BGMDevice as the // default. This handles cases like segfaults where it wouldn't be safe to clean up from the // crashing process. // #ifndef BGMApp__BGMTermination #define BGMApp__BGMTermination // Local Includes #import "BGMAudioDeviceManager.h" // PublicUtility Includes #import "CAPThread.h" // STL Includes #import <exception> #pragma clang assume_nonnull begin class BGMTermination { public: /*! Starts a thread that will clean up before exiting if BGMApp receives SIGINT, SIGTERM or SIGQUIT. Sets a similar clean up function to run if BGMApp terminates due to an uncaught exception. */ static void SetUpTerminationCleanUp(BGMAudioDeviceManager* inAudioDevices); /*! Some commented out ways to have BGMApp crash for testing. Does nothing if unmodified. */ static void TestCrash() __attribute__((noinline)); private: static void StartExitSignalsThread(); static void CleanUpAudioDevices(); /*! Adds some info about the uncaught exception that caused a crash to the crash report. */ static void AddCurrentExceptionToCrashReport(); /*! The entry point for sExitSignalsThread. */ static void* __nullable ExitSignalsProc(void* __nullable ignored); /*! The thread that handles SIGQUIT, SIGTERM and SIGINT. Never destroyed. */ static CAPThread* const sExitSignalsThread; static sigset_t sExitSignals; /*! The function that handles std::terminate by default. */ static std::terminate_handler sOriginalTerminateHandler; /*! The audio device manager. (Must be static to be accessed in our std::terminate_handler.) */ static BGMAudioDeviceManager* __nullable sAudioDevices; }; #pragma clang assume_nonnull end #endif /* BGMApp__BGMTermination */
3,029
C++
.h
65
43.923077
100
0.72613
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,451
BGMDebugLoggingMenuItem.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMDebugLoggingMenuItem.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMDebugLoggingMenuItem.h // BGMApp // // Copyright © 2020 Kyle Neideck // // A menu item in the main menu that enables/disables debug logging. Only visible if you hold the // option down when you click the status bar icon to reveal the main menu. // // TODO: It would be better to have this menu item in the Preferences menu (maybe in an Advanced // section) and always visible, but first we'd need to add something that tells the user how // to view the log messages. Or better yet, something that automatically opens them. // // System Includes #import <Cocoa/Cocoa.h> #pragma clang assume_nonnull begin @interface BGMDebugLoggingMenuItem : NSObject - (instancetype) initWithMenuItem:(NSMenuItem*)menuItem; // True if the main menu is showing hidden items/options because the user held the option key when // they clicked the icon. This class makes the debug logging menu item visible if this property has // been set true or if debug logging is enabled. @property (nonatomic) BOOL menuShowingExtraOptions; @end #pragma clang assume_nonnull end
1,786
C++
.h
38
45.736842
99
0.771577
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,453
SystemPreferences.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/SystemPreferences.h
/* * SystemPreferences.h */ #import <AppKit/AppKit.h> #import <ScriptingBridge/ScriptingBridge.h> @class SystemPreferencesItem, SystemPreferencesApplication, SystemPreferencesColor, SystemPreferencesDocument, SystemPreferencesWindow, SystemPreferencesAttributeRun, SystemPreferencesCharacter, SystemPreferencesParagraph, SystemPreferencesText, SystemPreferencesAttachment, SystemPreferencesWord, SystemPreferencesAnchor, SystemPreferencesPane, SystemPreferencesPrintSettings; enum SystemPreferencesSavo { SystemPreferencesSavoAsk = 'ask ' /* Ask the user whether or not to save the file. */, SystemPreferencesSavoNo = 'no ' /* Do not save the file. */, SystemPreferencesSavoYes = 'yes ' /* Save the file. */ }; typedef enum SystemPreferencesSavo SystemPreferencesSavo; enum SystemPreferencesEnum { SystemPreferencesEnumStandard = 'lwst' /* Standard PostScript error handling */, SystemPreferencesEnumDetailed = 'lwdt' /* print a detailed report of PostScript errors */ }; typedef enum SystemPreferencesEnum SystemPreferencesEnum; /* * Standard Suite */ // A scriptable object. @interface SystemPreferencesItem : SBObject @property (copy) NSDictionary *properties; // All of the object's properties. - (void)closeSaving:(SystemPreferencesSavo) saving savingIn:(NSURL *)savingIn; // Close an object. - (void)delete; // Delete an object. - (void)duplicateTo:(SBObject *)to withProperties:(NSDictionary *)withProperties; // Copy object(s) and put the copies at a new location. - (BOOL)exists; // Verify if an object exists. - (void)moveTo:(SBObject *)to; // Move object(s) to a new location. - (void)saveAs:(NSString *)as in:(NSURL *)in_; // Save an object. @end // An application's top level scripting object. @interface SystemPreferencesApplication : SBApplication - (SBElementArray *)documents; - (SBElementArray *)windows; @property (readonly) BOOL frontmost; // Is this the frontmost (active) application? @property (copy, readonly) NSString *name; // The name of the application. @property (copy, readonly) NSString *version; // The version of the application. - (SystemPreferencesDocument *)open:(NSURL *)x; // Open an object. - (void)print:(NSURL *)x printDialog:(BOOL) printDialog withProperties:(SystemPreferencesPrintSettings *)withProperties; // Print an object. - (void)quitSaving:(SystemPreferencesSavo)saving; // Quit an application. @end // A color. @interface SystemPreferencesColor : SystemPreferencesItem @end // A document. @interface SystemPreferencesDocument : SystemPreferencesItem @property (readonly) BOOL modified; // Has the document been modified since the last save? @property (copy) NSString *name; // The document's name. @property (copy) NSString *path; // The document's path. @end // A window. @interface SystemPreferencesWindow : SystemPreferencesItem @property NSRect bounds; // The bounding rectangle of the window. @property (readonly) BOOL closeable; // Whether the window has a close box. @property (copy, readonly) SystemPreferencesDocument *document; // The document whose contents are being displayed in the window. @property (readonly) BOOL floating; // Whether the window floats. - (NSInteger)id; // The unique identifier of the window. @property NSInteger index; // The index of the window, ordered front to back. @property (readonly) BOOL miniaturizable; // Whether the window can be miniaturized. @property BOOL miniaturized; // Whether the window is currently miniaturized. @property (readonly) BOOL modal; // Whether the window is the application's current modal window. @property (copy) NSString *name; // The full title of the window. @property (readonly) BOOL resizable; // Whether the window can be resized. @property (readonly) BOOL titled; // Whether the window has a title bar. @property BOOL visible; // Whether the window is currently visible. @property (readonly) BOOL zoomable; // Whether the window can be zoomed. @property BOOL zoomed; // Whether the window is currently zoomed. @end /* * Text Suite */ // This subdivides the text into chunks that all have the same attributes. @interface SystemPreferencesAttributeRun : SystemPreferencesItem - (SBElementArray *)attachments; - (SBElementArray *)attributeRuns; - (SBElementArray *)characters; - (SBElementArray *)paragraphs; - (SBElementArray *)words; @property (copy) NSColor *color; // The color of the first character. @property (copy) NSString *font; // The name of the font of the first character. @property NSInteger size; // The size in points of the first character. @end // This subdivides the text into characters. @interface SystemPreferencesCharacter : SystemPreferencesItem - (SBElementArray *)attachments; - (SBElementArray *)attributeRuns; - (SBElementArray *)characters; - (SBElementArray *)paragraphs; - (SBElementArray *)words; @property (copy) NSColor *color; // The color of the first character. @property (copy) NSString *font; // The name of the font of the first character. @property NSInteger size; // The size in points of the first character. @end // This subdivides the text into paragraphs. @interface SystemPreferencesParagraph : SystemPreferencesItem - (SBElementArray *)attachments; - (SBElementArray *)attributeRuns; - (SBElementArray *)characters; - (SBElementArray *)paragraphs; - (SBElementArray *)words; @property (copy) NSColor *color; // The color of the first character. @property (copy) NSString *font; // The name of the font of the first character. @property NSInteger size; // The size in points of the first character. @end // Rich (styled) text @interface SystemPreferencesText : SystemPreferencesItem - (SBElementArray *)attachments; - (SBElementArray *)attributeRuns; - (SBElementArray *)characters; - (SBElementArray *)paragraphs; - (SBElementArray *)words; @property (copy) NSColor *color; // The color of the first character. @property (copy) NSString *font; // The name of the font of the first character. @property NSInteger size; // The size in points of the first character. @end // Represents an inline text attachment. This class is used mainly for make commands. @interface SystemPreferencesAttachment : SystemPreferencesText @property (copy) NSString *fileName; // The path to the file for the attachment @end // This subdivides the text into words. @interface SystemPreferencesWord : SystemPreferencesItem - (SBElementArray *)attachments; - (SBElementArray *)attributeRuns; - (SBElementArray *)characters; - (SBElementArray *)paragraphs; - (SBElementArray *)words; @property (copy) NSColor *color; // The color of the first character. @property (copy) NSString *font; // The name of the font of the first character. @property NSInteger size; // The size in points of the first character. @end /* * System Preferences */ // an anchor within a preference pane @interface SystemPreferencesAnchor : SystemPreferencesItem @property (copy, readonly) NSString *name; // name of the anchor within a preference pane - (SystemPreferencesAnchor *)reveal; // Reveals an anchor within a preference pane or preference pane itself @end // System Preferences top level scripting object @interface SystemPreferencesApplication (SystemPreferences) - (SBElementArray *)panes; @property (copy) SystemPreferencesPane *currentPane; // the currently selected pane @property (copy, readonly) SystemPreferencesWindow *preferencesWindow; // the main preferences window @property BOOL showAll; // Is SystemPrefs in show all view. (Setting to false will do nothing) @end // a preference pane @interface SystemPreferencesPane : SystemPreferencesItem - (SBElementArray *)anchors; - (NSString *)id; // locale independent name of the preference pane; can refer to a pane using the expression: pane id "<name>" @property (copy, readonly) NSString *localizedName; // localized name of the preference pane @property (copy, readonly) NSString *name; // name of the preference pane as it appears in the title bar; can refer to a pane using the expression: pane "<name>" - (NSInteger)timedLoad; // This command does xxxx. @end /* * Type Definitions */ @interface SystemPreferencesPrintSettings : SBObject @property NSInteger copies; // the number of copies of a document to be printed @property BOOL collating; // Should printed copies be collated? @property NSInteger startingPage; // the first page of the document to be printed @property NSInteger endingPage; // the last page of the document to be printed @property NSInteger pagesAcross; // number of logical pages laid across a physical page @property NSInteger pagesDown; // number of logical pages laid out down a physical page @property (copy) NSDate *requestedPrintTime; // the time at which the desktop printer should print the document @property SystemPreferencesEnum errorHandling; // how errors are handled @property (copy) NSString *faxNumber; // for fax number @property (copy) NSString *targetPrinter; // for target printer - (void)closeSaving:(SystemPreferencesSavo) saving savingIn:(NSURL *)savingIn; // Close an object. - (void)delete; // Delete an object. - (void)duplicateTo:(SBObject *)to withProperties:(NSDictionary *)withProperties; // Copy object(s) and put the copies at a new location. - (BOOL)exists; // Verify if an object exists. - (void)moveTo:(SBObject *)to; // Move object(s) to a new location. - (void)saveAs:(NSString *)as in:(NSURL *)in_; // Save an object. @end
9,470
C++
.h
174
52.856322
377
0.777356
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
4,454
BGMAppWatcher.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMAppWatcher.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMAppWatcher.h // BGMApp // // Copyright © 2019 Kyle Neideck // // Calls callback functions when a given application is launched or terminated. Starts watching // after being initialised, stops after being destroyed. // // System Includes #import <Foundation/Foundation.h> #pragma clang assume_nonnull begin @interface BGMAppWatcher : NSObject // appLaunched will be called when the application is launched and appTerminated will be called when // it's terminated. Background apps, status bar apps, etc. are ignored. - (instancetype) initWithBundleID:(NSString*)bundleID appLaunched:(void(^)(void))appLaunched appTerminated:(void(^)(void))appTerminated; // With this constructor, when an application is launched or terminated, isMatchingBundleID will be // called first to decide whether or not the callback should be called. - (instancetype) initWithAppLaunched:(void(^)(void))appLaunched appTerminated:(void(^)(void))appTerminated isMatchingBundleID:(BOOL(^)(NSString* appBundleID))isMatchingBundleID; @end #pragma clang assume_nonnull end
1,849
C++
.h
39
44.025641
100
0.751667
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,455
BGMAudioDeviceManager.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMAudioDeviceManager.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMAudioDeviceManager.h // BGMApp // // Copyright © 2016-2018 Kyle Neideck // // Manages BGMDevice and the output device. Sets the system's current default device as the output // device on init, then starts playthrough and mirroring the devices' controls. // #if defined(__cplusplus) // Local Includes #import "BGMBackgroundMusicDevice.h" // PublicUtility Includes #import "CAHALAudioDevice.h" #endif /* defined(__cplusplus) */ // System Includes #import <Foundation/Foundation.h> #import <CoreAudio/AudioHardwareBase.h> // Forward Declarations @class BGMOutputVolumeMenuItem; @class BGMOutputDeviceMenuSection; #pragma clang assume_nonnull begin static const int kBGMErrorCode_OutputDeviceNotFound = 1; static const int kBGMErrorCode_ReturningEarly = 2; @interface BGMAudioDeviceManager : NSObject // Returns nil if BGMDevice isn't installed. - (instancetype) init; // Set the BGMOutputVolumeMenuItem to be notified when the output device is changed. - (void) setOutputVolumeMenuItem:(BGMOutputVolumeMenuItem*)item; // Set the BGMOutputDeviceMenuSection to be notified when the output device is changed. - (void) setOutputDeviceMenuSection:(BGMOutputDeviceMenuSection*)menuSection; // Set BGMDevice as the default audio device for all processes - (NSError* __nullable) setBGMDeviceAsOSDefault; // Replace BGMDevice as the default device with the output device - (NSError* __nullable) unsetBGMDeviceAsOSDefault; #ifdef __cplusplus // The virtual device published by BGMDriver. - (BGMBackgroundMusicDevice) bgmDevice; // The device BGMApp will play audio through, making it, from the user's perspective, the system's // default output device. - (CAHALAudioDevice) outputDevice; #endif - (BOOL) isOutputDevice:(AudioObjectID)deviceID; - (BOOL) isOutputDataSource:(UInt32)dataSourceID; // Set the audio output device that BGMApp uses. // // Returns an error if the output device couldn't be changed. If revertOnFailure is true in that case, // this method will attempt to set the output device back to the original device. If it fails to // revert, an additional error will be included in the error's userInfo with the key "revertError". // // Both errors' codes will be the code of the exception that caused the failure, if any, generally one // of the error constants from AudioHardwareBase.h. // // Blocks while the old device stops IO (if there was one). - (NSError* __nullable) setOutputDeviceWithID:(AudioObjectID)deviceID revertOnFailure:(BOOL)revertOnFailure; // As above, but also sets the new output device's data source. See kAudioDevicePropertyDataSource in // AudioHardware.h. - (NSError* __nullable) setOutputDeviceWithID:(AudioObjectID)deviceID dataSourceID:(UInt32)dataSourceID revertOnFailure:(BOOL)revertOnFailure; // Start playthrough synchronously. Blocks until IO has started on the output device and playthrough // is running. See BGMPlayThrough. // // Returns one of the error codes defined by this class or BGMPlayThrough, or an AudioHardware error // code received from the HAL. - (OSStatus) startPlayThroughSync:(BOOL)forUISoundsDevice; // When the output device is changed, BGMAudioDeviceManager will send the ID of the new output // device to BGMXPCHelper through this connection. - (void) setBGMXPCHelperConnection:(NSXPCConnection* __nullable)connection; @end #pragma clang assume_nonnull end
4,158
C++
.h
86
45.976744
102
0.780084
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,456
BGMXPCListener.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMXPCListener.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMXPCListener.h // BGMApp // // Copyright © 2016 Kyle Neideck // // Connects to BGMXPCHelper via XPC. When BGMDriver wants BGMApp to do something it can call one of BGMHelper's // XPC methods, which passes the request along to this class. // // Local Includes #import "BGMAudioDeviceManager.h" #import "BGMXPCProtocols.h" // System Includes #import <Foundation/Foundation.h> #pragma clang assume_nonnull begin @interface BGMXPCListener : NSObject <BGMAppXPCProtocol, NSXPCListenerDelegate> - (id) initWithAudioDevices:(BGMAudioDeviceManager*)devices helperConnectionErrorHandler:(void (^)(NSError* error))errorHandler; - (void) initHelperConnection; @end #pragma clang assume_nonnull end
1,413
C++
.h
34
40.235294
128
0.784357
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,457
BGMPlayThroughRTLogger.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMPlayThroughRTLogger.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMPlayThroughRTLogger.h // BGMApp // // Copyright © 2020 Kyle Neideck // // A real-time safe logger for BGMPlayThrough. The messages are logged asynchronously by a // non-realtime thread. // // For the sake of simplicity, this class is very closely coupled with BGMPlayThrough and its // methods make assumptions about where they will be called. Also, if the same logging method is // called multiple times before the logging thread next checks for messages, it will only log the // message for one of those calls and ignore the others. // // This class's methods are real-time safe in that they return in a bounded amount of time and we // think they're probably fast enough that the callers won't miss their deadlines, but we don't try // to guarantee it. Some of them should only be called in unusual cases where it's worth increasing // the risk of a thread missing its deadline. // #ifndef BGMApp__BGMPlayThroughRTLogger #define BGMApp__BGMPlayThroughRTLogger // PublicUtility Includes #include "CARingBuffer.h" // STL Includes #include <thread> // System Includes #include <mach/error.h> #include <mach/semaphore.h> #pragma clang assume_nonnull begin class BGMPlayThroughRTLogger { #pragma mark Construction/Destruction public: BGMPlayThroughRTLogger(); ~BGMPlayThroughRTLogger(); BGMPlayThroughRTLogger(const BGMPlayThroughRTLogger&) = delete; BGMPlayThroughRTLogger& operator=( const BGMPlayThroughRTLogger&) = delete; private: static semaphore_t CreateSemaphore(); #pragma mark Log Messages public: /*! For BGMPlayThrough::ReleaseThreadsWaitingForOutputToStart. */ void LogReleasingWaitingThreads(); /*! For BGMPlayThrough::ReleaseThreadsWaitingForOutputToStart. */ void LogIfMachError_ReleaseWaitingThreadsSignal(mach_error_t inError); /*! For BGMPlayThrough::OutputDeviceIOProc. Not thread-safe. */ void LogIfDroppedFrames(Float64 inFirstInputSampleTime, Float64 inLastInputSampleTime); /*! For BGMPlayThrough::OutputDeviceIOProc. Not thread-safe. */ void LogNoSamplesReady(CARingBuffer::SampleTime inLastInputSampleTime, CARingBuffer::SampleTime inReadHeadSampleTime, Float64 inInToOutSampleOffset); /*! For BGMPlayThrough::UpdateIOProcState. Not thread-safe. */ void LogExceptionStoppingIOProc(const char* inCallerName) { LogExceptionStoppingIOProc(inCallerName, noErr, false); } /*! For BGMPlayThrough::UpdateIOProcState. Not thread-safe. */ void LogExceptionStoppingIOProc(const char* inCallerName, OSStatus inError) { LogExceptionStoppingIOProc(inCallerName, inError, true); } private: void LogExceptionStoppingIOProc(const char* inCallerName, OSStatus inError, bool inErrorKnown); public: /*! For BGMPlayThrough::UpdateIOProcState. Not thread-safe. */ void LogUnexpectedIOStateAfterStopping(const char* inCallerName, int inIOState); /*! For BGMPlayThrough::InputDeviceIOProc and BGMPlayThrough::OutputDeviceIOProc. */ void LogRingBufferUnavailable(const char* inCallerName, bool inGotLock); /*! For BGMPlayThrough::OutputDeviceIOProc. */ void LogIfRingBufferError_Fetch(CARingBufferError inError) { LogIfRingBufferError(inError, mRingBufferFetchError); } /*! For BGMPlayThrough::InputDeviceIOProc. */ void LogIfRingBufferError_Store(CARingBufferError inError) { LogIfRingBufferError(inError, mRingBufferStoreError); } private: void LogIfRingBufferError(CARingBufferError inError, std::atomic<CARingBufferError>& outError); template <typename T, typename F> void LogAsync(T& inMessageData, F&& inStoreMessageData); // Wrapper methods used to mock out the logging for unit tests. void LogSync_Warning(const char* inFormat, ...) __printflike(2, 3); void LogSync_Error(const char* inFormat, ...) __printflike(2, 3); #pragma mark Logging Thread private: void WakeLoggingThread(); void LogMessages(); void LogSync_ReleasingWaitingThreads(); void LogSync_ReleaseWaitingThreadsSignalError(); void LogSync_DroppedFrames(); void LogSync_NoSamplesReady(); void LogSync_ExceptionStoppingIOProc(); void LogSync_UnexpectedIOStateAfterStopping(); void LogSync_RingBufferUnavailable(); void LogSync_RingBufferError( std::atomic<CARingBufferError>& ioRingBufferError, const char* inMethodName); // The entry point of the logging thread (mLoggingThread). static void* __nullable LoggingThreadEntry(BGMPlayThroughRTLogger* inRefCon); #if BGM_UnitTest #pragma mark Test Helpers public: /*! * @return True if the logger thread finished logging the requested messages. False if it still * had messages to log after 5 seconds. */ bool WaitUntilLoggerThreadIdle(); #endif /* BGM_UnitTest */ private: // For BGMPlayThrough::ReleaseThreadsWaitingForOutputToStart std::atomic<bool> mLogReleasingWaitingThreadsMsg { false }; std::atomic<kern_return_t> mReleaseWaitingThreadsSignalError { KERN_SUCCESS }; // For BGMPlayThrough::InputDeviceIOProc and BGMPlayThrough::OutputDeviceIOProc struct { Float64 firstInputSampleTime; Float64 lastInputSampleTime; std::atomic<bool> shouldLogMessage { false }; } mDroppedFrames; struct { CARingBuffer::SampleTime lastInputSampleTime; CARingBuffer::SampleTime readHeadSampleTime; Float64 inToOutSampleOffset; std::atomic<bool> shouldLogMessage { false }; } mNoSamplesReady; struct { const char* callerName; bool gotLock; std::atomic<bool> shouldLogMessage { false }; } mRingBufferUnavailable; // For BGMPlayThrough::UpdateIOProcState struct { const char* callerName; int ioState; std::atomic<bool> shouldLogMessage { false }; } mUnexpectedIOStateAfterStopping; struct { const char* callerName; OSStatus error; bool errorKnown; // If false, we didn't get an error code from the exception. std::atomic<bool> shouldLogMessage { false }; } mExceptionStoppingIOProc; // For BGMPlayThrough::OutputDeviceIOProc std::atomic<CARingBufferError> mRingBufferStoreError { kCARingBufferError_OK }; // For BGMPlayThrough::InputDeviceIOProc. std::atomic<CARingBufferError> mRingBufferFetchError { kCARingBufferError_OK }; // Signalled to wake up the mLoggingThread when it has messages to log. semaphore_t mWakeUpLoggingThreadSemaphore; std::atomic<bool> mLoggingThreadShouldExit { false }; // The thread that actually logs the messages. std::thread mLoggingThread; #if BGM_UnitTest public: // Tests normally crash (abort) if LogError is called. This flag lets us test the code that // would otherwise call LogError. bool mContinueOnErrorLogged { false }; int mNumDebugMessagesLogged { 0 }; int mNumWarningMessagesLogged { 0 }; int mNumErrorMessagesLogged { 0 }; #endif /* BGM_UnitTest */ }; #pragma clang assume_nonnull end #endif /* BGMApp__BGMPlayThroughRTLogger */
9,229
C++
.h
184
41.516304
100
0.636858
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,458
BGMVolumeChangeListener.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/BGMVolumeChangeListener.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMVolumeChangeListener.h // BGMApp // // Copyright © 2019 Kyle Neideck // // Local Includes #include "BGMBackgroundMusicDevice.h" // PublicUtility Includes #import "CAPropertyAddress.h" // STL Includes #include <functional> // System Includes #include <CoreAudio/CoreAudio.h> #pragma clang assume_nonnull begin class BGMVolumeChangeListener { public: /*! * @param device Listens for notifications about this device. * @param handler The function to call when the device's volume (or mute) changes. Called on the * main queue. */ BGMVolumeChangeListener(BGMAudioDevice device, std::function<void(void)> handler); virtual ~BGMVolumeChangeListener(); BGMVolumeChangeListener(const BGMVolumeChangeListener&) = delete; BGMVolumeChangeListener& operator=(const BGMVolumeChangeListener&) = delete; private: AudioObjectPropertyListenerBlock mListenerBlock; BGMAudioDevice mDevice; }; #pragma clang assume_nonnull end
1,723
C++
.h
46
35.130435
100
0.75601
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,459
BGMAppDelegate+AppleScript.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Scripting/BGMAppDelegate+AppleScript.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMAppDelegate+AppleScript.h // BGMApp // // Copyright © 2017 Kyle Neideck // Copyright © 2021 Marcus Wu // #import "BGMAppDelegate.h" // Local Includes #import "BGMASOutputDevice.h" #import "BGMASApplication.h" // System Includes #import <Foundation/Foundation.h> #pragma clang assume_nonnull begin @interface BGMAppDelegate (AppleScript) - (BOOL) application:(NSApplication*)sender delegateHandlesKey:(NSString*)key; @property BGMASOutputDevice* selectedOutputDevice; @property (readonly) NSArray<BGMASOutputDevice*>* outputDevices; @property double mainVolume; @property (readonly) NSArray<BGMASApplication*>* applications; @end #pragma clang assume_nonnull end
1,390
C++
.h
36
37.222222
78
0.788806
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,460
BGMASApplication.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Scripting/BGMASApplication.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMASApplication.h // BGMApp // // Copyright © 2021 Marcus Wu // Copyright © 2021 Kyle Neideck // // An AppleScript class for volume and pan settings for running applications. // // Local Includes #import "BGMAppVolumesController.h" // System Includes #import <Foundation/Foundation.h> #import <Cocoa/Cocoa.h> NS_ASSUME_NONNULL_BEGIN @interface BGMASApplication : NSObject - (instancetype) initWithApplication:(NSRunningApplication*)app volumeController:(BGMAppVolumesController*)volumeController parentSpecifier:(NSScriptObjectSpecifier* __nullable)parentSpecifier index:(int)i; @property (readonly) NSString* name; @property (readonly) NSString* bundleID; @property int volume; @property int pan; @end NS_ASSUME_NONNULL_END
1,528
C++
.h
40
34.95
89
0.748645
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,461
BGMASOutputDevice.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Scripting/BGMASOutputDevice.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMASOutputDevice.h // BGMApp // // Copyright © 2017 Kyle Neideck // // An AppleScript class for the output devices that can be selected in the preferences menu. // // Local Includes #import "BGMAudioDeviceManager.h" // System Includes #import <Foundation/Foundation.h> #pragma clang assume_nonnull begin @interface BGMASOutputDevice : NSObject - (instancetype) initWithAudioObjectID:(AudioObjectID)objID audioDevices:(BGMAudioDeviceManager*)devices parentSpecifier:(NSScriptObjectSpecifier* __nullable)parentSpecifier; @property (readonly) NSString* name; @property BOOL selected; // is this the device to be used for audio output? @end #pragma clang assume_nonnull end
1,444
C++
.h
35
38.542857
93
0.761087
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,462
VOX.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/VOX.h
/* * VOX.h * * Generated with * sdef /Applications/VOX.app | sdp -fh --basename VOX */ #import <AppKit/AppKit.h> #import <ScriptingBridge/ScriptingBridge.h> @class VoxApplication, VoxApplication; /* * Standard Suite */ // The application's top level scripting object. @interface VoxApplication : SBApplication @property (copy, readonly) NSString *name; // The name of the application. @property (readonly) BOOL frontmost; // Is this the frontmost (active) application? @property (copy, readonly) NSString *version; // The version of the application. - (void) quit; // Quit an application. - (void) pause; // Pause playback. - (void) play; // Begin playback. - (void) playpause; // Toggle playback between playing and paused. - (void) next; // Skip to the next track in the playlist. - (void) previous; // Skip to the previous track in the playlist. - (void) shuffle; // Shuffle the tracks in the playlist. - (void) playUrl:(NSString *)x; // Play specified URL. - (void) addUrl:(NSString *)x; // Add specified URL to playlist - (void) rewindForward; // Rewind current track forward. - (void) rewindForwardFast; // Rewind current track forward fast. - (void) rewindBackward; // Rewind current track backward. - (void) rewindBackwardFast; // Rewind current track backward fast. - (void) increasVolume; // Increase volume. - (void) decreaseVolume; // Decrease volume. - (void) showHidePlaylist; // Show/Hide playlist. @end /* * Vox Suite */ // The application's top-level scripting object. @interface VoxApplication (VoxSuite) @property (copy, readonly) NSData *tiffArtworkData; // Current track artwork data in TIFF format. @property (copy, readonly) NSImage *artworkImage; // Current track artwork as an image. @property (readonly) NSInteger playerState; // Player state (playing = 1, paused = 0) @property (copy, readonly) NSString *track; // Current track title. @property (copy, readonly) NSString *trackUrl; // Current track URL. @property (copy, readonly) NSString *artist; // Current track artist. @property (copy, readonly) NSString *albumArtist; // Current track album artist. @property (copy, readonly) NSString *album; // Current track album. @property (copy, readonly) NSString *uniqueID; // Unique identifier for the current track. @property double currentTime; // The current playback position. @property (readonly) double totalTime; // The total time of the currently playing track. @property double playerVolume; // Player volume (0.0 to 1.0) @property NSInteger repeatState; // Player repeat state (none = 0, repeat one = 1, repeat all = 2) @end
2,618
C++
.h
53
47.90566
99
0.737441
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
4,463
BGMVLC.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/BGMVLC.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMVLC.h // BGMApp // // Copyright © 2016 Kyle Neideck // // Superclass/Protocol Import #import "BGMMusicPlayer.h" @interface BGMVLC : BGMMusicPlayerBase<BGMMusicPlayer> @end
892
C++
.h
24
35.916667
75
0.767981
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,464
BGMDecibel.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/BGMDecibel.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMDecibel.h // BGMApp // // Copyright © 2016 Kyle Neideck // // Superclass/Protocol Import #import "BGMMusicPlayer.h" @interface BGMDecibel : BGMMusicPlayerBase<BGMMusicPlayer> @end
900
C++
.h
24
36.25
75
0.770115
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,465
BGMScriptingBridge.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/BGMScriptingBridge.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMScriptingBridge.h // BGMApp // // Copyright © 2016, 2018 Kyle Neideck // // A wrapper around Scripting Bridge's SBApplication that tries to avoid ever launching the application. // // We use Scripting Bridge to communicate with music player apps, which we never want to launch // ourselves. But creating an SBApplication for an app, or sending messages/events to an existing one, // can launch the app. // // As a workaround, this class has an SBApplication property, application (see below), which is nil // unless the music player app is running. That way messages sent while the app is closed are ignored. // // Local Includes #import "BGMMusicPlayer.h" // System Includes #import <Cocoa/Cocoa.h> #import <ScriptingBridge/ScriptingBridge.h> #pragma clang assume_nonnull begin @interface BGMScriptingBridge : NSObject <SBApplicationDelegate> // Only keeps a weak ref to musicPlayer. - (instancetype) initWithMusicPlayer:(id<BGMMusicPlayer>)musicPlayer; // If the music player application is running, this property is the Scripting Bridge object representing // it. If not, it's set to nil. Used to send Apple events to the music player app. @property (readonly) __kindof SBApplication* __nullable application; // macOS 10.14 requires the user's permission to send Apple Events. If the music player that owns // this object (i.e. the one passed to initWithMusicPlayer) is currently the selected music player // and the user hasn't already given us permission to send it Apple Events, this method asks the // user for permission. - (void) ensurePermission; // SBApplicationDelegate // On 10.11, SBApplicationDelegate.h declares eventDidFail with a non-null return type, but the docs // specifically say that returning nil is allowed. #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wnullability" - (id __nullable) eventDidFail:(const AppleEvent*)event withError:(NSError*)error; #pragma clang diagnostic pop @end #pragma clang assume_nonnull end
2,697
C++
.h
55
47.781818
105
0.783866
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,466
BGMMusicPlayer.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/BGMMusicPlayer.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMMusicPlayer.h // BGMApp // // Copyright © 2016, 2018, 2019 Kyle Neideck // // The base classes and protocol for objects that represent a music player app. // // To add support for a music player, create a class that implements the BGMMusicPlayer protocol // and add it to initWithAudioDevices in BGMMusicPlayers.mm. // // You'll probably want to subclass BGMMusicPlayerBase and, if the music player supports // AppleScript, use BGMScriptingBridge. Your class might need to override the icon method if the // default implementation from BGMMusicPlayerBase doesn't work. // // BGMSpotify will probably be the most useful example to follow, but they're all pretty // similar. The music player classes written so far all use Scripting Bridge to communicate with // the music player apps (see iTunes.h/Spotify.h) but any other way is fine too. // // BGMDriver will use either the music player's bundle ID or PID to match it to the audio it // plays. (Though using PIDs hasn't been tested yet.) // // If you're not sure what bundle ID the music player uses, install a debug build of BGMDriver // and play something in the music player. The easiest way is to do // build_and_install.sh -d // BGMDriver will log the bundle ID to system.log when it becomes aware of the music player. // // Local Includes #import "BGMUserDefaults.h" // System Includes #import <Cocoa/Cocoa.h> #pragma clang assume_nonnull begin @protocol BGMMusicPlayer <NSObject> // Classes return an instance of themselves for each music player app they make available in // BGMApp. So far that's always been a single instance, but that will probably change eventually. // Most classes don't need to override the default implementation from BGMMusicPlayerBase. // // But, for example, a class for custom music players would probably return an instance for each // custom player the user has created. (Also note that it could return an empty array.) // // TODO: I think the return type should actually be NSArray<instancetype>*, but that doesn't seem // to work. There's a Clang bug about this: https://llvm.org/bugs/show_bug.cgi?id=27323 // (though it hasn't been confirmed yet). + (NSArray<id<BGMMusicPlayer>>*) createInstancesWithDefaults:(BGMUserDefaults*)userDefaults; // We need a unique ID for each music player to store in user defaults. In the most common case, // classes that provide a static (or at least bounded) number of music players, you can generate // IDs with uuidgen (the command line tool) and include them in your class as constants. Otherwise, // you'll probably want to store them in user defaults and load them in createInstancesWithDefaults. @property (readonly) NSUUID* musicPlayerID; // The name, tool-tip and icon of the music player, to be used in the UI. @property (readonly) NSString* name; @property (readonly) NSString* __nullable toolTip; @property (readonly) NSImage* __nullable icon; @property (readonly) NSString* __nullable bundleID; // Classes will usually ignore this property and leave it nil unless the music player has no // bundle ID. // // TODO: If we ever add a music player class that uses this property, it'll need a way to inform // BGMDevice of changes. It might be easiest to have BGMMusicPlayers to observe this property, // on the selected music player, with KVO and update BGMDevice when it changes. Or // BGMMusicPlayers could pass a pointer to itself to createInstancesWithDefaults. @property NSNumber* __nullable pid; // True if this is currently the selected music player. @property (readonly) BOOL selected; // The state of the music player. // // True if the music player app is open. @property (readonly, getter=isRunning) BOOL running; // True if the music player is playing a song or some other user-selected audio file. Note that // the music player playing audio for UI, notifications, etc. won't make this true (which is why we // need this property and can't just ask BGMDriver if the music player is playing audio). @property (readonly, getter=isPlaying) BOOL playing; // True if the music player has a current/open song (or whatever) and will continue playing it if // BGMMusicPlayer::unpause is called. Normally because the user was playing a song and they or // BGMApp paused it. @property (readonly, getter=isPaused) BOOL paused; // Called when the user selects this music player. - (void) wasSelected; // Called when this was the selected music player and the user just selected a different one. - (void) wasDeselected; // Pause the music player. Does nothing if the music player is already paused or isn't running. // Returns YES if the music player is paused now but wasn't before, returns NO otherwise. - (BOOL) pause; // Unpause the music player. Does nothing if the music player is already playing or isn't running. // Returns YES if the music player is playing now but wasn't before, returns NO otherwise. - (BOOL) unpause; @end @interface BGMMusicPlayerBase : NSObject - (instancetype) initWithMusicPlayerID:(NSUUID*)musicPlayerID name:(NSString*)name bundleID:(NSString* __nullable)bundleID; - (instancetype) initWithMusicPlayerID:(NSUUID*)musicPlayerID name:(NSString*)name toolTip:(NSString*)toolTip bundleID:(NSString* __nullable)bundleID; - (instancetype) initWithMusicPlayerID:(NSUUID*)musicPlayerID name:(NSString*)name toolTip:(NSString* __nullable)toolTip bundleID:(NSString* __nullable)bundleID pid:(NSNumber* __nullable)pid; // Convenience wrapper around NSUUID's initWithUUIDString. musicPlayerIDString must be a string // generated by uuidgen (command line tool), e.g. "60BA9739-B6DD-4E6A-8134-51410A45BB84". + (NSUUID*) makeID:(NSString*)musicPlayerIDString; // BGMMusicPlayer default implementations + (NSArray<id<BGMMusicPlayer>>*) createInstancesWithDefaults:(BGMUserDefaults*)userDefaults; @property (readonly) NSImage* __nullable icon; @property (readonly) NSUUID* musicPlayerID; @property (readonly) NSString* name; @property (readonly) NSString* __nullable toolTip; @property (readonly) NSString* __nullable bundleID; @property NSNumber* __nullable pid; @property (readonly) BOOL selected; - (void) wasSelected; - (void) wasDeselected; @end #pragma clang assume_nonnull end
7,213
C++
.h
130
52.061538
100
0.745359
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,467
BGMMusicPlayers.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/BGMMusicPlayers.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMMusicPlayers.h // BGMApp // // Copyright © 2016, 2019 Kyle Neideck // // Holds the music players (i.e. BGMMusicPlayer objects) available in BGMApp. Also keeps track of // which music player is currently selected by the user. // // Local Includes #import "BGMAudioDeviceManager.h" #import "BGMMusicPlayer.h" #import "BGMUserDefaults.h" // System Includes #import <Foundation/Foundation.h> #pragma clang assume_nonnull begin @interface BGMMusicPlayers : NSObject // Calls initWithAudioDevices:musicPlayers: with sensible defaults. - (instancetype) initWithAudioDevices:(BGMAudioDeviceManager*)devices userDefaults:(BGMUserDefaults*)defaults; // defaultMusicPlayerID is the musicPlayerID (see BGMMusicPlayer.h) of the music player that should be // selected by default. // // The createInstancesWithDefaults method of each class in musicPlayerClasses will be called and // the results will be stored in the musicPlayers property. - (instancetype) initWithAudioDevices:(BGMAudioDeviceManager*)devices defaultMusicPlayerID:(NSUUID*)defaultMusicPlayerID musicPlayerClasses:(NSArray<Class<BGMMusicPlayer>>*)musicPlayerClasses userDefaults:(BGMUserDefaults*)defaults; @property (readonly) NSArray<id<BGMMusicPlayer>>* musicPlayers; // The music player currently selected in the preferences menu. BGMDevice is informed when this property // is changed. @property id<BGMMusicPlayer> selectedMusicPlayer; @end #pragma clang assume_nonnull end
2,247
C++
.h
49
42.836735
104
0.773455
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,468
BGMSpotify.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/BGMSpotify.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMSpotify.h // BGMApp // // Copyright © 2016 Kyle Neideck // // Superclass/Protocol Import #import "BGMMusicPlayer.h" @interface BGMSpotify : BGMMusicPlayerBase<BGMMusicPlayer> @end
900
C++
.h
24
36.25
75
0.770115
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,469
Decibel.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/Decibel.h
/* * Decibel.h * * Generated with * sdef /Applications/Decibel.app | sdp -fh --basename Decibel */ #import <AppKit/AppKit.h> #import <ScriptingBridge/ScriptingBridge.h> @class DecibelApplication, DecibelDocument, DecibelWindow, DecibelApplication, DecibelTrack; enum DecibelSaveOptions { DecibelSaveOptionsYes = 'yes ' /* Save the file. */, DecibelSaveOptionsNo = 'no ' /* Do not save the file. */, DecibelSaveOptionsAsk = 'ask ' /* Ask the user whether or not to save the file. */ }; typedef enum DecibelSaveOptions DecibelSaveOptions; enum DecibelPrintingErrorHandling { DecibelPrintingErrorHandlingStandard = 'lwst' /* Standard PostScript error handling */, DecibelPrintingErrorHandlingDetailed = 'lwdt' /* print a detailed report of PostScript errors */ }; typedef enum DecibelPrintingErrorHandling DecibelPrintingErrorHandling; enum DecibelShuffleMode { DecibelShuffleModeOff = 'off ' /* Off */, DecibelShuffleModeTrack = 'trck' /* Track */, DecibelShuffleModeAlbum = 'albm' /* Album */, DecibelShuffleModeArtist = 'arts' /* Artist */ }; typedef enum DecibelShuffleMode DecibelShuffleMode; enum DecibelRepeatMode { DecibelRepeatModeOff = 'off ' /* Off */, DecibelRepeatModeTrack = 'trck' /* Track */, DecibelRepeatModeAlbum = 'albm' /* Album */, DecibelRepeatModeArtist = 'arts' /* Artist */, DecibelRepeatModeAll = 'all ' /* All */ }; typedef enum DecibelRepeatMode DecibelRepeatMode; @protocol DecibelGenericMethods - (void) closeSaving:(DecibelSaveOptions)saving savingIn:(NSURL *)savingIn; // Close a document. - (void) saveIn:(NSURL *)in_ as:(id)as; // Save a document. - (void) printWithProperties:(NSDictionary *)withProperties printDialog:(BOOL)printDialog; // Print a document. - (void) delete; // Delete an object. - (void) duplicateTo:(SBObject *)to withProperties:(NSDictionary *)withProperties; // Copy an object. - (void) moveTo:(SBObject *)to; // Move an object to a new location. @end /* * Standard Suite */ // The application's top-level scripting object. @interface DecibelApplication : SBApplication - (SBElementArray<DecibelDocument *> *) documents; - (SBElementArray<DecibelWindow *> *) windows; @property (copy, readonly) NSString *name; // The name of the application. @property (readonly) BOOL frontmost; // Is this the active application? @property (copy, readonly) NSString *version; // The version number of the application. - (id) open:(id)x; // Open a document. - (void) print:(id)x withProperties:(NSDictionary *)withProperties printDialog:(BOOL)printDialog; // Print a document. - (void) quitSaving:(DecibelSaveOptions)saving; // Quit the application. - (BOOL) exists:(id)x; // Verify that an object exists. - (void) play; // Begin audio playback - (void) pause; // Suspend audio playback - (void) stop; // Stop audio playback - (void) playPause; // Begin or suspend audio playback - (void) seekForward; // Seek forward three seconds - (void) seekBackward; // Seek backward three seconds - (void) playSelection; // Play the selected track, or the first track if more than one are selected - (void) playPreviousTrack; // Play the previous logical track in the playlist - (void) playNextTrack; // Play the next logical track in the playlist - (void) addFile:(NSURL *)x; // Add a file to the playlist - (void) playFile:(NSURL *)x; // Add a file to the playlist and play it - (void) playTrackAtIndex:(NSInteger)x; // Play a track in the playlist - (void) increaseDeviceVolume; // Increase the device volume - (void) decreaseDeviceVolume; // Decrease the device volume - (void) increaseDigitalVolume; // Increase the digital volume - (void) decreaseDigitalVolume; // Decrease the digital volume - (void) clearPlaylist; // Clear the playlist - (void) scramblePlaylist; // Scramble the playlist @end // A document. @interface DecibelDocument : SBObject <DecibelGenericMethods> @property (copy, readonly) NSString *name; // Its name. @property (readonly) BOOL modified; // Has it been modified since the last save? @property (copy, readonly) NSURL *file; // Its location on disk, if it has one. @end // A window. @interface DecibelWindow : SBObject <DecibelGenericMethods> @property (copy, readonly) NSString *name; // The title of the window. - (NSInteger) id; // The unique identifier of the window. @property NSInteger index; // The index of the window, ordered front to back. @property NSRect bounds; // The bounding rectangle of the window. @property (readonly) BOOL closeable; // Does the window have a close button? @property (readonly) BOOL miniaturizable; // Does the window have a minimize button? @property BOOL miniaturized; // Is the window minimized right now? @property (readonly) BOOL resizable; // Can the window be resized? @property BOOL visible; // Is the window visible right now? @property (readonly) BOOL zoomable; // Does the window have a zoom button? @property BOOL zoomed; // Is the window zoomed right now? @property (copy, readonly) DecibelDocument *document; // The document whose contents are displayed in the window. @end /* * Decibel Scripting Suite */ // The Decibel application class. @interface DecibelApplication (DecibelScriptingSuite) - (SBElementArray<DecibelTrack *> *) tracks; @property (readonly) BOOL playing; // Is the player currently playing? @property (readonly) BOOL shuffling; // Is the player currently shuffling? @property (readonly) BOOL repeating; // Is the player currently repeating? @property (copy, readonly) DecibelTrack *nowPlaying; // The track that is currently playing? @property double deviceVolume; // The current device volume @property double digitalVolume; // The current digital volume @property double playbackPosition; // The current playback position [0, 1] @property double playbackTime; // The current playback time in seconds @property (readonly) BOOL canPlay; // Is the player currently playing? @property (readonly) BOOL canPlayPreviousTrack; // Is the player currently playing? @property (readonly) BOOL canPlayNextTrack; // Is the player currently playing? @property (readonly) BOOL canAdjustDeviceVolume; // Can the device volume be adjusted? @property DecibelShuffleMode shuffleMode; // Player shuffle mode @property DecibelRepeatMode repeatMode; // Player repeat mode @property (copy, readonly) SBObject *currentPlaylist; // The current playlist @end // A track in the playlist @interface DecibelTrack : SBObject <DecibelGenericMethods> - (NSString *) id; // The track's ID @property (copy, readonly) NSURL *file; // The track's location @property (readonly) double duration; // The track's duration in seconds @property (readonly) double sampleRate; // The track's sample rate in Hz @property (readonly) NSInteger bitDepth; // The bit depth @property (readonly) NSInteger channels; // The track's channels @property (copy) NSString *title; // The track's title @property (copy) NSString *artist; // The track's artist @property (copy) NSString *albumTitle; // The track's album title @property (copy) NSString *albumArtist; // The track's album artist @property NSInteger trackNumber; // The track's track number @property NSInteger trackTotal; // The total number of tracks on the album @property NSInteger discNumber; // The disc number containing the track @property NSInteger discTotal; // The total number of discs (for multidisc albums) @property BOOL partOfACompilation; // Is the track part of a compilation? @property (copy) NSString *genre; // The track's genre @property (copy) NSString *composer; // The track's composer @property (copy) NSString *releaseDate; // The track's release date @property (copy) NSString *ISRC; // The track's ISRC @property (copy) id MCN; // The track's MCN - (void) playTrack; // Play a track in the playlist @end
7,810
C++
.h
143
53.188811
119
0.757111
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,470
VLC.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/VLC.h
/* * VLC.h * * Generated with * sdef /Applications/VLC.app | sdp -fh --basename VLC */ #import <AppKit/AppKit.h> #import <ScriptingBridge/ScriptingBridge.h> @class VLCItem, VLCApplication, VLCColor, VLCDocument, VLCWindow, VLCAttributeRun, VLCCharacter, VLCParagraph, VLCText, VLCAttachment, VLCWord, VLCPrintSettings; enum VLCSavo { VLCSavoAsk = 'ask ' /* Ask the user whether or not to save the file. */, VLCSavoNo = 'no ' /* Do not save the file. */, VLCSavoYes = 'yes ' /* Save the file. */ }; typedef enum VLCSavo VLCSavo; enum VLCEnum { VLCEnumStandard = 'lwst' /* Standard PostScript error handling */, VLCEnumDetailed = 'lwdt' /* print a detailed report of PostScript errors */ }; typedef enum VLCEnum VLCEnum; @protocol VLCGenericMethods - (void) closeSaving:(VLCSavo)saving savingIn:(NSURL *)savingIn; // Close an object. - (void) delete; // Delete an object. - (void) duplicateTo:(SBObject *)to withProperties:(NSDictionary *)withProperties; // Copy object(s) and put the copies at a new location. - (BOOL) exists; // Verify if an object exists. - (void) moveTo:(SBObject *)to; // Move object(s) to a new location. - (void) saveAs:(NSString *)as in:(NSURL *)in_; // Save an object. - (void) fullscreen; // Toggle between fullscreen and windowed mode. - (void) GetURL; // Get a URL - (void) mute; // Mute the audio - (void) next; // Go to the next item in the playlist or the next chapter in the DVD/VCD. - (void) OpenURL; // Open a URL - (void) play; // Start playing the current playlistitem or pause it when it is already playing. - (void) previous; // Go to the previous item in the playlist or the previous chapter in the DVD/VCD. - (void) stepBackward; // Step the current playlist item backward the specified step width (default is 2) (1=extraShort, 2=short, 3=medium, 4=long). - (void) stepForward; // Step the current playlist item forward the specified step width (default is 2) (1=extraShort, 2=short, 3=medium, 4=long). - (void) stop; // Stop playing the current playlistitem - (void) volumeDown; // Bring the volume down by one step. There are 32 steps from 0 to 400% volume. - (void) volumeUp; // Bring the volume up by one step. There are 32 steps from 0 to 400% volume. @end /* * Standard Suite */ // A scriptable object. @interface VLCItem : SBObject <VLCGenericMethods> @property (copy) NSDictionary *properties; // All of the object's properties. @end // An application's top level scripting object. @interface VLCApplication : SBApplication - (SBElementArray<VLCDocument *> *) documents; - (SBElementArray<VLCWindow *> *) windows; @property (readonly) BOOL frontmost; // Is this the frontmost (active) application? @property (copy, readonly) NSString *name; // The name of the application. @property (copy, readonly) NSString *version; // The version of the application. - (VLCDocument *) open:(NSURL *)x; // Open an object. - (void) print:(NSURL *)x printDialog:(BOOL)printDialog withProperties:(VLCPrintSettings *)withProperties; // Print an object. - (void) quitSaving:(VLCSavo)saving; // Quit an application. @end // A color. @interface VLCColor : VLCItem @end // A document. @interface VLCDocument : VLCItem @property (readonly) BOOL modified; // Has the document been modified since the last save? @property (copy) NSString *name; // The document's name. @property (copy) NSString *path; // The document's path. @end // A window. @interface VLCWindow : VLCItem @property NSRect bounds; // The bounding rectangle of the window. @property (readonly) BOOL closeable; // Whether the window has a close box. @property (copy, readonly) VLCDocument *document; // The document whose contents are being displayed in the window. @property (readonly) BOOL floating; // Whether the window floats. - (NSInteger) id; // The unique identifier of the window. @property NSInteger index; // The index of the window, ordered front to back. @property (readonly) BOOL miniaturizable; // Whether the window can be miniaturized. @property BOOL miniaturized; // Whether the window is currently miniaturized. @property (readonly) BOOL modal; // Whether the window is the application's current modal window. @property (copy) NSString *name; // The full title of the window. @property (readonly) BOOL resizable; // Whether the window can be resized. @property (readonly) BOOL titled; // Whether the window has a title bar. @property BOOL visible; // Whether the window is currently visible. @property (readonly) BOOL zoomable; // Whether the window can be zoomed. @property BOOL zoomed; // Whether the window is currently zoomed. @end /* * Text Suite */ // This subdivides the text into chunks that all have the same attributes. @interface VLCAttributeRun : VLCItem - (SBElementArray<VLCAttachment *> *) attachments; - (SBElementArray<VLCAttributeRun *> *) attributeRuns; - (SBElementArray<VLCCharacter *> *) characters; - (SBElementArray<VLCParagraph *> *) paragraphs; - (SBElementArray<VLCWord *> *) words; @property (copy) NSColor *color; // The color of the first character. @property (copy) NSString *font; // The name of the font of the first character. @property NSInteger size; // The size in points of the first character. @end // This subdivides the text into characters. @interface VLCCharacter : VLCItem - (SBElementArray<VLCAttachment *> *) attachments; - (SBElementArray<VLCAttributeRun *> *) attributeRuns; - (SBElementArray<VLCCharacter *> *) characters; - (SBElementArray<VLCParagraph *> *) paragraphs; - (SBElementArray<VLCWord *> *) words; @property (copy) NSColor *color; // The color of the first character. @property (copy) NSString *font; // The name of the font of the first character. @property NSInteger size; // The size in points of the first character. @end // This subdivides the text into paragraphs. @interface VLCParagraph : VLCItem - (SBElementArray<VLCAttachment *> *) attachments; - (SBElementArray<VLCAttributeRun *> *) attributeRuns; - (SBElementArray<VLCCharacter *> *) characters; - (SBElementArray<VLCParagraph *> *) paragraphs; - (SBElementArray<VLCWord *> *) words; @property (copy) NSColor *color; // The color of the first character. @property (copy) NSString *font; // The name of the font of the first character. @property NSInteger size; // The size in points of the first character. @end // Rich (styled) text @interface VLCText : VLCItem - (SBElementArray<VLCAttachment *> *) attachments; - (SBElementArray<VLCAttributeRun *> *) attributeRuns; - (SBElementArray<VLCCharacter *> *) characters; - (SBElementArray<VLCParagraph *> *) paragraphs; - (SBElementArray<VLCWord *> *) words; @property (copy) NSColor *color; // The color of the first character. @property (copy) NSString *font; // The name of the font of the first character. @property NSInteger size; // The size in points of the first character. @end // Represents an inline text attachment. This class is used mainly for make commands. @interface VLCAttachment : VLCText @property (copy) NSString *fileName; // The path to the file for the attachment @end // This subdivides the text into words. @interface VLCWord : VLCItem - (SBElementArray<VLCAttachment *> *) attachments; - (SBElementArray<VLCAttributeRun *> *) attributeRuns; - (SBElementArray<VLCCharacter *> *) characters; - (SBElementArray<VLCParagraph *> *) paragraphs; - (SBElementArray<VLCWord *> *) words; @property (copy) NSColor *color; // The color of the first character. @property (copy) NSString *font; // The name of the font of the first character. @property NSInteger size; // The size in points of the first character. @end /* * VLC suite */ // VLC's top level scripting object @interface VLCApplication (VLCSuite) @property NSInteger audioVolume; // The volume of the current playlist item from 0 to 4, where 4 is 400% @property NSInteger currentTime; // The current time of the current playlist item in seconds. @property (readonly) NSInteger durationOfCurrentItem; // The duration of the current playlist item in seconds. @property BOOL fullscreenMode; // indicates whether fullscreen is enabled or not @property (readonly) BOOL muted; // Is VLC currently muted? @property (copy, readonly) NSString *nameOfCurrentItem; // Name of the current playlist item. @property (copy, readonly) NSString *pathOfCurrentItem; // Path to the current playlist item. @property (readonly) BOOL playing; // Is VLC playing an item? @end /* * Type Definitions */ @interface VLCPrintSettings : SBObject <VLCGenericMethods> @property NSInteger copies; // the number of copies of a document to be printed @property BOOL collating; // Should printed copies be collated? @property NSInteger startingPage; // the first page of the document to be printed @property NSInteger endingPage; // the last page of the document to be printed @property NSInteger pagesAcross; // number of logical pages laid across a physical page @property NSInteger pagesDown; // number of logical pages laid out down a physical page @property (copy) NSDate *requestedPrintTime; // the time at which the desktop printer should print the document @property VLCEnum errorHandling; // how errors are handled @property (copy) NSString *faxNumber; // for fax number @property (copy) NSString *targetPrinter; // for target printer @end
9,346
C++
.h
176
51.5625
161
0.751237
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,471
BGMiTunes.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/BGMiTunes.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMiTunes.h // BGMApp // // Copyright © 2016 Kyle Neideck // // Superclass/Protocol Import #import "BGMMusicPlayer.h" @interface BGMiTunes : BGMMusicPlayerBase<BGMMusicPlayer> // The music player ID (see BGMMusicPlayer.h) used by BGMiTunes instances. (Though BGMApp only ever creates one instance of // BGMiTunes, sharedMusicPlayerID is exposed so iTunes can be set as the default music player.) + (NSUUID*) sharedMusicPlayerID; @end
1,152
C++
.h
27
41.407407
123
0.775492
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,472
Hermes.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/Hermes.h
/* * Hermes.h * * Generated with * sdef /Applications/Hermes.app | sdp -fh --basename Hermes */ #import <AppKit/AppKit.h> #import <ScriptingBridge/ScriptingBridge.h> @class HermesApplication, HermesSong, HermesStation; // Legal player states enum HermesPlayerStates { HermesPlayerStatesStopped = 'stop' /* Player is stopped */, HermesPlayerStatesPlaying = 'play' /* Player is playing */, HermesPlayerStatesPaused = 'paus' /* Player is paused */ }; typedef enum HermesPlayerStates HermesPlayerStates; /* * Hermes Suite */ // The Pandora player. @interface HermesApplication : SBApplication - (SBElementArray<HermesStation *> *) stations; @property NSInteger playbackVolume; // The current playback volume (0–100). @property HermesPlayerStates playbackState; // The current playback state. @property (readonly) double playbackPosition; // The current song’s playback position, in seconds. @property (readonly) double currentSongDuration; // The duration (length) of the current song, in seconds. @property (copy) HermesStation *currentStation; // The currently selected Pandora station. @property (copy, readonly) HermesSong *currentSong; // The currently playing (or paused) Pandora song (WARNING: This is an invalid reference in current versions of Hermes; you must access the current song’s properties individually or as a group directly instead.) - (void) playpause; // Play the current song if it is paused; pause the current song if it is playing. - (void) pause; // Pause the currently playing song. - (void) play; // Resume playing the current song. - (void) nextSong; // Skip to the next song on the current station. - (void) thumbsUp; // Tell Pandora you like the current song. - (void) thumbsDown; // Tell Pandora you don’t like the current song. - (void) tiredOfSong; // Tell Pandora you’re tired of the current song. - (void) increaseVolume; // Increase the playback volume. - (void) decreaseVolume; // Decrease the playback volume. - (void) maximizeVolume; // Set the playback volume to its maximum level. - (void) mute; // Mutes playback, saving the current volume level. - (void) unmute; // Restores the volume to the level prior to muting. @end // A Pandora song (track). @interface HermesSong : SBObject @property (copy, readonly) NSString *title; // The song’s title. @property (copy, readonly) NSString *artist; // The song’s artist. @property (copy, readonly) NSString *album; // The song’s album. @property (copy, readonly) NSString *artworkURL; // An image URL for the album’s cover artwork. @property (readonly) NSInteger rating; // The song’s numeric rating. @property (copy, readonly) NSString *albumURL; // A Pandora URL for more information on the album. @property (copy, readonly) NSString *artistURL; // A Pandora URL for more information on the artist. @property (copy, readonly) NSString *trackURL; // A Pandora URL for more information on the track. @end // A Pandora station. @interface HermesStation : SBObject @property (copy, readonly) NSString *name; // The station’s name. @property (copy, readonly) NSString *stationID; // The station’s ID. @end
3,167
C++
.h
57
53.596491
264
0.754649
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,473
Music.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/Music.h
/* * Music.h * * Generated with * sdef /System/Applications/Music.app | sdp -fh --basename Music */ #import <AppKit/AppKit.h> #import <ScriptingBridge/ScriptingBridge.h> @class MusicApplication, MusicItem, MusicAirPlayDevice, MusicArtwork, MusicEncoder, MusicEQPreset, MusicPlaylist, MusicAudioCDPlaylist, MusicLibraryPlaylist, MusicRadioTunerPlaylist, MusicSource, MusicSubscriptionPlaylist, MusicTrack, MusicAudioCDTrack, MusicFileTrack, MusicSharedTrack, MusicURLTrack, MusicUserPlaylist, MusicFolderPlaylist, MusicVisual, MusicWindow, MusicBrowserWindow, MusicEQWindow, MusicMiniplayerWindow, MusicPlaylistWindow, MusicVideoWindow; enum MusicEKnd { MusicEKndTrackListing = 'kTrk' /* a basic listing of tracks within a playlist */, MusicEKndAlbumListing = 'kAlb' /* a listing of a playlist grouped by album */, MusicEKndCdInsert = 'kCDi' /* a printout of the playlist for jewel case inserts */ }; typedef enum MusicEKnd MusicEKnd; enum MusicEnum { MusicEnumStandard = 'lwst' /* Standard PostScript error handling */, MusicEnumDetailed = 'lwdt' /* print a detailed report of PostScript errors */ }; typedef enum MusicEnum MusicEnum; enum MusicEPlS { MusicEPlSStopped = 'kPSS', MusicEPlSPlaying = 'kPSP', MusicEPlSPaused = 'kPSp', MusicEPlSFastForwarding = 'kPSF', MusicEPlSRewinding = 'kPSR' }; typedef enum MusicEPlS MusicEPlS; enum MusicERpt { MusicERptOff = 'kRpO', MusicERptOne = 'kRp1', MusicERptAll = 'kAll' }; typedef enum MusicERpt MusicERpt; enum MusicEShM { MusicEShMSongs = 'kShS', MusicEShMAlbums = 'kShA', MusicEShMGroupings = 'kShG' }; typedef enum MusicEShM MusicEShM; enum MusicESrc { MusicESrcLibrary = 'kLib', MusicESrcIPod = 'kPod', MusicESrcAudioCD = 'kACD', MusicESrcMP3CD = 'kMCD', MusicESrcRadioTuner = 'kTun', MusicESrcSharedLibrary = 'kShd', MusicESrcITunesStore = 'kITS', MusicESrcUnknown = 'kUnk' }; typedef enum MusicESrc MusicESrc; enum MusicESrA { MusicESrAAlbums = 'kSrL' /* albums only */, MusicESrAAll = 'kAll' /* all text fields */, MusicESrAArtists = 'kSrR' /* artists only */, MusicESrAComposers = 'kSrC' /* composers only */, MusicESrADisplayed = 'kSrV' /* visible text fields */, MusicESrASongs = 'kSrS' /* song names only */ }; typedef enum MusicESrA MusicESrA; enum MusicESpK { MusicESpKNone = 'kNon', MusicESpKFolder = 'kSpF', MusicESpKGenius = 'kSpG', MusicESpKLibrary = 'kSpL', MusicESpKMusic = 'kSpZ', MusicESpKPurchasedMusic = 'kSpM' }; typedef enum MusicESpK MusicESpK; enum MusicEMdK { MusicEMdKSong = 'kMdS' /* music track */, MusicEMdKMusicVideo = 'kVdV' /* music video track */, MusicEMdKUnknown = 'kUnk' }; typedef enum MusicEMdK MusicEMdK; enum MusicERtK { MusicERtKUser = 'kRtU' /* user-specified rating */, MusicERtKComputed = 'kRtC' /* iTunes-computed rating */ }; typedef enum MusicERtK MusicERtK; enum MusicEAPD { MusicEAPDComputer = 'kAPC', MusicEAPDAirPortExpress = 'kAPX', MusicEAPDAppleTV = 'kAPT', MusicEAPDAirPlayDevice = 'kAPO', MusicEAPDBluetoothDevice = 'kAPB', MusicEAPDHomePod = 'kAPH', MusicEAPDUnknown = 'kAPU' }; typedef enum MusicEAPD MusicEAPD; enum MusicEClS { MusicEClSUnknown = 'kUnk', MusicEClSPurchased = 'kPur', MusicEClSMatched = 'kMat', MusicEClSUploaded = 'kUpl', MusicEClSIneligible = 'kRej', MusicEClSRemoved = 'kRem', MusicEClSError = 'kErr', MusicEClSDuplicate = 'kDup', MusicEClSSubscription = 'kSub', MusicEClSNoLongerAvailable = 'kRev', MusicEClSNotUploaded = 'kUpP' }; typedef enum MusicEClS MusicEClS; @protocol MusicGenericMethods - (void) printPrintDialog:(BOOL)printDialog withProperties:(NSDictionary *)withProperties kind:(MusicEKnd)kind theme:(NSString *)theme; // Print the specified object(s) - (void) close; // Close an object - (void) delete; // Delete an element from an object - (SBObject *) duplicateTo:(SBObject *)to; // Duplicate one or more object(s) - (BOOL) exists; // Verify if an object exists - (void) open; // Open the specified object(s) - (void) save; // Save the specified object(s) - (void) playOnce:(BOOL)once; // play the current track or the specified track or file. - (void) select; // select the specified object(s) @end /* * iTunes Suite */ // The application program @interface MusicApplication : SBApplication - (SBElementArray<MusicAirPlayDevice *> *) AirPlayDevices; - (SBElementArray<MusicBrowserWindow *> *) browserWindows; - (SBElementArray<MusicEncoder *> *) encoders; - (SBElementArray<MusicEQPreset *> *) EQPresets; - (SBElementArray<MusicEQWindow *> *) EQWindows; - (SBElementArray<MusicMiniplayerWindow *> *) miniplayerWindows; - (SBElementArray<MusicPlaylist *> *) playlists; - (SBElementArray<MusicPlaylistWindow *> *) playlistWindows; - (SBElementArray<MusicSource *> *) sources; - (SBElementArray<MusicTrack *> *) tracks; - (SBElementArray<MusicVideoWindow *> *) videoWindows; - (SBElementArray<MusicVisual *> *) visuals; - (SBElementArray<MusicWindow *> *) windows; @property (readonly) BOOL AirPlayEnabled; // is AirPlay currently enabled? @property (readonly) BOOL converting; // is a track currently being converted? @property (copy) NSArray<MusicAirPlayDevice *> *currentAirPlayDevices; // the currently selected AirPlay device(s) @property (copy) MusicEncoder *currentEncoder; // the currently selected encoder (MP3, AIFF, WAV, etc.) @property (copy) MusicEQPreset *currentEQPreset; // the currently selected equalizer preset @property (copy, readonly) MusicPlaylist *currentPlaylist; // the playlist containing the currently targeted track @property (copy, readonly) NSString *currentStreamTitle; // the name of the current song in the playing stream (provided by streaming server) @property (copy, readonly) NSString *currentStreamURL; // the URL of the playing stream or streaming web site (provided by streaming server) @property (copy, readonly) MusicTrack *currentTrack; // the current targeted track @property (copy) MusicVisual *currentVisual; // the currently selected visual plug-in @property BOOL EQEnabled; // is the equalizer enabled? @property BOOL fixedIndexing; // true if all AppleScript track indices should be independent of the play order of the owning playlist. @property BOOL frontmost; // is iTunes the frontmost application? @property BOOL fullScreen; // are visuals displayed using the entire screen? @property (copy, readonly) NSString *name; // the name of the application @property BOOL mute; // has the sound output been muted? @property double playerPosition; // the player’s position within the currently playing track in seconds. @property (readonly) MusicEPlS playerState; // is iTunes stopped, paused, or playing? @property (copy, readonly) SBObject *selection; // the selection visible to the user @property BOOL shuffleEnabled; // are songs played in random order? @property MusicEShM shuffleMode; // the playback shuffle mode @property MusicERpt songRepeat; // the playback repeat mode @property NSInteger soundVolume; // the sound output volume (0 = minimum, 100 = maximum) @property (copy, readonly) NSString *version; // the version of iTunes @property BOOL visualsEnabled; // are visuals currently being displayed? - (void) printPrintDialog:(BOOL)printDialog withProperties:(NSDictionary *)withProperties kind:(MusicEKnd)kind theme:(NSString *)theme; // Print the specified object(s) - (void) run; // Run iTunes - (void) quit; // Quit iTunes - (MusicTrack *) add:(NSArray<NSURL *> *)x to:(SBObject *)to; // add one or more files to a playlist - (void) backTrack; // reposition to beginning of current track or go to previous track if already at start of current track - (MusicTrack *) convert:(NSArray<SBObject *> *)x; // convert one or more files or tracks - (void) fastForward; // skip forward in a playing track - (void) nextTrack; // advance to the next track in the current playlist - (void) pause; // pause playback - (void) playOnce:(BOOL)once; // play the current track or the specified track or file. - (void) playpause; // toggle the playing/paused state of the current track - (void) previousTrack; // return to the previous track in the current playlist - (void) resume; // disable fast forward/rewind and resume playback, if playing. - (void) rewind; // skip backwards in a playing track - (void) stop; // stop playback - (void) openLocation:(NSString *)x; // Opens a Music Store or audio stream URL @end // an item @interface MusicItem : SBObject <MusicGenericMethods> @property (copy, readonly) SBObject *container; // the container of the item - (NSInteger) id; // the id of the item @property (readonly) NSInteger index; // The index of the item in internal application order. @property (copy) NSString *name; // the name of the item @property (copy, readonly) NSString *persistentID; // the id of the item as a hexadecimal string. This id does not change over time. @property (copy) NSDictionary *properties; // every property of the item - (void) download; // download a cloud track or playlist - (void) reveal; // reveal and select a track or playlist @end // an AirPlay device @interface MusicAirPlayDevice : MusicItem @property (readonly) BOOL active; // is the device currently being played to? @property (readonly) BOOL available; // is the device currently available? @property (readonly) MusicEAPD kind; // the kind of the device @property (copy, readonly) NSString *networkAddress; // the network (MAC) address of the device - (BOOL) protected; // is the device password- or passcode-protected? @property BOOL selected; // is the device currently selected? @property (readonly) BOOL supportsAudio; // does the device support audio playback? @property (readonly) BOOL supportsVideo; // does the device support video playback? @property NSInteger soundVolume; // the output volume for the device (0 = minimum, 100 = maximum) @end // a piece of art within a track or playlist @interface MusicArtwork : MusicItem @property (copy) NSImage *data; // data for this artwork, in the form of a picture @property (copy) NSString *objectDescription; // description of artwork as a string @property (readonly) BOOL downloaded; // was this artwork downloaded by iTunes? @property (copy, readonly) NSNumber *format; // the data format for this piece of artwork @property NSInteger kind; // kind or purpose of this piece of artwork @property (copy) NSData *rawData; // data for this artwork, in original format @end // converts a track to a specific file format @interface MusicEncoder : MusicItem @property (copy, readonly) NSString *format; // the data format created by the encoder @end // equalizer preset configuration @interface MusicEQPreset : MusicItem @property double band1; // the equalizer 32 Hz band level (-12.0 dB to +12.0 dB) @property double band2; // the equalizer 64 Hz band level (-12.0 dB to +12.0 dB) @property double band3; // the equalizer 125 Hz band level (-12.0 dB to +12.0 dB) @property double band4; // the equalizer 250 Hz band level (-12.0 dB to +12.0 dB) @property double band5; // the equalizer 500 Hz band level (-12.0 dB to +12.0 dB) @property double band6; // the equalizer 1 kHz band level (-12.0 dB to +12.0 dB) @property double band7; // the equalizer 2 kHz band level (-12.0 dB to +12.0 dB) @property double band8; // the equalizer 4 kHz band level (-12.0 dB to +12.0 dB) @property double band9; // the equalizer 8 kHz band level (-12.0 dB to +12.0 dB) @property double band10; // the equalizer 16 kHz band level (-12.0 dB to +12.0 dB) @property (readonly) BOOL modifiable; // can this preset be modified? @property double preamp; // the equalizer preamp level (-12.0 dB to +12.0 dB) @property BOOL updateTracks; // should tracks which refer to this preset be updated when the preset is renamed or deleted? @end // a list of songs/streams @interface MusicPlaylist : MusicItem - (SBElementArray<MusicTrack *> *) tracks; - (SBElementArray<MusicArtwork *> *) artworks; @property (copy) NSString *objectDescription; // the description of the playlist @property BOOL disliked; // is this playlist disliked? @property (readonly) NSInteger duration; // the total length of all songs (in seconds) @property (copy) NSString *name; // the name of the playlist @property BOOL loved; // is this playlist loved? @property (copy, readonly) MusicPlaylist *parent; // folder which contains this playlist (if any) @property (readonly) NSInteger size; // the total size of all songs (in bytes) @property (readonly) MusicESpK specialKind; // special playlist kind @property (copy, readonly) NSString *time; // the length of all songs in MM:SS format @property (readonly) BOOL visible; // is this playlist visible in the Source list? - (void) moveTo:(SBObject *)to; // Move playlist(s) to a new location - (MusicTrack *) searchFor:(NSString *)for_ only:(MusicESrA)only; // search a playlist for tracks matching the search string. Identical to entering search text in the Search field in iTunes. @end // a playlist representing an audio CD @interface MusicAudioCDPlaylist : MusicPlaylist - (SBElementArray<MusicAudioCDTrack *> *) audioCDTracks; @property (copy) NSString *artist; // the artist of the CD @property BOOL compilation; // is this CD a compilation album? @property (copy) NSString *composer; // the composer of the CD @property NSInteger discCount; // the total number of discs in this CD’s album @property NSInteger discNumber; // the index of this CD disc in the source album @property (copy) NSString *genre; // the genre of the CD @property NSInteger year; // the year the album was recorded/released @end // the master music library playlist @interface MusicLibraryPlaylist : MusicPlaylist - (SBElementArray<MusicFileTrack *> *) fileTracks; - (SBElementArray<MusicURLTrack *> *) URLTracks; - (SBElementArray<MusicSharedTrack *> *) sharedTracks; @end // the radio tuner playlist @interface MusicRadioTunerPlaylist : MusicPlaylist - (SBElementArray<MusicURLTrack *> *) URLTracks; @end // a music source (music library, CD, device, etc.) @interface MusicSource : MusicItem - (SBElementArray<MusicAudioCDPlaylist *> *) audioCDPlaylists; - (SBElementArray<MusicLibraryPlaylist *> *) libraryPlaylists; - (SBElementArray<MusicPlaylist *> *) playlists; - (SBElementArray<MusicRadioTunerPlaylist *> *) radioTunerPlaylists; - (SBElementArray<MusicSubscriptionPlaylist *> *) subscriptionPlaylists; - (SBElementArray<MusicUserPlaylist *> *) userPlaylists; @property (readonly) long long capacity; // the total size of the source if it has a fixed size @property (readonly) long long freeSpace; // the free space on the source if it has a fixed size @property (readonly) MusicESrc kind; @end // a subscription playlist from Apple Music @interface MusicSubscriptionPlaylist : MusicPlaylist - (SBElementArray<MusicFileTrack *> *) fileTracks; - (SBElementArray<MusicURLTrack *> *) URLTracks; @end // playable audio source @interface MusicTrack : MusicItem - (SBElementArray<MusicArtwork *> *) artworks; @property (copy) NSString *album; // the album name of the track @property (copy) NSString *albumArtist; // the album artist of the track @property BOOL albumDisliked; // is the album for this track disliked? @property BOOL albumLoved; // is the album for this track loved? @property NSInteger albumRating; // the rating of the album for this track (0 to 100) @property (readonly) MusicERtK albumRatingKind; // the rating kind of the album rating for this track @property (copy) NSString *artist; // the artist/source of the track @property (readonly) NSInteger bitRate; // the bit rate of the track (in kbps) @property double bookmark; // the bookmark time of the track in seconds @property BOOL bookmarkable; // is the playback position for this track remembered? @property NSInteger bpm; // the tempo of this track in beats per minute @property (copy) NSString *category; // the category of the track @property (readonly) MusicEClS cloudStatus; // the iCloud status of the track @property (copy) NSString *comment; // freeform notes about the track @property BOOL compilation; // is this track from a compilation album? @property (copy) NSString *composer; // the composer of the track @property (readonly) NSInteger databaseID; // the common, unique ID for this track. If two tracks in different playlists have the same database ID, they are sharing the same data. @property (copy, readonly) NSDate *dateAdded; // the date the track was added to the playlist @property (copy) NSString *objectDescription; // the description of the track @property NSInteger discCount; // the total number of discs in the source album @property NSInteger discNumber; // the index of the disc containing this track on the source album @property BOOL disliked; // is this track disliked? @property (copy, readonly) NSString *downloaderAppleID; // the Apple ID of the person who downloaded this track @property (copy, readonly) NSString *downloaderName; // the name of the person who downloaded this track @property (readonly) double duration; // the length of the track in seconds @property BOOL enabled; // is this track checked for playback? @property (copy) NSString *episodeID; // the episode ID of the track @property NSInteger episodeNumber; // the episode number of the track @property (copy) NSString *EQ; // the name of the EQ preset of the track @property double finish; // the stop time of the track in seconds @property BOOL gapless; // is this track from a gapless album? @property (copy) NSString *genre; // the music/audio genre (category) of the track @property (copy) NSString *grouping; // the grouping (piece) of the track. Generally used to denote movements within a classical work. @property (copy, readonly) NSString *kind; // a text description of the track @property (copy) NSString *longDescription; @property BOOL loved; // is this track loved? @property (copy) NSString *lyrics; // the lyrics of the track @property MusicEMdK mediaKind; // the media kind of the track @property (copy, readonly) NSDate *modificationDate; // the modification date of the content of this track @property (copy) NSString *movement; // the movement name of the track @property NSInteger movementCount; // the total number of movements in the work @property NSInteger movementNumber; // the index of the movement in the work @property NSInteger playedCount; // number of times this track has been played @property (copy) NSDate *playedDate; // the date and time this track was last played @property (copy, readonly) NSString *purchaserAppleID; // the Apple ID of the person who purchased this track @property (copy, readonly) NSString *purchaserName; // the name of the person who purchased this track @property NSInteger rating; // the rating of this track (0 to 100) @property (readonly) MusicERtK ratingKind; // the rating kind of this track @property (copy, readonly) NSDate *releaseDate; // the release date of this track @property (readonly) NSInteger sampleRate; // the sample rate of the track (in Hz) @property NSInteger seasonNumber; // the season number of the track @property BOOL shufflable; // is this track included when shuffling? @property NSInteger skippedCount; // number of times this track has been skipped @property (copy) NSDate *skippedDate; // the date and time this track was last skipped @property (copy) NSString *show; // the show name of the track @property (copy) NSString *sortAlbum; // override string to use for the track when sorting by album @property (copy) NSString *sortArtist; // override string to use for the track when sorting by artist @property (copy) NSString *sortAlbumArtist; // override string to use for the track when sorting by album artist @property (copy) NSString *sortName; // override string to use for the track when sorting by name @property (copy) NSString *sortComposer; // override string to use for the track when sorting by composer @property (copy) NSString *sortShow; // override string to use for the track when sorting by show name @property (readonly) long long size; // the size of the track (in bytes) @property double start; // the start time of the track in seconds @property (copy, readonly) NSString *time; // the length of the track in MM:SS format @property NSInteger trackCount; // the total number of tracks on the source album @property NSInteger trackNumber; // the index of the track on the source album @property BOOL unplayed; // is this track unplayed? @property NSInteger volumeAdjustment; // relative volume adjustment of the track (-100% to 100%) @property (copy) NSString *work; // the work name of the track @property NSInteger year; // the year the track was recorded/released @end // a track on an audio CD @interface MusicAudioCDTrack : MusicTrack @property (copy, readonly) NSURL *location; // the location of the file represented by this track @end // a track representing an audio file (MP3, AIFF, etc.) @interface MusicFileTrack : MusicTrack @property (copy) NSURL *location; // the location of the file represented by this track - (void) refresh; // update file track information from the current information in the track’s file @end // a track residing in a shared library @interface MusicSharedTrack : MusicTrack @end // a track representing a network stream @interface MusicURLTrack : MusicTrack @property (copy) NSString *address; // the URL for this track @end // custom playlists created by the user @interface MusicUserPlaylist : MusicPlaylist - (SBElementArray<MusicFileTrack *> *) fileTracks; - (SBElementArray<MusicURLTrack *> *) URLTracks; - (SBElementArray<MusicSharedTrack *> *) sharedTracks; @property BOOL shared; // is this playlist shared? @property (readonly) BOOL smart; // is this a Smart Playlist? @property (readonly) BOOL genius; // is this a Genius Playlist? @end // a folder that contains other playlists @interface MusicFolderPlaylist : MusicUserPlaylist @end // a visual plug-in @interface MusicVisual : MusicItem @end // any window @interface MusicWindow : MusicItem @property NSRect bounds; // the boundary rectangle for the window @property (readonly) BOOL closeable; // does the window have a close button? @property (readonly) BOOL collapseable; // does the window have a collapse button? @property BOOL collapsed; // is the window collapsed? @property BOOL fullScreen; // is the window full screen? @property NSPoint position; // the upper left position of the window @property (readonly) BOOL resizable; // is the window resizable? @property BOOL visible; // is the window visible? @property (readonly) BOOL zoomable; // is the window zoomable? @property BOOL zoomed; // is the window zoomed? @end // the main iTunes window @interface MusicBrowserWindow : MusicWindow @property (copy, readonly) SBObject *selection; // the selected songs @property (copy) MusicPlaylist *view; // the playlist currently displayed in the window @end // the iTunes equalizer window @interface MusicEQWindow : MusicWindow @end // the miniplayer window @interface MusicMiniplayerWindow : MusicWindow @end // a sub-window showing a single playlist @interface MusicPlaylistWindow : MusicWindow @property (copy, readonly) SBObject *selection; // the selected songs @property (copy, readonly) MusicPlaylist *view; // the playlist displayed in the window @end // the video window @interface MusicVideoWindow : MusicWindow @end
23,439
C++
.h
419
54.46778
465
0.765729
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
4,474
Spotify.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/Spotify.h
/* * Spotify.h * * Generated with * sdef /Applications/Spotify.app | sdp -fh --basename Spotify */ #import <AppKit/AppKit.h> #import <ScriptingBridge/ScriptingBridge.h> @class SpotifyApplication, SpotifyTrack, SpotifyApplication; enum SpotifyEPlS { SpotifyEPlSStopped = 'kPSS', SpotifyEPlSPlaying = 'kPSP', SpotifyEPlSPaused = 'kPSp' }; typedef enum SpotifyEPlS SpotifyEPlS; /* * Spotify Suite */ // The Spotify application. @interface SpotifyApplication : SBApplication @property (copy, readonly) SpotifyTrack *currentTrack; // The current playing track. @property NSInteger soundVolume; // The sound output volume (0 = minimum, 100 = maximum) @property (readonly) SpotifyEPlS playerState; // Is Spotify stopped, paused, or playing? @property double playerPosition; // The player’s position within the currently playing track in seconds. @property (readonly) BOOL repeatingEnabled; // Is repeating enabled in the current playback context? @property BOOL repeating; // Is repeating on or off? @property (readonly) BOOL shufflingEnabled; // Is shuffling enabled in the current playback context? @property BOOL shuffling; // Is shuffling on or off? - (void) nextTrack; // Skip to the next track. - (void) previousTrack; // Skip to the previous track. - (void) playpause; // Toggle play/pause. - (void) pause; // Pause playback. - (void) play; // Resume playback. - (void) playTrack:(NSString *)x inContext:(NSString *)inContext; // Start playback of a track in the given context. @end // A Spotify track. @interface SpotifyTrack : SBObject @property (copy, readonly) NSString *artist; // The artist of the track. @property (copy, readonly) NSString *album; // The album of the track. @property (readonly) NSInteger discNumber; // The disc number of the track. @property (readonly) NSInteger duration; // The length of the track in seconds. @property (readonly) NSInteger playedCount; // The number of times this track has been played. @property (readonly) NSInteger trackNumber; // The index of the track in its album. @property (readonly) BOOL starred; // Is the track starred? @property (readonly) NSInteger popularity; // How popular is this track? 0-100 - (NSString *) id; // The ID of the item. @property (copy, readonly) NSString *name; // The name of the track. @property (copy, readonly) NSImage *artwork; // The track's album cover. @property (copy, readonly) NSString *albumArtist; // That album artist of the track. @property (copy) NSString *spotifyUrl; // The URL of the track. @end /* * Standard Suite */ // The application's top level scripting object. @interface SpotifyApplication (StandardSuite) @property (copy, readonly) NSString *name; // The name of the application. @property (readonly) BOOL frontmost; // Is this the frontmost (active) application? @property (copy, readonly) NSString *version; // The version of the application. @end
2,923
C++
.h
60
47.15
117
0.753256
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
true
true
false
false
false
false
false
false
4,475
Swinsian.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/Swinsian.h
/* * Swinsian.h * * Generated with * sdef /Applications/Swinsian.app | sdp -fh --basename Swinsian */ #import <AppKit/AppKit.h> #import <ScriptingBridge/ScriptingBridge.h> @class SwinsianItem, SwinsianColor, SwinsianWindow, SwinsianApplication, SwinsianPlaylist, SwinsianLibrary, SwinsianTrack, SwinsianLibraryTrack, SwinsianIPodTrack, SwinsianQueue, SwinsianSmartPlaylist, SwinsianNormalPlaylist, SwinsianPlaylistFolder, SwinsianAudioDevice; enum SwinsianSaveOptions { SwinsianSaveOptionsYes = 'yes ' /* Save the file. */, SwinsianSaveOptionsNo = 'no ' /* Do not save the file. */, SwinsianSaveOptionsAsk = 'ask ' /* Ask the user whether or not to save the file. */ }; typedef enum SwinsianSaveOptions SwinsianSaveOptions; enum SwinsianPlayerState { SwinsianPlayerStateStopped = 'kPSS', SwinsianPlayerStatePlaying = 'kPSP', SwinsianPlayerStatePaused = 'kPSp' }; typedef enum SwinsianPlayerState SwinsianPlayerState; @protocol SwinsianGenericMethods - (void) closeSaving:(SwinsianSaveOptions)saving savingIn:(NSURL *)savingIn; // Close an object. - (void) delete; // Delete an object. - (void) duplicateTo:(SBObject *)to withProperties:(NSDictionary *)withProperties; // Copy object(s) and put the copies at a new location. - (BOOL) exists; // Verify if an object exists. - (void) moveTo:(SBObject *)to; // Move object(s) to a new location. - (void) saveIn:(NSURL *)in_ as:(NSString *)as; // Save an object. @end /* * Standard Suite */ // A scriptable object. @interface SwinsianItem : SBObject <SwinsianGenericMethods> @property (copy) NSDictionary *properties; // All of the object's properties. @end // A color. @interface SwinsianColor : SBObject <SwinsianGenericMethods> @end // A window. @interface SwinsianWindow : SBObject <SwinsianGenericMethods> @property (copy) NSString *name; // The full title of the window. - (NSNumber *) id; // The unique identifier of the window. @property NSRect bounds; // The bounding rectangle of the window. @property (readonly) BOOL closeable; // Whether the window has a close box. @property (readonly) BOOL titled; // Whether the window has a title bar. @property (copy) NSNumber *index; // The index of the window in the back-to-front window ordering. @property (readonly) BOOL floating; // Whether the window floats. @property (readonly) BOOL miniaturizable; // Whether the window can be miniaturized. @property BOOL miniaturized; // Whether the window is currently miniaturized. @property (readonly) BOOL modal; // Whether the window is the application's current modal window. @property (readonly) BOOL resizable; // Whether the window can be resized. @property BOOL visible; // Whether the window is currently visible. @property (readonly) BOOL zoomable; // Whether the window can be zoomed. @property BOOL zoomed; // Whether the window is currently zoomed. @property (copy, readonly) NSArray<SwinsianTrack *> *selection; // Currently seleted tracks @end /* * Swinsian Suite */ // The application @interface SwinsianApplication : SBApplication - (SBElementArray<SwinsianWindow *> *) windows; - (SBElementArray<SwinsianPlaylist *> *) playlists; - (SBElementArray<SwinsianSmartPlaylist *> *) smartPlaylists; - (SBElementArray<SwinsianNormalPlaylist *> *) normalPlaylists; - (SBElementArray<SwinsianLibrary *> *) libraries; - (SBElementArray<SwinsianTrack *> *) tracks; - (SBElementArray<SwinsianAudioDevice *> *) audioDevices; @property (copy, readonly) NSString *name; // The name of the application. @property (readonly) BOOL frontmost; // Is this the frontmost (active) application? @property (copy, readonly) NSString *version; // The version of the application. @property NSInteger playerPosition; // the player’s position within the currently playing track in seconds. @property (copy, readonly) SwinsianTrack *currentTrack; // the currently playing track @property (copy) NSNumber *soundVolume; // the volume. (0 minimum, 100 maximum) @property (readonly) SwinsianPlayerState playerState; // are we stopped, paused or still playing? @property (copy, readonly) SwinsianQueue *playbackQueue; // the currently queued tracks @property (copy) SwinsianAudioDevice *outputDevice; // current audio output device - (void) open:(NSURL *)x; // Open an object. - (void) print:(NSURL *)x; // Print an object. - (void) quitSaving:(SwinsianSaveOptions)saving; // Quit an application. - (void) play; // begin playing the current playlist - (void) pause; // pause playback - (void) nextTrack; // skip to the next track in the current playlist - (void) stop; // stop playback - (NSArray<SwinsianTrack *> *) searchPlaylist:(SwinsianPlaylist *)playlist for:(NSString *)for_; // search a playlist for tracks matching a string - (void) previousTrack; // skip back to the previous track - (void) playpause; // toggle play/pause - (void) addTracks:(NSArray<SwinsianTrack *> *)tracks to:(SwinsianNormalPlaylist *)to; // add a track to a playlist - (void) notify; // show currently playing track notification - (void) rescanTags:(NSArray<SwinsianTrack *> *)x; // rescan tags on tracks - (NSArray<SwinsianTrack *> *) findTrack:(NSString *)x; // Finds tracks for the given path - (void) removeTracks:(NSArray<SwinsianTrack *> *)tracks from:(SwinsianNormalPlaylist *)from; // remove tracks from a playlist @end // generic playlist type, subcasses include smart playlist and normal playlist @interface SwinsianPlaylist : SwinsianItem - (SBElementArray<SwinsianTrack *> *) tracks; @property (copy) NSString *name; // the name of the playlist @property (readonly) BOOL smart; // is this a smart playlist @end @interface SwinsianLibrary : SwinsianItem - (SBElementArray<SwinsianTrack *> *) tracks; @end // a music track @interface SwinsianTrack : SwinsianItem @property (copy) NSString *album; // the album of the track @property (copy) NSString *artist; // the artist @property (copy) NSString *composer; // the composer @property (copy) NSString *genre; // the genre @property (copy, readonly) NSString *time; // the length of the track in text format as MM:SS @property NSInteger year; // the year the track was recorded @property (copy, readonly) NSDate *dateAdded; // the date the track was added to the library @property (readonly) double duration; // the length of the track in seconds @property (copy, readonly) NSString *location; // location on disk @property (readonly) BOOL iPodTrack; // TRUE if the track is on an iPod @property (copy) NSString *name; // the title of the track (same as title) @property (readonly) NSInteger bitRate; // the bitrate of the track @property (copy, readonly) NSString *kind; // a text description of the type of file the track is @property (copy) NSNumber *rating; // Track rating. 0-5 @property NSInteger trackNumber; // the Track number @property (readonly) NSInteger fileSize; // file size in bytes @property (copy, readonly) NSImage *albumArt; // the album artwork @property (copy, readonly) NSString *artFormat; // the data format for this piece of artwork. text that will be "PNG" or "JPEG". getting the album art property first will mean this information has been retrieved already, otherwise the tags for the file will have to be re-read @property (copy) NSNumber *discNumber; // the disc number @property (copy) NSNumber *discCount; // the total number of discs in the album - (NSString *) id; // uuid @property (copy) NSString *albumArtist; // the album artist @property (copy, readonly) NSString *albumArtistOrArtist; // the album artist of the track, or is none is set, the artist @property BOOL compilation; // compilation flag @property (copy) NSString *title; // track title (the same as name) @property (copy) NSString *comment; // the comment @property (copy, readonly) NSDate *dateCreated; // the date created @property (readonly) NSInteger channels; // audio channel count @property (readonly) NSInteger sampleRate; // audio sample rate @property (readonly) NSInteger bitDepth; // the audio bit depth @property (copy) NSDate *lastPlayed; // date track was last played @property (copy) NSString *lyrics; // track lyrics @property (copy, readonly) NSString *path; // POSIX style path @property (copy) NSString *grouping; // grouping @property (copy) NSString *publisher; // the publisher @property (copy) NSString *conductor; // the conductor @property (copy) NSString *objectDescription; // the description @property (copy, readonly) NSString *encoder; // the encoder @property (copy, readonly) NSString *copyright; // the copyright @property (copy) NSString *catalogNumber; // the catalog number @property (copy, readonly) NSDate *dateModified; // the date modified @property NSInteger playCount; // the play count @property (copy) NSNumber *trackCount; // the total number of tracks in the album @end @interface SwinsianLibraryTrack : SwinsianTrack @end @interface SwinsianIPodTrack : SwinsianTrack @property (copy, readonly) NSString *iPodName; // the name of the iPod this track is on @end // The playback queue @interface SwinsianQueue : SwinsianItem - (SBElementArray<SwinsianTrack *> *) tracks; @end // a smart playlist @interface SwinsianSmartPlaylist : SwinsianPlaylist @end // a normal, non-smart, playlist @interface SwinsianNormalPlaylist : SwinsianPlaylist - (SBElementArray<SwinsianTrack *> *) tracks; - (NSString *) id; // uuid @end // folder of playlists @interface SwinsianPlaylistFolder : SwinsianPlaylist - (SBElementArray<SwinsianPlaylist *> *) playlists; - (NSString *) id; // uuid @end // an audio output device @interface SwinsianAudioDevice : SBObject <SwinsianGenericMethods> @property (copy, readonly) NSString *name; // device name - (NSString *) id; // uuid - (void) setId: (NSString *) id; @end
9,792
C++
.h
177
53.813559
277
0.760063
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,476
BGMGooglePlayMusicDesktopPlayer.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/BGMGooglePlayMusicDesktopPlayer.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMGooglePlayMusicDesktopPlayer.h // BGMApp // // Copyright © 2019 Kyle Neideck // // We have a lot more code for GPMDP than most music players largely because GPMDP has a WebSockets // API and because the user has to enter a code from GPMDP to allow BGMApp to control it. // Currently, the other music players all have AppleScript APIs, so for them the OS asks the user // for permission on our behalf automatically and handles the whole process for us. // // This class implements the usual BGMMusicPlayer methods and handles the UI for authenticating // with GPMDP. BGMGooglePlayMusicDesktopPlayerConnection manages the connection to GPMDP and hides // the details of its API. // // Superclass/Protocol Import #import "BGMMusicPlayer.h" #pragma clang assume_nonnull begin API_AVAILABLE(macos(10.10)) @interface BGMGooglePlayMusicDesktopPlayer : BGMMusicPlayerBase<BGMMusicPlayer> + (NSArray<id<BGMMusicPlayer>>*) createInstancesWithDefaults:(BGMUserDefaults*)userDefaults; @end #pragma clang assume_nonnull end
1,741
C++
.h
37
45.810811
100
0.789971
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,477
BGMMusic.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/BGMMusic.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMMusic.h // BGMApp // // Copyright © 2016, 2019 Kyle Neideck // Copyright © 2019 theLMGN // // Superclass/Protocol Import #import "BGMMusicPlayer.h" #pragma clang assume_nonnull begin @interface BGMMusic : BGMMusicPlayerBase<BGMMusicPlayer> @end #pragma clang assume_nonnull end
1,002
C++
.h
27
35.740741
75
0.772021
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,478
BGMVOX.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/BGMVOX.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMVOX.h // BGMApp // // Copyright © 2016 Kyle Neideck // // Superclass/Protocol Import #import "BGMMusicPlayer.h" @interface BGMVOX : BGMMusicPlayerBase<BGMMusicPlayer> @end
892
C++
.h
24
35.916667
75
0.767981
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,479
BGMGooglePlayMusicDesktopPlayerConnection.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/BGMGooglePlayMusicDesktopPlayerConnection.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMGooglePlayMusicDesktopPlayerConnection.h // BGMApp // // Copyright © 2019 Kyle Neideck // // Local Includes #import "BGMUserDefaults.h" // System Includes #import <Cocoa/Cocoa.h> #import <WebKit/WebKit.h> #pragma clang assume_nonnull begin API_AVAILABLE(macos(10.10)) @interface BGMGooglePlayMusicDesktopPlayerConnection : NSObject<WKScriptMessageHandler> // authRequiredHandler: A UI callback that asks the user for the auth code GPMDP will display. // Returns the auth code they entered, or nil. // connectionErrorHandler: A UI callback that shows a connection error message. // apiVersionMismatchHandler: A UI callback that shows a warning dialog explaining that GPMDP // reported an API version that we don't support yet. - (instancetype) initWithUserDefaults:(BGMUserDefaults*)defaults authRequiredHandler:(NSString* __nullable (^)(void))authHandler connectionErrorHandler:(void (^)(void))errorHandler apiVersionMismatchHandler:(void (^)(NSString* reportedAPIVersion))apiVersionHandler; // Returns before the connection has been fully established. The playing and paused properties will // remain false until the connection is complete, but playPause can be called at any time after // calling this method. // // If the connection fails, it will be retried after a one second delay, up to the number of times // given. - (void) connectWithRetries:(int)retries; - (void) disconnect; // Tell GPMDP to play if it's paused or pause if it's playing. - (void) playPause; @property (readonly) BOOL playing; @property (readonly) BOOL paused; @end #pragma clang assume_nonnull end
2,397
C++
.h
51
44.862745
99
0.75868
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,480
iTunes.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/iTunes.h
/* * iTunes.h * * Generated with * sdef /Applications/iTunes.app | sdp -fh --basename iTunes */ #import <AppKit/AppKit.h> #import <ScriptingBridge/ScriptingBridge.h> @class iTunesPrintSettings, iTunesApplication, iTunesItem, iTunesAirPlayDevice, iTunesArtwork, iTunesEncoder, iTunesEQPreset, iTunesPlaylist, iTunesAudioCDPlaylist, iTunesLibraryPlaylist, iTunesRadioTunerPlaylist, iTunesSource, iTunesTrack, iTunesAudioCDTrack, iTunesFileTrack, iTunesSharedTrack, iTunesURLTrack, iTunesUserPlaylist, iTunesFolderPlaylist, iTunesVisual, iTunesWindow, iTunesBrowserWindow, iTunesEQWindow, iTunesPlaylistWindow; enum iTunesEKnd { iTunesEKndTrackListing = 'kTrk' /* a basic listing of tracks within a playlist */, iTunesEKndAlbumListing = 'kAlb' /* a listing of a playlist grouped by album */, iTunesEKndCdInsert = 'kCDi' /* a printout of the playlist for jewel case inserts */ }; typedef enum iTunesEKnd iTunesEKnd; enum iTunesEnum { iTunesEnumStandard = 'lwst' /* Standard PostScript error handling */, iTunesEnumDetailed = 'lwdt' /* print a detailed report of PostScript errors */ }; typedef enum iTunesEnum iTunesEnum; enum iTunesEPlS { iTunesEPlSStopped = 'kPSS', iTunesEPlSPlaying = 'kPSP', iTunesEPlSPaused = 'kPSp', iTunesEPlSFastForwarding = 'kPSF', iTunesEPlSRewinding = 'kPSR' }; typedef enum iTunesEPlS iTunesEPlS; enum iTunesERpt { iTunesERptOff = 'kRpO', iTunesERptOne = 'kRp1', iTunesERptAll = 'kAll' }; typedef enum iTunesERpt iTunesERpt; enum iTunesEVSz { iTunesEVSzSmall = 'kVSS', iTunesEVSzMedium = 'kVSM', iTunesEVSzLarge = 'kVSL' }; typedef enum iTunesEVSz iTunesEVSz; enum iTunesESrc { iTunesESrcLibrary = 'kLib', iTunesESrcIPod = 'kPod', iTunesESrcAudioCD = 'kACD', iTunesESrcMP3CD = 'kMCD', iTunesESrcRadioTuner = 'kTun', iTunesESrcSharedLibrary = 'kShd', iTunesESrcUnknown = 'kUnk' }; typedef enum iTunesESrc iTunesESrc; enum iTunesESrA { iTunesESrAAlbums = 'kSrL' /* albums only */, iTunesESrAAll = 'kAll' /* all text fields */, iTunesESrAArtists = 'kSrR' /* artists only */, iTunesESrAComposers = 'kSrC' /* composers only */, iTunesESrADisplayed = 'kSrV' /* visible text fields */, iTunesESrASongs = 'kSrS' /* song names only */ }; typedef enum iTunesESrA iTunesESrA; enum iTunesESpK { iTunesESpKNone = 'kNon', iTunesESpKBooks = 'kSpA', iTunesESpKFolder = 'kSpF', iTunesESpKGenius = 'kSpG', iTunesESpKITunesU = 'kSpU', iTunesESpKLibrary = 'kSpL', iTunesESpKMovies = 'kSpI', iTunesESpKMusic = 'kSpZ', iTunesESpKPodcasts = 'kSpP', iTunesESpKPurchasedMusic = 'kSpM', iTunesESpKTVShows = 'kSpT' }; typedef enum iTunesESpK iTunesESpK; enum iTunesEVdK { iTunesEVdKNone = 'kNon' /* not a video or unknown video kind */, iTunesEVdKHomeVideo = 'kVdH' /* home video track */, iTunesEVdKMovie = 'kVdM' /* movie track */, iTunesEVdKMusicVideo = 'kVdV' /* music video track */, iTunesEVdKTVShow = 'kVdT' /* TV show track */ }; typedef enum iTunesEVdK iTunesEVdK; enum iTunesERtK { iTunesERtKUser = 'kRtU' /* user-specified rating */, iTunesERtKComputed = 'kRtC' /* iTunes-computed rating */ }; typedef enum iTunesERtK iTunesERtK; enum iTunesEAPD { iTunesEAPDComputer = 'kAPC', iTunesEAPDAirPortExpress = 'kAPX', iTunesEAPDAppleTV = 'kAPT', iTunesEAPDAirPlayDevice = 'kAPO', iTunesEAPDUnknown = 'kAPU' }; typedef enum iTunesEAPD iTunesEAPD; /* * Standard Suite */ @interface iTunesPrintSettings : SBObject @property (readonly) NSInteger copies; // the number of copies of a document to be printed @property (readonly) BOOL collating; // Should printed copies be collated? @property (readonly) NSInteger startingPage; // the first page of the document to be printed @property (readonly) NSInteger endingPage; // the last page of the document to be printed @property (readonly) NSInteger pagesAcross; // number of logical pages laid across a physical page @property (readonly) NSInteger pagesDown; // number of logical pages laid out down a physical page @property (readonly) iTunesEnum errorHandling; // how errors are handled @property (copy, readonly) NSDate *requestedPrintTime; // the time at which the desktop printer should print the document @property (copy, readonly) NSArray *printerFeatures; // printer specific options @property (copy, readonly) NSString *faxNumber; // for fax number @property (copy, readonly) NSString *targetPrinter; // for target printer - (void) printPrintDialog:(BOOL)printDialog withProperties:(iTunesPrintSettings *)withProperties kind:(iTunesEKnd)kind theme:(NSString *)theme; // Print the specified object(s) - (void) close; // Close an object - (void) delete; // Delete an element from an object - (SBObject *) duplicateTo:(SBObject *)to; // Duplicate one or more object(s) - (BOOL) exists; // Verify if an object exists - (void) open; // open the specified object(s) - (void) playOnce:(BOOL)once; // play the current track or the specified track or file. @end /* * iTunes Suite */ // The application program @interface iTunesApplication : SBApplication - (SBElementArray *) AirPlayDevices; - (SBElementArray *) browserWindows; - (SBElementArray *) encoders; - (SBElementArray *) EQPresets; - (SBElementArray *) EQWindows; - (SBElementArray *) playlistWindows; - (SBElementArray *) sources; - (SBElementArray *) visuals; - (SBElementArray *) windows; @property (readonly) BOOL AirPlayEnabled; // is AirPlay currently enabled? @property (readonly) BOOL converting; // is a track currently being converted? @property (copy) NSArray *currentAirPlayDevices; // the currently selected AirPlay device(s) @property (copy) iTunesEncoder *currentEncoder; // the currently selected encoder (MP3, AIFF, WAV, etc.) @property (copy) iTunesEQPreset *currentEQPreset; // the currently selected equalizer preset @property (copy, readonly) iTunesPlaylist *currentPlaylist; // the playlist containing the currently targeted track @property (copy, readonly) NSString *currentStreamTitle; // the name of the current song in the playing stream (provided by streaming server) @property (copy, readonly) NSString *currentStreamURL; // the URL of the playing stream or streaming web site (provided by streaming server) @property (copy, readonly) iTunesTrack *currentTrack; // the current targeted track @property (copy) iTunesVisual *currentVisual; // the currently selected visual plug-in @property BOOL EQEnabled; // is the equalizer enabled? @property BOOL fixedIndexing; // true if all AppleScript track indices should be independent of the play order of the owning playlist. @property BOOL frontmost; // is iTunes the frontmost application? @property BOOL fullScreen; // are visuals displayed using the entire screen? @property (copy, readonly) NSString *name; // the name of the application @property BOOL mute; // has the sound output been muted? @property double playerPosition; // the player’s position within the currently playing track in seconds. @property (readonly) iTunesEPlS playerState; // is iTunes stopped, paused, or playing? @property (copy, readonly) SBObject *selection; // the selection visible to the user @property NSInteger soundVolume; // the sound output volume (0 = minimum, 100 = maximum) @property (copy, readonly) NSString *version; // the version of iTunes @property BOOL visualsEnabled; // are visuals currently being displayed? @property iTunesEVSz visualSize; // the size of the displayed visual @property (copy, readonly) NSString *iAdIdentifier; // the iAd identifier - (void) printPrintDialog:(BOOL)printDialog withProperties:(iTunesPrintSettings *)withProperties kind:(iTunesEKnd)kind theme:(NSString *)theme; // Print the specified object(s) - (void) run; // run iTunes - (void) quit; // quit iTunes - (iTunesTrack *) add:(NSArray *)x to:(SBObject *)to; // add one or more files to a playlist - (void) backTrack; // reposition to beginning of current track or go to previous track if already at start of current track - (iTunesTrack *) convert:(NSArray *)x; // convert one or more files or tracks - (void) fastForward; // skip forward in a playing track - (void) nextTrack; // advance to the next track in the current playlist - (void) pause; // pause playback - (void) playOnce:(BOOL)once; // play the current track or the specified track or file. - (void) playpause; // toggle the playing/paused state of the current track - (void) previousTrack; // return to the previous track in the current playlist - (void) resume; // disable fast forward/rewind and resume playback, if playing. - (void) rewind; // skip backwards in a playing track - (void) stop; // stop playback - (void) update; // update the specified iPod - (void) eject; // eject the specified iPod - (void) subscribe:(NSString *)x; // subscribe to a podcast feed - (void) updateAllPodcasts; // update all subscribed podcast feeds - (void) updatePodcast; // update podcast feed - (void) openLocation:(NSString *)x; // Opens a Music Store or audio stream URL @end // an item @interface iTunesItem : SBObject @property (copy, readonly) SBObject *container; // the container of the item - (NSInteger) id; // the id of the item @property (readonly) NSInteger index; // The index of the item in internal application order. @property (copy) NSString *name; // the name of the item @property (copy, readonly) NSString *persistentID; // the id of the item as a hexadecimal string. This id does not change over time. @property (copy) NSDictionary *properties; // every property of the item - (void) printPrintDialog:(BOOL)printDialog withProperties:(iTunesPrintSettings *)withProperties kind:(iTunesEKnd)kind theme:(NSString *)theme; // Print the specified object(s) - (void) close; // Close an object - (void) delete; // Delete an element from an object - (SBObject *) duplicateTo:(SBObject *)to; // Duplicate one or more object(s) - (BOOL) exists; // Verify if an object exists - (void) open; // open the specified object(s) - (void) playOnce:(BOOL)once; // play the current track or the specified track or file. - (void) reveal; // reveal and select a track or playlist @end // an AirPlay device @interface iTunesAirPlayDevice : iTunesItem @property (readonly) BOOL active; // is the device currently being played to? @property (readonly) BOOL available; // is the device currently available? @property (readonly) iTunesEAPD kind; // the kind of the device @property (copy, readonly) NSString *networkAddress; // the network (MAC) address of the device - (BOOL) protected; // is the device password- or passcode-protected? @property BOOL selected; // is the device currently selected? @property (readonly) BOOL supportsAudio; // does the device support audio playback? @property (readonly) BOOL supportsVideo; // does the device support video playback? @property NSInteger soundVolume; // the output volume for the device (0 = minimum, 100 = maximum) @end // a piece of art within a track @interface iTunesArtwork : iTunesItem @property (copy) NSImage *data; // data for this artwork, in the form of a picture @property (copy) NSString *objectDescription; // description of artwork as a string @property (readonly) BOOL downloaded; // was this artwork downloaded by iTunes? @property (copy, readonly) NSNumber *format; // the data format for this piece of artwork @property NSInteger kind; // kind or purpose of this piece of artwork @property (copy) NSData *rawData; // data for this artwork, in original format @end // converts a track to a specific file format @interface iTunesEncoder : iTunesItem @property (copy, readonly) NSString *format; // the data format created by the encoder @end // equalizer preset configuration @interface iTunesEQPreset : iTunesItem @property double band1; // the equalizer 32 Hz band level (-12.0 dB to +12.0 dB) @property double band2; // the equalizer 64 Hz band level (-12.0 dB to +12.0 dB) @property double band3; // the equalizer 125 Hz band level (-12.0 dB to +12.0 dB) @property double band4; // the equalizer 250 Hz band level (-12.0 dB to +12.0 dB) @property double band5; // the equalizer 500 Hz band level (-12.0 dB to +12.0 dB) @property double band6; // the equalizer 1 kHz band level (-12.0 dB to +12.0 dB) @property double band7; // the equalizer 2 kHz band level (-12.0 dB to +12.0 dB) @property double band8; // the equalizer 4 kHz band level (-12.0 dB to +12.0 dB) @property double band9; // the equalizer 8 kHz band level (-12.0 dB to +12.0 dB) @property double band10; // the equalizer 16 kHz band level (-12.0 dB to +12.0 dB) @property (readonly) BOOL modifiable; // can this preset be modified? @property double preamp; // the equalizer preamp level (-12.0 dB to +12.0 dB) @property BOOL updateTracks; // should tracks which refer to this preset be updated when the preset is renamed or deleted? @end // a list of songs/streams @interface iTunesPlaylist : iTunesItem - (SBElementArray *) tracks; @property (readonly) NSInteger duration; // the total length of all songs (in seconds) @property (copy) NSString *name; // the name of the playlist @property BOOL loved; // is this plalist loved? @property (copy, readonly) iTunesPlaylist *parent; // folder which contains this playlist (if any) @property BOOL shuffle; // play the songs in this playlist in random order? @property (readonly) NSInteger size; // the total size of all songs (in bytes) @property iTunesERpt songRepeat; // playback repeat mode @property (readonly) iTunesESpK specialKind; // special playlist kind @property (copy, readonly) NSString *time; // the length of all songs in MM:SS format @property (readonly) BOOL visible; // is this playlist visible in the Source list? - (void) moveTo:(SBObject *)to; // Move playlist(s) to a new location - (iTunesTrack *) searchFor:(NSString *)for_ only:(iTunesESrA)only; // search a playlist for tracks matching the search string. Identical to entering search text in the Search field in iTunes. @end // a playlist representing an audio CD @interface iTunesAudioCDPlaylist : iTunesPlaylist - (SBElementArray *) audioCDTracks; @property (copy) NSString *artist; // the artist of the CD @property BOOL compilation; // is this CD a compilation album? @property (copy) NSString *composer; // the composer of the CD @property NSInteger discCount; // the total number of discs in this CD’s album @property NSInteger discNumber; // the index of this CD disc in the source album @property (copy) NSString *genre; // the genre of the CD @property NSInteger year; // the year the album was recorded/released @end // the master music library playlist @interface iTunesLibraryPlaylist : iTunesPlaylist - (SBElementArray *) fileTracks; - (SBElementArray *) URLTracks; - (SBElementArray *) sharedTracks; @end // the radio tuner playlist @interface iTunesRadioTunerPlaylist : iTunesPlaylist - (SBElementArray *) URLTracks; @end // a music source (music library, CD, device, etc.) @interface iTunesSource : iTunesItem - (SBElementArray *) audioCDPlaylists; - (SBElementArray *) libraryPlaylists; - (SBElementArray *) playlists; - (SBElementArray *) radioTunerPlaylists; - (SBElementArray *) userPlaylists; @property (readonly) long long capacity; // the total size of the source if it has a fixed size @property (readonly) long long freeSpace; // the free space on the source if it has a fixed size @property (readonly) iTunesESrc kind; - (void) update; // update the specified iPod - (void) eject; // eject the specified iPod @end // playable audio source @interface iTunesTrack : iTunesItem - (SBElementArray *) artworks; @property (copy) NSString *album; // the album name of the track @property (copy) NSString *albumArtist; // the album artist of the track @property BOOL albumLoved; // is the album for this track loved? @property NSInteger albumRating; // the rating of the album for this track (0 to 100) @property (readonly) iTunesERtK albumRatingKind; // the rating kind of the album rating for this track @property (copy) NSString *artist; // the artist/source of the track @property (readonly) NSInteger bitRate; // the bit rate of the track (in kbps) @property double bookmark; // the bookmark time of the track in seconds @property BOOL bookmarkable; // is the playback position for this track remembered? @property NSInteger bpm; // the tempo of this track in beats per minute @property (copy) NSString *category; // the category of the track @property (copy) NSString *comment; // freeform notes about the track @property BOOL compilation; // is this track from a compilation album? @property (copy) NSString *composer; // the composer of the track @property (readonly) NSInteger databaseID; // the common, unique ID for this track. If two tracks in different playlists have the same database ID, they are sharing the same data. @property (copy, readonly) NSDate *dateAdded; // the date the track was added to the playlist @property (copy) NSString *objectDescription; // the description of the track @property NSInteger discCount; // the total number of discs in the source album @property NSInteger discNumber; // the index of the disc containing this track on the source album @property (readonly) double duration; // the length of the track in seconds @property BOOL enabled; // is this track checked for playback? @property (copy) NSString *episodeID; // the episode ID of the track @property NSInteger episodeNumber; // the episode number of the track @property (copy) NSString *EQ; // the name of the EQ preset of the track @property double finish; // the stop time of the track in seconds @property BOOL gapless; // is this track from a gapless album? @property (copy) NSString *genre; // the music/audio genre (category) of the track @property (copy) NSString *grouping; // the grouping (piece) of the track. Generally used to denote movements within a classical work. @property (readonly) BOOL iTunesU; // is this track an iTunes U episode? @property (copy, readonly) NSString *kind; // a text description of the track @property (copy) NSString *longDescription; @property BOOL loved; // is this track loved? @property (copy) NSString *lyrics; // the lyrics of the track @property (copy, readonly) NSDate *modificationDate; // the modification date of the content of this track @property NSInteger playedCount; // number of times this track has been played @property (copy) NSDate *playedDate; // the date and time this track was last played @property (readonly) BOOL podcast; // is this track a podcast episode? @property NSInteger rating; // the rating of this track (0 to 100) @property (readonly) iTunesERtK ratingKind; // the rating kind of this track @property (copy, readonly) NSDate *releaseDate; // the release date of this track @property (readonly) NSInteger sampleRate; // the sample rate of the track (in Hz) @property NSInteger seasonNumber; // the season number of the track @property BOOL shufflable; // is this track included when shuffling? @property NSInteger skippedCount; // number of times this track has been skipped @property (copy) NSDate *skippedDate; // the date and time this track was last skipped @property (copy) NSString *show; // the show name of the track @property (copy) NSString *sortAlbum; // override string to use for the track when sorting by album @property (copy) NSString *sortArtist; // override string to use for the track when sorting by artist @property (copy) NSString *sortAlbumArtist; // override string to use for the track when sorting by album artist @property (copy) NSString *sortName; // override string to use for the track when sorting by name @property (copy) NSString *sortComposer; // override string to use for the track when sorting by composer @property (copy) NSString *sortShow; // override string to use for the track when sorting by show name @property (readonly) long long size; // the size of the track (in bytes) @property double start; // the start time of the track in seconds @property (copy, readonly) NSString *time; // the length of the track in MM:SS format @property NSInteger trackCount; // the total number of tracks on the source album @property NSInteger trackNumber; // the index of the track on the source album @property BOOL unplayed; // is this track unplayed? @property iTunesEVdK videoKind; // kind of video track @property NSInteger volumeAdjustment; // relative volume adjustment of the track (-100% to 100%) @property NSInteger year; // the year the track was recorded/released @end // a track on an audio CD @interface iTunesAudioCDTrack : iTunesTrack @property (copy, readonly) NSURL *location; // the location of the file represented by this track @end // a track representing an audio file (MP3, AIFF, etc.) @interface iTunesFileTrack : iTunesTrack @property (copy) NSURL *location; // the location of the file represented by this track - (void) refresh; // update file track information from the current information in the track’s file @end // a track residing in a shared library @interface iTunesSharedTrack : iTunesTrack @end // a track representing a network stream @interface iTunesURLTrack : iTunesTrack @property (copy) NSString *address; // the URL for this track - (void) download; // download podcast episode @end // custom playlists created by the user @interface iTunesUserPlaylist : iTunesPlaylist - (SBElementArray *) fileTracks; - (SBElementArray *) URLTracks; - (SBElementArray *) sharedTracks; @property BOOL shared; // is this playlist shared? @property (readonly) BOOL smart; // is this a Smart Playlist? @end // a folder that contains other playlists @interface iTunesFolderPlaylist : iTunesUserPlaylist @end // a visual plug-in @interface iTunesVisual : iTunesItem @end // any window @interface iTunesWindow : iTunesItem @property NSRect bounds; // the boundary rectangle for the window @property (readonly) BOOL closeable; // does the window have a close box? @property (readonly) BOOL collapseable; // does the window have a collapse (windowshade) box? @property BOOL collapsed; // is the window collapsed? @property NSPoint position; // the upper left position of the window @property (readonly) BOOL resizable; // is the window resizable? @property BOOL visible; // is the window visible? @property (readonly) BOOL zoomable; // is the window zoomable? @property BOOL zoomed; // is the window zoomed? @end // the main iTunes window @interface iTunesBrowserWindow : iTunesWindow @property BOOL minimized; // is the small player visible? @property (copy, readonly) SBObject *selection; // the selected songs @property (copy) iTunesPlaylist *view; // the playlist currently displayed in the window @end // the iTunes equalizer window @interface iTunesEQWindow : iTunesWindow @property BOOL minimized; // is the small EQ window visible? @end // a sub-window showing a single playlist @interface iTunesPlaylistWindow : iTunesWindow @property (copy, readonly) SBObject *selection; // the selected songs @property (copy, readonly) iTunesPlaylist *view; // the playlist displayed in the window @end
23,110
C++
.h
408
55.183824
441
0.763466
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
true
false
false
false
false
false
false
4,481
BGMHermes.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/BGMHermes.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMHermes.h // BGMApp // // Copyright © 2016 Kyle Neideck // // Superclass/Protocol Import #import "BGMMusicPlayer.h" @interface BGMHermes : BGMMusicPlayerBase<BGMMusicPlayer> @end
898
C++
.h
24
36.166667
75
0.769585
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,482
BGMSwinsian.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Music Players/BGMSwinsian.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMSwinsian.h // BGMApp // // Copyright © 2018 Kyle Neideck // // Superclass/Protocol Import #import "BGMMusicPlayer.h" #pragma clang assume_nonnull begin @interface BGMSwinsian : BGMMusicPlayerBase<BGMMusicPlayer> @end #pragma clang assume_nonnull end
972
C++
.h
26
36.076923
75
0.776119
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,483
BGMPreferencesMenu.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Preferences/BGMPreferencesMenu.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMPreferencesMenu.h // BGMApp // // Copyright © 2016, 2018, 2019 Kyle Neideck // // Handles the preferences menu UI. The user's preference changes are often passed directly to the driver rather // than to other BGMApp classes. // // Local Includes #import "BGMAudioDeviceManager.h" #import "BGMMusicPlayers.h" #import "BGMStatusBarItem.h" // System Includes #import <Cocoa/Cocoa.h> NS_ASSUME_NONNULL_BEGIN @interface BGMPreferencesMenu : NSObject - (id) initWithBGMMenu:(NSMenu*)inBGMMenu audioDevices:(BGMAudioDeviceManager*)inAudioDevices musicPlayers:(BGMMusicPlayers*)inMusicPlayers statusBarItem:(BGMStatusBarItem*)inStatusBarItem aboutPanel:(NSPanel*)inAboutPanel aboutPanelLicenseView:(NSTextView*)inAboutPanelLicenseView; @end NS_ASSUME_NONNULL_END
1,523
C++
.h
39
36.717949
113
0.774763
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,484
BGMAutoPauseMusicPrefs.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Preferences/BGMAutoPauseMusicPrefs.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMAutoPauseMusicPrefs.h // BGMApp // // Copyright © 2016 Kyle Neideck // // Local Includes #import "BGMAudioDeviceManager.h" #import "BGMMusicPlayers.h" // System Includes #import <Cocoa/Cocoa.h> #pragma clang assume_nonnull begin @interface BGMAutoPauseMusicPrefs : NSObject - (id) initWithPreferencesMenu:(NSMenu*)inPrefsMenu audioDevices:(BGMAudioDeviceManager*)inAudioDevices musicPlayers:(BGMMusicPlayers*)inMusicPlayers; @end #pragma clang assume_nonnull end
1,224
C++
.h
32
35.78125
75
0.765651
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,485
BGMAboutPanel.h
kyleneideck_BackgroundMusic/BGMApp/BGMApp/Preferences/BGMAboutPanel.h
// This file is part of Background Music. // // Background Music is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 2 of the // License, or (at your option) any later version. // // Background Music is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Background Music. If not, see <http://www.gnu.org/licenses/>. // // BGMAboutPanel.h // BGMApp // // Copyright © 2016 Kyle Neideck // // This class manages the "About Background Music" window. // // System Includes #import <Cocoa/Cocoa.h> NS_ASSUME_NONNULL_BEGIN @interface BGMAboutPanel : NSObject - (instancetype)initWithPanel:(NSPanel*)inAboutPanel licenseView:(NSTextView*)inLicenseView; - (void) show; @end @interface BGMLinkField : NSTextField @end NS_ASSUME_NONNULL_END
1,131
C++
.h
32
34
92
0.773897
kyleneideck/BackgroundMusic
15,929
676
482
GPL-2.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,486
CutterApplication.cpp
rizinorg_cutter/src/CutterApplication.cpp
#include "common/PythonManager.h" #include "CutterApplication.h" #include "plugins/PluginManager.h" #include "CutterConfig.h" #include "common/Decompiler.h" #include "common/ResourcePaths.h" #include <QApplication> #include <QFileOpenEvent> #include <QEvent> #include <QMenu> #include <QMessageBox> #include <QCommandLineParser> #include <QTextCodec> #include <QStringList> #include <QProcess> #include <QPluginLoader> #include <QDir> #include <QTranslator> #include <QLibraryInfo> #include <QFontDatabase> #ifdef Q_OS_WIN # include <QtNetwork/QtNetwork> #endif // Q_OS_WIN #include <cstdlib> #if CUTTER_RZGHIDRA_STATIC # include <RzGhidraDecompiler.h> #endif // Rizin before 301e5af2170d9f3ed1edd658b0f9633f31fc4126 // has RZ_GITTAP defined and uses it in rz_core_version(). // After that, RZ_GITTAP is not defined anymore and RZ_VERSION is used. #ifdef RZ_GITTAP # define CUTTER_COMPILE_TIME_RZ_VERSION "" RZ_GITTAP #else # define CUTTER_COMPILE_TIME_RZ_VERSION "" RZ_VERSION #endif CutterApplication::CutterApplication(int &argc, char **argv) : QApplication(argc, argv) { // Setup application information setApplicationVersion(CUTTER_VERSION_FULL); #ifdef Q_OS_MACOS setWindowIcon(QIcon(":/img/cutter_macos_simple.svg")); #else setWindowIcon(QIcon(":/img/cutter.svg")); #endif #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0) setAttribute(Qt::AA_UseHighDpiPixmaps); // always enabled on Qt >= 6.0.0 #endif setLayoutDirection(Qt::LeftToRight); // WARN!!! Put initialization code below this line. Code above this line is mandatory to be run // First #ifdef Q_OS_WIN // Hack to force Cutter load internet connection related DLL's QSslSocket s; s.sslConfiguration(); #endif // Q_OS_WIN // Load translations if (!loadTranslations()) { qWarning() << "Cannot load translations"; } // Load fonts int ret = QFontDatabase::addApplicationFont(":/fonts/Anonymous Pro.ttf"); if (ret == -1) { qWarning() << "Cannot load Anonymous Pro font."; } ret = QFontDatabase::addApplicationFont(":/fonts/Inconsolata-Regular.ttf"); if (ret == -1) { qWarning() << "Cannot load Incosolata-Regular font."; } // Set QString codec to UTF-8 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8")); #if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8")); QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF-8")); #endif if (!parseCommandLineOptions()) { std::exit(1); } // Check rizin version QString rzversion = rz_core_version(); QString localVersion = CUTTER_COMPILE_TIME_RZ_VERSION; qDebug() << rzversion << localVersion; if (rzversion != localVersion) { QMessageBox msg; msg.setIcon(QMessageBox::Critical); msg.setStandardButtons(QMessageBox::Yes | QMessageBox::No); msg.setWindowTitle(QObject::tr("Version mismatch!")); msg.setText(QString(QObject::tr("The version used to compile Cutter (%1) does not match " "the binary version of rizin (%2). This could result in " "unexpected behaviour. Are you sure you want to continue?")) .arg(localVersion, rzversion)); if (msg.exec() == QMessageBox::No) { std::exit(1); } } #ifdef CUTTER_ENABLE_PYTHON // Init python if (!clOptions.pythonHome.isEmpty()) { Python()->setPythonHome(clOptions.pythonHome); } Python()->initialize(); #endif Core()->initialize(clOptions.enableRizinPlugins); Core()->setSettings(); Config()->loadInitial(); Core()->loadCutterRC(); Config()->setOutputRedirectionEnabled(clOptions.outputRedirectionEnabled); #if CUTTER_RZGHIDRA_STATIC Core()->registerDecompiler(new RzGhidraDecompiler(Core())); #endif Plugins()->loadPlugins(clOptions.enableCutterPlugins); for (auto &plugin : Plugins()->getPlugins()) { plugin->registerDecompilers(); } mainWindow = new MainWindow(); installEventFilter(mainWindow); // set up context menu shortcut display fix #if QT_VERSION_CHECK(5, 10, 0) < QT_VERSION setStyle(new CutterProxyStyle()); #endif // QT_VERSION_CHECK(5, 10, 0) < QT_VERSION if (clOptions.args.empty() && clOptions.fileOpenOptions.projectFile.isEmpty()) { // check if this is the first execution of Cutter in this computer // Note: the execution after the preferences been reset, will be considered as // first-execution if (Config()->isFirstExecution()) { mainWindow->displayWelcomeDialog(); } mainWindow->displayNewFileDialog(); } else { // filename specified as positional argument bool askOptions = (clOptions.analysisLevel != AutomaticAnalysisLevel::Ask) || !clOptions.fileOpenOptions.projectFile.isEmpty(); mainWindow->openNewFile(clOptions.fileOpenOptions, askOptions); } #ifdef APPIMAGE { auto appdir = QDir(QCoreApplication::applicationDirPath()); // appdir/bin appdir.cdUp(); // appdir auto sleighHome = appdir; // appdir/lib/rizin/plugins/rz_ghidra_sleigh/ sleighHome.cd("lib/rizin/plugins/rz_ghidra_sleigh/"); Core()->setConfig("ghidra.sleighhome", sleighHome.absolutePath()); } #endif #if defined(Q_OS_MACOS) && defined(CUTTER_ENABLE_PACKAGING) { auto rzprefix = QDir(QCoreApplication::applicationDirPath()); // Contents/MacOS rzprefix.cdUp(); // Contents rzprefix.cd("Resources"); // Contents/Resources/ auto sleighHome = rzprefix; // Contents/Resources/lib/rizin/plugins/rz_ghidra_sleigh sleighHome.cd("lib/rizin/plugins/rz_ghidra_sleigh"); Core()->setConfig("ghidra.sleighhome", sleighHome.absolutePath()); } #endif #if defined(Q_OS_WIN) && defined(CUTTER_ENABLE_PACKAGING) { auto sleighHome = QDir(QCoreApplication::applicationDirPath()); sleighHome.cd("lib/rizin/plugins/rz_ghidra_sleigh"); Core()->setConfig("ghidra.sleighhome", sleighHome.absolutePath()); } #endif } CutterApplication::~CutterApplication() { Plugins()->destroyPlugins(); delete mainWindow; #ifdef CUTTER_ENABLE_PYTHON Python()->shutdown(); #endif } void CutterApplication::launchNewInstance(const QStringList &args) { QProcess process(this); process.setEnvironment(QProcess::systemEnvironment()); QStringList allArgs; if (!clOptions.enableCutterPlugins) { allArgs.push_back("--no-cutter-plugins"); } if (!clOptions.enableRizinPlugins) { allArgs.push_back("--no-rizin-plugins"); } allArgs.append(args); process.startDetached(qApp->applicationFilePath(), allArgs); } bool CutterApplication::event(QEvent *e) { if (e->type() == QEvent::FileOpen) { QFileOpenEvent *openEvent = static_cast<QFileOpenEvent *>(e); if (openEvent) { if (m_FileAlreadyDropped) { // We already dropped a file in macOS, let's spawn another instance // (Like the File -> Open) QString fileName = openEvent->file(); launchNewInstance({ fileName }); } else { QString fileName = openEvent->file(); m_FileAlreadyDropped = true; mainWindow->closeNewFileDialog(); InitialOptions options; options.filename = fileName; mainWindow->openNewFile(options); } } } return QApplication::event(e); } bool CutterApplication::loadTranslations() { const QString &language = Config()->getCurrLocale().bcp47Name(); if (language == QStringLiteral("en") || language.startsWith(QStringLiteral("en-"))) { return true; } const auto &allLocales = QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript, QLocale::AnyCountry); bool cutterTrLoaded = false; for (const QLocale &it : allLocales) { const QString &langPrefix = it.bcp47Name(); if (langPrefix == language) { QApplication::setLayoutDirection(it.textDirection()); QLocale::setDefault(it); QTranslator *trCutter = new QTranslator; QTranslator *trQtBase = new QTranslator; QTranslator *trQt = new QTranslator; const QStringList &cutterTrPaths = Cutter::getTranslationsDirectories(); for (const auto &trPath : cutterTrPaths) { if (trCutter && trCutter->load(it, QLatin1String("cutter"), QLatin1String("_"), trPath)) { installTranslator(trCutter); cutterTrLoaded = true; trCutter = nullptr; } if (trQt && trQt->load(it, "qt", "_", trPath)) { installTranslator(trQt); trQt = nullptr; } if (trQtBase && trQtBase->load(it, "qtbase", "_", trPath)) { installTranslator(trQtBase); trQtBase = nullptr; } } if (trCutter) { delete trCutter; } if (trQt) { delete trQt; } if (trQtBase) { delete trQtBase; } return true; } } if (!cutterTrLoaded) { qWarning() << "Cannot load Cutter's translation for " << language; } return false; } QStringList CutterApplication::getArgs() const { auto &options = clOptions.fileOpenOptions; QStringList args; switch (clOptions.analysisLevel) { case AutomaticAnalysisLevel::None: args.push_back("-A"); args.push_back("0"); break; case AutomaticAnalysisLevel::AAA: args.push_back("-A"); args.push_back("1"); break; case AutomaticAnalysisLevel::AAAA: args.push_back("-A"); args.push_back("2"); break; default: break; } if (!options.useVA) { args.push_back("-P"); } if (options.writeEnabled) { args.push_back("-w"); } if (!options.script.isEmpty()) { args.push_back("-i"); args.push_back(options.script); } if (!options.projectFile.isEmpty()) { args.push_back("-p"); args.push_back(options.projectFile); } if (!options.arch.isEmpty()) { args.push_back("-a"); args.push_back(options.arch); } if (options.bits > 0) { args.push_back("-b"); args.push_back(QString::asprintf("%d", options.bits)); } if (!options.cpu.isEmpty()) { args.push_back("-c"); args.push_back(options.cpu); } if (!options.os.isEmpty()) { args.push_back("-o"); args.push_back(options.os); } switch (options.endian) { case InitialOptions::Endianness::Little: args.push_back("-e"); args.push_back("little"); break; case InitialOptions::Endianness::Big: args.push_back("-e"); args.push_back("big"); break; default: break; } if (!options.forceBinPlugin.isEmpty()) { args.push_back("-F"); args.push_back(options.forceBinPlugin); } if (options.binLoadAddr != RVA_INVALID) { args.push_back("-B"); args.push_back(RzAddressString(options.binLoadAddr)); } if (options.mapAddr != RVA_INVALID) { args.push_back("-m"); args.push_back(RzAddressString(options.mapAddr)); } if (!options.filename.isEmpty()) { args.push_back(options.filename); } return args; } bool CutterApplication::parseCommandLineOptions() { // Keep this function in sync with documentation QCommandLineParser cmd_parser; cmd_parser.setApplicationDescription( QObject::tr("A Qt and C++ GUI for rizin reverse engineering framework")); cmd_parser.addHelpOption(); cmd_parser.addVersionOption(); cmd_parser.addPositionalArgument("filename", QObject::tr("Filename to open.")); QCommandLineOption analOption( { "A", "analysis" }, QObject::tr("Automatically open file and optionally start analysis. " "Needs filename to be specified. May be a value between 0 and 2:" " 0 = no analysis, 1 = aaa, 2 = aaaa (experimental)"), QObject::tr("level")); cmd_parser.addOption(analOption); QCommandLineOption archOption({ "a", "arch" }, QObject::tr("Sets a specific architecture name"), QObject::tr("arch")); cmd_parser.addOption(archOption); QCommandLineOption bitsOption({ "b", "bits" }, QObject::tr("Sets a specific architecture bits"), QObject::tr("bits")); cmd_parser.addOption(bitsOption); QCommandLineOption cpuOption({ "c", "cpu" }, QObject::tr("Sets a specific CPU"), QObject::tr("cpu")); cmd_parser.addOption(cpuOption); QCommandLineOption osOption({ "o", "os" }, QObject::tr("Sets a specific operating system"), QObject::tr("os")); cmd_parser.addOption(osOption); QCommandLineOption endianOption({ "e", "endian" }, QObject::tr("Sets the endianness (big or little)"), QObject::tr("big|little")); cmd_parser.addOption(endianOption); QCommandLineOption formatOption({ "F", "format" }, QObject::tr("Force using a specific file format (bin plugin)"), QObject::tr("name")); cmd_parser.addOption(formatOption); QCommandLineOption baddrOption({ "B", "base" }, QObject::tr("Load binary at a specific base address"), QObject::tr("base address")); cmd_parser.addOption(baddrOption); QCommandLineOption maddrOption({ "m", "map" }, QObject::tr("Map the binary at a specific address"), QObject::tr("map address")); cmd_parser.addOption(maddrOption); QCommandLineOption scriptOption("i", QObject::tr("Run script file"), QObject::tr("file")); cmd_parser.addOption(scriptOption); QCommandLineOption projectOption({ "p", "project" }, QObject::tr("Load project file"), QObject::tr("project file")); cmd_parser.addOption(projectOption); QCommandLineOption writeModeOption({ "w", "writemode" }, QObject::tr("Open file in write mode")); cmd_parser.addOption(writeModeOption); QCommandLineOption phyModeOption({ "P", "phymode" }, QObject::tr("Disables virtual addressing")); cmd_parser.addOption(phyModeOption); QCommandLineOption pythonHomeOption( "pythonhome", QObject::tr("PYTHONHOME to use for embedded python interpreter"), "PYTHONHOME"); cmd_parser.addOption(pythonHomeOption); QCommandLineOption disableRedirectOption( "no-output-redirect", QObject::tr("Disable output redirection." " Some of the output in console widget will not be visible." " Use this option when debuging a crash or freeze and output " " redirection is causing some messages to be lost.")); cmd_parser.addOption(disableRedirectOption); QCommandLineOption disablePlugins("no-plugins", QObject::tr("Do not load plugins")); cmd_parser.addOption(disablePlugins); QCommandLineOption disableCutterPlugins("no-cutter-plugins", QObject::tr("Do not load Cutter plugins")); cmd_parser.addOption(disableCutterPlugins); QCommandLineOption disableRizinPlugins("no-rizin-plugins", QObject::tr("Do not load rizin plugins")); cmd_parser.addOption(disableRizinPlugins); cmd_parser.process(*this); CutterCommandLineOptions opts; opts.args = cmd_parser.positionalArguments(); if (cmd_parser.isSet(analOption)) { bool analysisLevelSpecified = false; int analysisLevel = cmd_parser.value(analOption).toInt(&analysisLevelSpecified); if (!analysisLevelSpecified || analysisLevel < 0 || analysisLevel > 2) { fprintf(stderr, "%s\n", QObject::tr("Invalid Analysis Level. May be a value between 0 and 2.") .toLocal8Bit() .constData()); return false; } switch (analysisLevel) { case 0: opts.analysisLevel = AutomaticAnalysisLevel::None; break; case 1: opts.analysisLevel = AutomaticAnalysisLevel::AAA; break; case 2: opts.analysisLevel = AutomaticAnalysisLevel::AAAA; break; } } if (opts.args.empty() && opts.analysisLevel != AutomaticAnalysisLevel::Ask) { fprintf(stderr, "%s\n", QObject::tr("Filename must be specified to start analysis automatically.") .toLocal8Bit() .constData()); return false; } if (!opts.args.isEmpty()) { opts.fileOpenOptions.filename = opts.args[0]; opts.fileOpenOptions.forceBinPlugin = cmd_parser.value(formatOption); if (cmd_parser.isSet(baddrOption)) { bool ok = false; RVA baddr = cmd_parser.value(baddrOption).toULongLong(&ok, 0); if (ok) { opts.fileOpenOptions.binLoadAddr = baddr; } } if (cmd_parser.isSet(maddrOption)) { bool ok = false; RVA maddr = cmd_parser.value(maddrOption).toULongLong(&ok, 0); if (ok) { opts.fileOpenOptions.mapAddr = maddr; } } switch (opts.analysisLevel) { case AutomaticAnalysisLevel::Ask: break; case AutomaticAnalysisLevel::None: opts.fileOpenOptions.analysisCmd = {}; break; case AutomaticAnalysisLevel::AAA: opts.fileOpenOptions.analysisCmd = { { "aaa", "Auto analysis" } }; break; case AutomaticAnalysisLevel::AAAA: opts.fileOpenOptions.analysisCmd = { { "aaaa", "Auto analysis (experimental)" } }; break; } opts.fileOpenOptions.script = cmd_parser.value(scriptOption); opts.fileOpenOptions.arch = cmd_parser.value(archOption); opts.fileOpenOptions.cpu = cmd_parser.value(cpuOption); opts.fileOpenOptions.os = cmd_parser.value(osOption); if (cmd_parser.isSet(bitsOption)) { bool ok = false; int bits = cmd_parser.value(bitsOption).toInt(&ok, 10); if (ok && bits > 0) { opts.fileOpenOptions.bits = bits; } } if (cmd_parser.isSet(endianOption)) { QString endian = cmd_parser.value(endianOption).toLower(); opts.fileOpenOptions.endian = InitialOptions::Endianness::Auto; if (endian == "little") { opts.fileOpenOptions.endian = InitialOptions::Endianness::Little; } else if (endian == "big") { opts.fileOpenOptions.endian = InitialOptions::Endianness::Big; } else { fprintf(stderr, "%s\n", QObject::tr("Invalid Endianness. You can only set it to `big` or `little`.") .toLocal8Bit() .constData()); return false; } } else { opts.fileOpenOptions.endian = InitialOptions::Endianness::Auto; } opts.fileOpenOptions.writeEnabled = cmd_parser.isSet(writeModeOption); opts.fileOpenOptions.useVA = !cmd_parser.isSet(phyModeOption); } opts.fileOpenOptions.projectFile = cmd_parser.value(projectOption); if (cmd_parser.isSet(pythonHomeOption)) { opts.pythonHome = cmd_parser.value(pythonHomeOption); } opts.outputRedirectionEnabled = !cmd_parser.isSet(disableRedirectOption); if (cmd_parser.isSet(disablePlugins)) { opts.enableCutterPlugins = false; opts.enableRizinPlugins = false; } if (cmd_parser.isSet(disableCutterPlugins)) { opts.enableCutterPlugins = false; } if (cmd_parser.isSet(disableRizinPlugins)) { opts.enableRizinPlugins = false; } this->clOptions = opts; return true; } void CutterProxyStyle::polish(QWidget *widget) { QProxyStyle::polish(widget); #if QT_VERSION_CHECK(5, 10, 0) < QT_VERSION // HACK: This is the only way I've found to force Qt (5.10 and newer) to // display shortcuts in context menus on all platforms. It's ugly, // but it gets the job done. if (auto menu = qobject_cast<QMenu *>(widget)) { const auto &actions = menu->actions(); for (auto action : actions) { action->setShortcutVisibleInContextMenu(true); } } #endif // QT_VERSION_CHECK(5, 10, 0) < QT_VERSION }
21,417
C++
.cpp
535
31.016822
100
0.614505
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,487
Main.cpp
rizinorg_cutter/src/Main.cpp
#include "CutterApplication.h" #include "core/MainWindow.h" #include "common/UpdateWorker.h" #include "CutterConfig.h" #include "common/SettingsUpgrade.h" #include <QJsonObject> #include <QJsonArray> #include <iostream> /** * @brief Attempt to connect to a parent console and configure outputs. */ #ifdef Q_OS_WIN # include <windows.h> static void connectToConsole() { BOOL attached = AttachConsole(ATTACH_PARENT_PROCESS); // Avoid reconfiguring stdin/stderr/stdout if one of them is already connected to a stream. // This can happen when running with stdout/stderr redirected to a file. if (0 > fileno(stdin)) { // Overwrite FD 0, FD 1 and 2 for the benefit of any code that uses the FDs // directly. This is safe because the CRT allocates FDs 0, 1 and // 2 at startup even if they don't have valid underlying Windows // handles. This means we won't be overwriting an FD created by // _open() after startup. _close(0); freopen(attached ? "CONIN$" : "NUL", "r+", stdin); } if (0 > fileno(stdout)) { _close(1); if (freopen(attached ? "CONOUT$" : "NUL", "a+", stdout)) { // Avoid buffering stdout/stderr since IOLBF is replaced by IOFBF in Win32. setvbuf(stdout, nullptr, _IONBF, 0); } } if (0 > fileno(stderr)) { _close(2); if (freopen(attached ? "CONOUT$" : "NUL", "a+", stderr)) { setvbuf(stderr, nullptr, _IONBF, 0); } } // Fix all cout, wcout, cin, wcin, cerr, wcerr, clog and wclog. std::ios::sync_with_stdio(); } #endif int main(int argc, char *argv[]) { #ifdef Q_OS_WIN connectToConsole(); #endif qRegisterMetaType<QList<StringDescription>>(); qRegisterMetaType<QList<FunctionDescription>>(); QCoreApplication::setOrganizationName("rizin"); #ifndef Q_OS_MACOS // don't set on macOS so that it doesn't affect config path there QCoreApplication::setOrganizationDomain("rizin.re"); #endif QCoreApplication::setApplicationName("cutter"); // Importing settings after setting rename, needs separate handling in addition to regular // version to version upgrade. if (Cutter::shouldOfferSettingImport()) { Cutter::showSettingImportDialog(argc, argv); } Cutter::initializeSettings(); QCoreApplication::setAttribute( Qt::AA_ShareOpenGLContexts); // needed for QtWebEngine inside Plugins #ifdef Q_OS_WIN QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); # if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) QGuiApplication::setHighDpiScaleFactorRoundingPolicy( Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); # endif #endif CutterApplication a(argc, argv); Cutter::migrateThemes(); if (Config()->getAutoUpdateEnabled()) { #if CUTTER_UPDATE_WORKER_AVAILABLE UpdateWorker *updateWorker = new UpdateWorker; QObject::connect(updateWorker, &UpdateWorker::checkComplete, [=](const QVersionNumber &version, const QString &error) { if (error.isEmpty() && version > UpdateWorker::currentVersionNumber()) { updateWorker->showUpdateDialog(true); } updateWorker->deleteLater(); }); updateWorker->checkCurrentVersion(7000); #endif } int ret = a.exec(); return ret; }
3,513
C++
.cpp
90
31.977778
95
0.648839
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,488
MainWindow.cpp
rizinorg_cutter/src/core/MainWindow.cpp
#include "core/MainWindow.h" #include "ui_MainWindow.h" // Common Headers #include "common/AnalysisTask.h" #include "common/BugReporting.h" #include "common/Highlighter.h" #include "common/Helpers.h" #include "common/SvgIconEngine.h" #include "common/ProgressIndicator.h" #include "common/TempConfig.h" #include "common/RunScriptTask.h" #include "common/PythonManager.h" #include "plugins/CutterPlugin.h" #include "plugins/PluginManager.h" #include "CutterConfig.h" #include "CutterApplication.h" // Dialogs #include "dialogs/WelcomeDialog.h" #include "dialogs/NewFileDialog.h" #include "dialogs/InitialOptionsDialog.h" #include "dialogs/CommentsDialog.h" #include "dialogs/AboutDialog.h" #include "dialogs/preferences/PreferencesDialog.h" #include "dialogs/MapFileDialog.h" #include "dialogs/AsyncTaskDialog.h" #include "dialogs/LayoutManager.h" // Widgets Headers #include "widgets/DisassemblerGraphView.h" #include "widgets/GraphView.h" #include "widgets/GraphWidget.h" #include "widgets/GlobalsWidget.h" #include "widgets/OverviewWidget.h" #include "widgets/OverviewView.h" #include "widgets/FunctionsWidget.h" #include "widgets/SectionsWidget.h" #include "widgets/SegmentsWidget.h" #include "widgets/CommentsWidget.h" #include "widgets/ImportsWidget.h" #include "widgets/ExportsWidget.h" #include "widgets/TypesWidget.h" #include "widgets/SearchWidget.h" #include "widgets/SymbolsWidget.h" #include "widgets/StringsWidget.h" #include "widgets/RelocsWidget.h" #include "widgets/FlagsWidget.h" #include "widgets/VisualNavbar.h" #include "widgets/Dashboard.h" #include "widgets/SdbWidget.h" #include "widgets/Omnibar.h" #include "widgets/ConsoleWidget.h" #include "widgets/EntrypointWidget.h" #include "widgets/ClassesWidget.h" #include "widgets/ResourcesWidget.h" #include "widgets/VTablesWidget.h" #include "widgets/HeadersWidget.h" #include "widgets/FlirtWidget.h" #include "widgets/DebugActions.h" #include "widgets/MemoryMapWidget.h" #include "widgets/BreakpointWidget.h" #include "widgets/RegisterRefsWidget.h" #include "widgets/DisassemblyWidget.h" #include "widgets/StackWidget.h" #include "widgets/ThreadsWidget.h" #include "widgets/ProcessesWidget.h" #include "widgets/RegistersWidget.h" #include "widgets/BacktraceWidget.h" #include "widgets/HexdumpWidget.h" #include "widgets/DecompilerWidget.h" #include "widgets/HexWidget.h" #include "widgets/RizinGraphWidget.h" #include "widgets/CallGraph.h" #include "widgets/HeapDockWidget.h" // Qt Headers #include <QActionGroup> #include <QApplication> #include <QComboBox> #include <QCompleter> #include <QDebug> #include <QDesktopServices> #include <QDir> #include <QDockWidget> #include <QFile> #include <QFileDialog> #include <QFont> #include <QFontDialog> #include <QLabel> #include <QLineEdit> #include <QList> #include <QMessageBox> #include <QProcess> #include <QPropertyAnimation> #include <QSysInfo> #include <QJsonObject> #include <QJsonArray> #include <QInputDialog> #include <QScrollBar> #include <QSettings> #include <QShortcut> #include <QStringListModel> #include <QStyledItemDelegate> #include <QStyleFactory> #include <QTextCursor> #include <QtGlobal> #include <QToolButton> #include <QToolTip> #include <QTreeWidgetItem> #include <QSvgRenderer> // Graphics #include <QGraphicsEllipseItem> #include <QGraphicsScene> #include <QGraphicsView> // Tools #include "tools/basefind/BaseFindDialog.h" #define PROJECT_FILE_FILTER tr("Rizin Project (*.rzdb)") template<class T> T *getNewInstance(MainWindow *m) { return new T(m); } using namespace Cutter; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), core(Core()), ui(new Ui::MainWindow) { tabsOnTop = false; configuration = Config(); initUI(); } MainWindow::~MainWindow() {} void MainWindow::initUI() { ui->setupUi(this); // Initialize context menu extensions for plugins disassemblyContextMenuExtensions = new QMenu(tr("Plugins"), this); addressableContextMenuExtensions = new QMenu(tr("Plugins"), this); connect(ui->actionExtraDecompiler, &QAction::triggered, this, &MainWindow::addExtraDecompiler); connect(ui->actionExtraGraph, &QAction::triggered, this, &MainWindow::addExtraGraph); connect(ui->actionExtraDisassembly, &QAction::triggered, this, &MainWindow::addExtraDisassembly); connect(ui->actionExtraHexdump, &QAction::triggered, this, &MainWindow::addExtraHexdump); connect(ui->actionCommitChanges, &QAction::triggered, this, []() { Core()->commitWriteCache(); }); ui->actionCommitChanges->setEnabled(false); connect(Core(), &CutterCore::ioCacheChanged, ui->actionCommitChanges, &QAction::setEnabled); widgetTypeToConstructorMap.insert(GraphWidget::getWidgetType(), getNewInstance<GraphWidget>); widgetTypeToConstructorMap.insert(DisassemblyWidget::getWidgetType(), getNewInstance<DisassemblyWidget>); widgetTypeToConstructorMap.insert(HexdumpWidget::getWidgetType(), getNewInstance<HexdumpWidget>); widgetTypeToConstructorMap.insert(DecompilerWidget::getWidgetType(), getNewInstance<DecompilerWidget>); initToolBar(); initDocks(); emptyState = saveState(); /* * Some global shortcuts */ // Period goes to command entry QShortcut *cmd_shortcut = new QShortcut(QKeySequence(Qt::Key_Period), this); connect(cmd_shortcut, &QShortcut::activated, consoleDock, &ConsoleWidget::focusInputLineEdit); // G and S goes to goto entry QShortcut *goto_shortcut = new QShortcut(QKeySequence(Qt::Key_G), this); connect(goto_shortcut, &QShortcut::activated, this->omnibar, [this]() { this->omnibar->setFocus(); }); QShortcut *seek_shortcut = new QShortcut(QKeySequence(Qt::Key_S), this); connect(seek_shortcut, &QShortcut::activated, this->omnibar, [this]() { this->omnibar->setFocus(); }); QShortcut *seek_to_func_end_shortcut = new QShortcut(QKeySequence(Qt::Key_Dollar), this); connect(seek_to_func_end_shortcut, &QShortcut::activated, this, &MainWindow::seekToFunctionLastInstruction); QShortcut *seek_to_func_start_shortcut = new QShortcut(QKeySequence(Qt::Key_AsciiCircum), this); connect(seek_to_func_start_shortcut, &QShortcut::activated, this, &MainWindow::seekToFunctionStart); QShortcut *refresh_shortcut = new QShortcut(QKeySequence(QKeySequence::Refresh), this); connect(refresh_shortcut, &QShortcut::activated, this, &MainWindow::refreshAll); connect(ui->actionZoomIn, &QAction::triggered, this, &MainWindow::onZoomIn); connect(ui->actionZoomOut, &QAction::triggered, this, &MainWindow::onZoomOut); connect(ui->actionZoomReset, &QAction::triggered, this, &MainWindow::onZoomReset); connect(core, &CutterCore::toggleDebugView, this, &MainWindow::toggleDebugView); connect(core, &CutterCore::newMessage, this->consoleDock, &ConsoleWidget::addOutput); connect(core, &CutterCore::newDebugMessage, this->consoleDock, &ConsoleWidget::addDebugOutput); connect(core, &CutterCore::showMemoryWidgetRequested, this, static_cast<void (MainWindow::*)()>(&MainWindow::showMemoryWidget)); updateTasksIndicator(); connect(core->getAsyncTaskManager(), &AsyncTaskManager::tasksChanged, this, &MainWindow::updateTasksIndicator); // Undo and redo seek ui->actionBackward->setShortcut(QKeySequence::Back); ui->actionForward->setShortcut(QKeySequence::Forward); initBackForwardMenu(); connect(core, &CutterCore::ioModeChanged, this, &MainWindow::setAvailableIOModeOptions); QActionGroup *ioModeActionGroup = new QActionGroup(this); ioModeActionGroup->addAction(ui->actionCacheMode); ioModeActionGroup->addAction(ui->actionWriteMode); ioModeActionGroup->addAction(ui->actionReadOnly); connect(ui->actionCacheMode, &QAction::triggered, this, [this]() { ioModesController.setIOMode(IOModesController::Mode::CACHE); setAvailableIOModeOptions(); }); connect(ui->actionWriteMode, &QAction::triggered, this, [this]() { ioModesController.setIOMode(IOModesController::Mode::WRITE); setAvailableIOModeOptions(); }); connect(ui->actionReadOnly, &QAction::triggered, this, [this]() { ioModesController.setIOMode(IOModesController::Mode::READ_ONLY); setAvailableIOModeOptions(); }); connect(ui->actionSaveLayout, &QAction::triggered, this, &MainWindow::saveNamedLayout); connect(ui->actionManageLayouts, &QAction::triggered, this, &MainWindow::manageLayouts); connect(ui->actionDocumentation, &QAction::triggered, this, &MainWindow::documentationClicked); /* Setup plugins interfaces */ const auto &plugins = Plugins()->getPlugins(); for (auto &plugin : plugins) { plugin->setupInterface(this); } // Check if plugins are loaded and display tooltips accordingly ui->menuWindows->setToolTipsVisible(true); if (plugins.empty()) { ui->menuPlugins->menuAction()->setToolTip( tr("No plugins are installed. Check the plugins section on Cutter documentation to " "learn more.")); ui->menuPlugins->setEnabled(false); } else if (ui->menuPlugins->isEmpty()) { ui->menuPlugins->menuAction()->setToolTip( tr("The installed plugins didn't add entries to this menu.")); ui->menuPlugins->setEnabled(false); } connect(ui->actionUnlock, &QAction::toggled, this, [this](bool unlock) { lockDocks(!unlock); }); #if QT_VERSION < QT_VERSION_CHECK(5, 7, 0) ui->actionGrouped_dock_dragging->setVisible(false); #endif enableDebugWidgetsMenu(false); readSettings(); // Display tooltip for the Analyze Program action ui->actionAnalyze->setToolTip(tr("Analyze the program using Rizin's \"aaa\" command")); ui->menuFile->setToolTipsVisible(true); } void MainWindow::initToolBar() { chooseThemeIcons(); // Sepparator between undo/redo and goto lineEdit QWidget *spacer3 = new QWidget(); spacer3->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); spacer3->setStyleSheet("background-color: rgba(0,0,0,0)"); spacer3->setMinimumSize(20, 20); spacer3->setMaximumWidth(100); ui->mainToolBar->addWidget(spacer3); DebugActions *debugActions = new DebugActions(ui->mainToolBar, this); // Debug menu auto debugViewAction = ui->menuDebug->addAction(tr("View")); debugViewAction->setMenu(ui->menuAddDebugWidgets); ui->menuDebug->addSeparator(); ui->menuDebug->addAction(debugActions->actionStart); ui->menuDebug->addAction(debugActions->actionStartEmul); ui->menuDebug->addAction(debugActions->actionAttach); ui->menuDebug->addAction(debugActions->actionStartRemote); ui->menuDebug->addSeparator(); ui->menuDebug->addAction(debugActions->actionStep); ui->menuDebug->addAction(debugActions->actionStepOver); ui->menuDebug->addAction(debugActions->actionStepOut); ui->menuDebug->addAction(debugActions->actionStepBack); ui->menuDebug->addSeparator(); ui->menuDebug->addAction(debugActions->actionContinue); ui->menuDebug->addAction(debugActions->actionContinueUntilCall); ui->menuDebug->addAction(debugActions->actionContinueUntilSyscall); ui->menuDebug->addAction(debugActions->actionContinueBack); ui->menuDebug->addSeparator(); ui->menuDebug->addAction(debugActions->actionTrace); // Sepparator between undo/redo and goto lineEdit QWidget *spacer4 = new QWidget(); spacer4->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); spacer4->setStyleSheet("background-color: rgba(0,0,0,0)"); spacer4->setMinimumSize(10, 10); spacer4->setMaximumWidth(10); ui->mainToolBar->addWidget(spacer4); // Omnibar LineEdit this->omnibar = new Omnibar(this); ui->mainToolBar->addWidget(this->omnibar); // Add special separators to the toolbar that expand to separate groups of elements QWidget *spacer2 = new QWidget(); spacer2->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); spacer2->setStyleSheet("background-color: rgba(0,0,0,0)"); spacer2->setMinimumSize(10, 10); spacer2->setMaximumWidth(300); ui->mainToolBar->addWidget(spacer2); // Separator between back/forward and undo/redo buttons QWidget *spacer = new QWidget(); spacer->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding); spacer->setStyleSheet("background-color: rgba(0,0,0,0)"); spacer->setMinimumSize(20, 20); ui->mainToolBar->addWidget(spacer); tasksProgressIndicator = new ProgressIndicator(); tasksProgressIndicator->setStyleSheet("background-color: rgba(0,0,0,0)"); ui->mainToolBar->addWidget(tasksProgressIndicator); QWidget *spacerEnd = new QWidget(); spacerEnd->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding); spacerEnd->setStyleSheet("background-color: rgba(0,0,0,0)"); spacerEnd->setMinimumSize(4, 0); spacerEnd->setMaximumWidth(4); ui->mainToolBar->addWidget(spacerEnd); // Visual navigation tool bar this->visualNavbar = new VisualNavbar(this); this->visualNavbar->setMovable(false); addToolBarBreak(Qt::TopToolBarArea); addToolBar(visualNavbar); QObject::connect(configuration, &Configuration::colorsUpdated, this, [this]() { this->visualNavbar->updateGraphicsScene(); }); QObject::connect(configuration, &Configuration::interfaceThemeChanged, this, &MainWindow::chooseThemeIcons); } void MainWindow::initDocks() { dockWidgets.reserve(20); consoleDock = new ConsoleWidget(this); overviewDock = new OverviewWidget(this); overviewDock->hide(); actionOverview = overviewDock->toggleViewAction(); connect(overviewDock, &OverviewWidget::isAvailableChanged, this, [this](bool isAvailable) { actionOverview->setEnabled(isAvailable); }); actionOverview->setEnabled(overviewDock->getIsAvailable()); actionOverview->setChecked(overviewDock->getUserOpened()); dashboardDock = new Dashboard(this); functionsDock = new FunctionsWidget(this); typesDock = new TypesWidget(this); searchDock = new SearchWidget(this); commentsDock = new CommentsWidget(this); stringsDock = new StringsWidget(this); QList<CutterDockWidget *> debugDocks = { stackDock = new StackWidget(this), threadsDock = new ThreadsWidget(this), processesDock = new ProcessesWidget(this), backtraceDock = new BacktraceWidget(this), registersDock = new RegistersWidget(this), memoryMapDock = new MemoryMapWidget(this), breakpointDock = new BreakpointWidget(this), registerRefsDock = new RegisterRefsWidget(this), heapDock = new HeapDockWidget(this) }; QList<CutterDockWidget *> infoDocks = { classesDock = new ClassesWidget(this), entrypointDock = new EntrypointWidget(this), exportsDock = new ExportsWidget(this), flagsDock = new FlagsWidget(this), headersDock = new HeadersWidget(this), importsDock = new ImportsWidget(this), relocsDock = new RelocsWidget(this), resourcesDock = new ResourcesWidget(this), sdbDock = new SdbWidget(this), sectionsDock = new SectionsWidget(this), segmentsDock = new SegmentsWidget(this), symbolsDock = new SymbolsWidget(this), globalsDock = new GlobalsWidget(this), vTablesDock = new VTablesWidget(this), flirtDock = new FlirtWidget(this), rzGraphDock = new RizinGraphWidget(this), callGraphDock = new CallGraphWidget(this, false), globalCallGraphDock = new CallGraphWidget(this, true), }; auto makeActionList = [this](QList<CutterDockWidget *> docks) { QList<QAction *> result; for (auto dock : docks) { if (dock != nullptr) { result.push_back(dock->toggleViewAction()); } else { auto separator = new QAction(this); separator->setSeparator(true); result.push_back(separator); } } return result; }; QList<CutterDockWidget *> windowDocks = { dashboardDock, nullptr, functionsDock, overviewDock, nullptr, searchDock, stringsDock, typesDock, nullptr, }; ui->menuWindows->insertActions(ui->actionExtraDecompiler, makeActionList(windowDocks)); QList<CutterDockWidget *> windowDocks2 = { consoleDock, commentsDock, nullptr, }; ui->menuWindows->addActions(makeActionList(windowDocks2)); ui->menuAddInfoWidgets->addActions(makeActionList(infoDocks)); ui->menuAddDebugWidgets->addActions(makeActionList(debugDocks)); auto uniqueDocks = windowDocks + windowDocks2 + infoDocks + debugDocks; for (auto dock : uniqueDocks) { if (dock) { // ignore nullptr used as separators addWidget(dock); } } } void MainWindow::toggleOverview(bool visibility, GraphWidget *targetGraph) { if (!overviewDock) { return; } if (visibility) { overviewDock->setTargetGraphWidget(targetGraph); } } void MainWindow::updateTasksIndicator() { bool running = core->getAsyncTaskManager()->getTasksRunning(); tasksProgressIndicator->setProgressIndicatorVisible(running); } void MainWindow::addExtraGraph() { auto *extraDock = new GraphWidget(this); addExtraWidget(extraDock); } void MainWindow::addExtraHexdump() { auto *extraDock = new HexdumpWidget(this); addExtraWidget(extraDock); } void MainWindow::addExtraDisassembly() { auto *extraDock = new DisassemblyWidget(this); addExtraWidget(extraDock); } void MainWindow::addExtraDecompiler() { auto *extraDock = new DecompilerWidget(this); addExtraWidget(extraDock); } void MainWindow::addExtraWidget(CutterDockWidget *extraDock) { extraDock->setTransient(true); dockOnMainArea(extraDock); addWidget(extraDock); extraDock->show(); extraDock->raise(); } QMenu *MainWindow::getMenuByType(MenuType type) { switch (type) { case MenuType::File: return ui->menuFile; case MenuType::Edit: return ui->menuEdit; case MenuType::View: return ui->menuView; case MenuType::Windows: return ui->menuWindows; case MenuType::Debug: return ui->menuDebug; case MenuType::Help: return ui->menuHelp; case MenuType::Plugins: return ui->menuPlugins; default: return nullptr; } } void MainWindow::addPluginDockWidget(CutterDockWidget *dockWidget) { addWidget(dockWidget); ui->menuPlugins->addAction(dockWidget->toggleViewAction()); addDockWidget(Qt::DockWidgetArea::TopDockWidgetArea, dockWidget); pluginDocks.push_back(dockWidget); } void MainWindow::addMenuFileAction(QAction *action) { ui->menuFile->addAction(action); } void MainWindow::openNewFile(InitialOptions &options, bool skipOptionsDialog) { setFilename(options.filename); /* Prompt to load filename.rz script */ if (options.script.isEmpty()) { QString script = QString("%1.rz").arg(this->filename); if (rz_file_exists(script.toStdString().data())) { QMessageBox mb; mb.setWindowTitle(tr("Script loading")); mb.setText(tr("Do you want to load the '%1' script?").arg(script)); mb.setStandardButtons(QMessageBox::Yes | QMessageBox::No); if (mb.exec() == QMessageBox::Yes) { options.script = script; } } } /* Show analysis options dialog */ displayInitialOptionsDialog(options, skipOptionsDialog); } void MainWindow::openNewFileFailed() { displayNewFileDialog(); QMessageBox mb(this); mb.setIcon(QMessageBox::Critical); mb.setStandardButtons(QMessageBox::Ok); mb.setWindowTitle(tr("Cannot open file!")); mb.setText(tr("Could not open the file! Make sure the file exists and that you have the " "correct permissions.")); mb.exec(); } /** * @brief displays the WelocmeDialog * * Upon first execution of Cutter, the WelcomeDialog would be showed to the user. * The Welcome dialog would be showed after a reset of Cutter's preferences by the user. */ void MainWindow::displayWelcomeDialog() { WelcomeDialog w; w.exec(); } void MainWindow::displayNewFileDialog() { NewFileDialog *n = new NewFileDialog(this); newFileDialog = n; n->setAttribute(Qt::WA_DeleteOnClose); n->show(); } void MainWindow::closeNewFileDialog() { if (newFileDialog) { newFileDialog->close(); } newFileDialog = nullptr; } void MainWindow::displayInitialOptionsDialog(const InitialOptions &options, bool skipOptionsDialog) { auto o = new InitialOptionsDialog(this); o->setAttribute(Qt::WA_DeleteOnClose); o->loadOptions(options); if (skipOptionsDialog) { if (!options.projectFile.isEmpty()) { if (!openProject(options.projectFile)) { displayNewFileDialog(); }; } else { o->setupAndStartAnalysis(); } } else { o->show(); } } bool MainWindow::openProject(const QString &file) { RzProjectErr err; RzList *res = rz_list_new(); { RzCoreLocked core(Core()); err = rz_project_load_file(core, file.toUtf8().constData(), true, res); } if (err != RZ_PROJECT_ERR_SUCCESS) { const char *s = rz_project_err_message(err); QString msg = tr("Failed to open project: %1").arg(QString::fromUtf8(s)); RzListIter *it; CutterRzListForeach (res, it, const char, s) { msg += "\n" + QString::fromUtf8(s); } QMessageBox::critical(this, tr("Open Project"), msg); rz_list_free(res); return false; } Config()->addRecentProject(file); rz_list_free(res); setFilename(file.trimmed()); finalizeOpen(); return true; } void MainWindow::finalizeOpen() { core->getRegs(); core->updateSeek(); refreshAll(); // Add fortune message char *fortune = rz_core_fortune_get_random(core->core()); if (fortune) { core->message("\n" + QString(fortune)); free(fortune); } // hide all docks before showing window to avoid false positive for refreshDeferrer for (auto dockWidget : dockWidgets) { dockWidget->hide(); } QSettings settings; auto geometry = settings.value("geometry").toByteArray(); if (!geometry.isEmpty()) { restoreGeometry(geometry); show(); } else { showMaximized(); } Config()->adjustColorThemeDarkness(); setViewLayout(getViewLayout(LAYOUT_DEFAULT)); // Set focus to disasm or graph widget // Graph with function in it has focus priority over DisasmWidget. // If there are no graph/disasm widgets focus on MainWindow setFocus(); bool graphContainsFunc = false; for (auto dockWidget : dockWidgets) { auto graphWidget = qobject_cast<GraphWidget *>(dockWidget); if (graphWidget && dockWidget->isVisibleToUser()) { graphContainsFunc = !graphWidget->getGraphView()->getBlocks().empty(); if (graphContainsFunc) { dockWidget->raiseMemoryWidget(); break; } } auto disasmWidget = qobject_cast<DisassemblyWidget *>(dockWidget); if (disasmWidget && dockWidget->isVisibleToUser()) { disasmWidget->raiseMemoryWidget(); // continue looping in case there is a graph widget } auto decompilerWidget = qobject_cast<DecompilerWidget *>(dockWidget); if (decompilerWidget && dockWidget->isVisibleToUser()) { decompilerWidget->raiseMemoryWidget(); // continue looping in case there is a graph widget } } } RzProjectErr MainWindow::saveProject(bool *canceled) { QString file = core->getConfig("prj.file"); if (file.isEmpty()) { return saveProjectAs(canceled); } if (canceled) { *canceled = false; } RzProjectErr err = rz_project_save_file(RzCoreLocked(core), file.toUtf8().constData(), false); if (err == RZ_PROJECT_ERR_SUCCESS) { Config()->addRecentProject(file); } return err; } RzProjectErr MainWindow::saveProjectAs(bool *canceled) { QString projectFile = core->getConfig("prj.file"); if (projectFile.isEmpty()) { // preferred name is of fromat 'binary.exe.rzdb' projectFile = QString("%1.%2").arg(filename).arg("rzdb"); } QFileDialog fileDialog(this); // Append 'rzdb' suffix if it does not exist fileDialog.setDefaultSuffix("rzdb"); QString file = fileDialog.getSaveFileName(this, tr("Save Project"), projectFile, PROJECT_FILE_FILTER); if (file.isEmpty()) { if (canceled) { *canceled = true; } return RZ_PROJECT_ERR_SUCCESS; } if (canceled) { *canceled = false; } RzProjectErr err = rz_project_save_file(RzCoreLocked(core), file.toUtf8().constData(), false); if (err == RZ_PROJECT_ERR_SUCCESS) { Config()->addRecentProject(file); } return err; } void MainWindow::showProjectSaveError(RzProjectErr err) { if (err == RZ_PROJECT_ERR_SUCCESS) { return; } const char *s = rz_project_err_message(err); QMessageBox::critical(this, tr("Save Project"), tr("Failed to save project: %1").arg(QString::fromUtf8(s))); } void MainWindow::refreshOmniBar(const QStringList &flags) { omnibar->refresh(flags); } void MainWindow::setFilename(const QString &fn) { // Add file name to window title this->filename = fn; this->setWindowTitle(APPNAME " – " + fn); } void MainWindow::closeEvent(QCloseEvent *event) { // Check if there are uncommitted changes if (!ioModesController.askCommitUnsavedChanges()) { // if false, Cancel was chosen event->ignore(); return; } activateWindow(); QMessageBox::StandardButton ret = QMessageBox::question( this, APPNAME, tr("Do you really want to exit?\nSave your project before closing!"), (QMessageBox::StandardButtons)(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel)); if (ret == QMessageBox::Cancel) { event->ignore(); return; } if (ret == QMessageBox::Save) { bool canceled; RzProjectErr save_err = saveProject(&canceled); if (canceled) { event->ignore(); return; } else if (save_err != RZ_PROJECT_ERR_SUCCESS) { event->ignore(); showProjectSaveError(save_err); return; } } if (!core->currentlyDebugging) { saveSettings(); } else { core->stopDebug(); } QMainWindow::closeEvent(event); } void MainWindow::paintEvent(QPaintEvent *event) { QMainWindow::paintEvent(event); /* * Dirty hack * Just to adjust the width of Functions Widget to fixed size. * After everything is drawn, restore the max width limit. */ if (functionsDock && functionDockWidthToRestore) { functionsDock->setMaximumWidth(functionDockWidthToRestore); functionDockWidthToRestore = 0; } } void MainWindow::readSettings() { QSettings settings; responsive = settings.value("responsive").toBool(); lockDocks(settings.value("panelLock").toBool()); tabsOnTop = settings.value("tabsOnTop").toBool(); setTabLocation(); bool dockGroupedDragging = settings.value("docksGroupedDragging", false).toBool(); ui->actionGrouped_dock_dragging->setChecked(dockGroupedDragging); on_actionGrouped_dock_dragging_triggered(dockGroupedDragging); loadLayouts(settings); } void MainWindow::saveSettings() { QSettings settings; settings.setValue("panelLock", !ui->actionUnlock->isChecked()); settings.setValue("tabsOnTop", tabsOnTop); settings.setValue("docksGroupedDragging", ui->actionGrouped_dock_dragging->isChecked()); settings.setValue("geometry", saveGeometry()); layouts[Core()->currentlyDebugging ? LAYOUT_DEBUG : LAYOUT_DEFAULT] = getViewLayout(); saveLayouts(settings); } void MainWindow::setTabLocation() { if (tabsOnTop) { this->setTabPosition(Qt::AllDockWidgetAreas, QTabWidget::North); ui->actionTabs_on_Top->setChecked(true); } else { this->setTabPosition(Qt::AllDockWidgetAreas, QTabWidget::South); ui->actionTabs_on_Top->setChecked(false); } } void MainWindow::refreshAll() { core->triggerRefreshAll(); } void MainWindow::lockDocks(bool lock) { if (ui->actionUnlock->isChecked() == lock) { ui->actionUnlock->setChecked(!lock); } if (lock) { for (QDockWidget *dockWidget : findChildren<QDockWidget *>()) { dockWidget->setFeatures(QDockWidget::NoDockWidgetFeatures); } } else { for (QDockWidget *dockWidget : findChildren<QDockWidget *>()) { dockWidget->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable); } } } void MainWindow::restoreDocks() { // Initial structure // func | main area | debug // |___________| // | console | addDockWidget(Qt::LeftDockWidgetArea, functionsDock); splitDockWidget(functionsDock, dashboardDock, Qt::Horizontal); splitDockWidget(dashboardDock, stackDock, Qt::Horizontal); splitDockWidget(dashboardDock, consoleDock, Qt::Vertical); // overview bellow func splitDockWidget(functionsDock, overviewDock, Qt::Vertical); // main area tabifyDockWidget(dashboardDock, entrypointDock); tabifyDockWidget(dashboardDock, flagsDock); tabifyDockWidget(dashboardDock, stringsDock); tabifyDockWidget(dashboardDock, relocsDock); tabifyDockWidget(dashboardDock, importsDock); tabifyDockWidget(dashboardDock, exportsDock); tabifyDockWidget(dashboardDock, typesDock); tabifyDockWidget(dashboardDock, searchDock); tabifyDockWidget(dashboardDock, headersDock); tabifyDockWidget(dashboardDock, flirtDock); tabifyDockWidget(dashboardDock, symbolsDock); tabifyDockWidget(dashboardDock, globalsDock); tabifyDockWidget(dashboardDock, classesDock); tabifyDockWidget(dashboardDock, resourcesDock); tabifyDockWidget(dashboardDock, vTablesDock); tabifyDockWidget(dashboardDock, sdbDock); tabifyDockWidget(dashboardDock, memoryMapDock); tabifyDockWidget(dashboardDock, breakpointDock); tabifyDockWidget(dashboardDock, registerRefsDock); tabifyDockWidget(dashboardDock, rzGraphDock); tabifyDockWidget(dashboardDock, callGraphDock); tabifyDockWidget(dashboardDock, globalCallGraphDock); for (const auto &it : dockWidgets) { // Check whether or not current widgets is graph, hexdump or disasm if (isExtraMemoryWidget(it)) { tabifyDockWidget(dashboardDock, it); } } // Console | Sections/segments/comments splitDockWidget(consoleDock, sectionsDock, Qt::Horizontal); tabifyDockWidget(sectionsDock, segmentsDock); tabifyDockWidget(sectionsDock, commentsDock); // Add Stack, Registers, Threads and Backtrace vertically stacked splitDockWidget(stackDock, registersDock, Qt::Vertical); tabifyDockWidget(stackDock, backtraceDock); tabifyDockWidget(backtraceDock, threadsDock); tabifyDockWidget(threadsDock, processesDock); tabifyDockWidget(processesDock, heapDock); for (auto dock : pluginDocks) { dockOnMainArea(dock); } } bool MainWindow::isDebugWidget(QDockWidget *dock) const { return dock == stackDock || dock == registersDock || dock == backtraceDock || dock == threadsDock || dock == memoryMapDock || dock == breakpointDock || dock == processesDock || dock == registerRefsDock || dock == heapDock; } bool MainWindow::isExtraMemoryWidget(QDockWidget *dock) const { return qobject_cast<GraphWidget *>(dock) || qobject_cast<HexdumpWidget *>(dock) || qobject_cast<DisassemblyWidget *>(dock) || qobject_cast<DecompilerWidget *>(dock); } MemoryWidgetType MainWindow::getMemoryWidgetTypeToRestore() { if (lastSyncMemoryWidget) { return lastSyncMemoryWidget->getType(); } return MemoryWidgetType::Disassembly; } QString MainWindow::getUniqueObjectName(const QString &widgetType) const { QStringList docks; docks.reserve(dockWidgets.size()); QString name; for (const auto &it : dockWidgets) { name = it->objectName(); if (name.split(';').at(0) == widgetType) { docks.push_back(name); } } if (docks.isEmpty()) { return widgetType; } int id = 0; while (docks.contains(widgetType + ";" + QString::number(id))) { id++; } return widgetType + ";" + QString::number(id); } void MainWindow::showMemoryWidget() { if (lastSyncMemoryWidget) { if (lastSyncMemoryWidget->tryRaiseMemoryWidget()) { return; } } showMemoryWidget(MemoryWidgetType::Disassembly); } void MainWindow::showMemoryWidget(MemoryWidgetType type) { for (auto &dock : dockWidgets) { if (auto memoryWidget = qobject_cast<MemoryDockWidget *>(dock)) { if (memoryWidget->getType() == type && memoryWidget->getSeekable()->isSynchronized()) { memoryWidget->tryRaiseMemoryWidget(); return; } } } auto memoryDockWidget = addNewMemoryWidget(type, Core()->getOffset()); memoryDockWidget->raiseMemoryWidget(); } QMenu *MainWindow::createShowInMenu(QWidget *parent, RVA address, AddressTypeHint addressType) { QMenu *menu = new QMenu(parent); // Memory dock widgets for (auto &dock : dockWidgets) { if (auto memoryWidget = qobject_cast<MemoryDockWidget *>(dock)) { if (memoryWidget->getType() == MemoryWidgetType::Graph || memoryWidget->getType() == MemoryWidgetType::Decompiler) { if (addressType == AddressTypeHint::Data) { continue; } } QAction *action = new QAction(memoryWidget->windowTitle(), menu); connect(action, &QAction::triggered, this, [memoryWidget, address]() { memoryWidget->getSeekable()->seek(address); memoryWidget->raiseMemoryWidget(); }); menu->addAction(action); } } menu->addSeparator(); // Rest of the AddressableDockWidgets that weren't added already for (auto &dock : dockWidgets) { if (auto memoryWidget = qobject_cast<AddressableDockWidget *>(dock)) { if (qobject_cast<MemoryDockWidget *>(dock)) { continue; } QAction *action = new QAction(memoryWidget->windowTitle(), menu); connect(action, &QAction::triggered, this, [memoryWidget, address]() { memoryWidget->getSeekable()->seek(address); memoryWidget->raiseMemoryWidget(); }); menu->addAction(action); } } menu->addSeparator(); auto createAddNewWidgetAction = [this, menu, address](QString label, MemoryWidgetType type) { QAction *action = new QAction(label, menu); connect(action, &QAction::triggered, this, [this, address, type]() { addNewMemoryWidget(type, address, false); }); menu->addAction(action); }; createAddNewWidgetAction(tr("New disassembly"), MemoryWidgetType::Disassembly); if (addressType != AddressTypeHint::Data) { createAddNewWidgetAction(tr("New graph"), MemoryWidgetType::Graph); } createAddNewWidgetAction(tr("New hexdump"), MemoryWidgetType::Hexdump); createAddNewWidgetAction(tr("New Decompiler"), MemoryWidgetType::Decompiler); return menu; } void MainWindow::setCurrentMemoryWidget(MemoryDockWidget *memoryWidget) { if (memoryWidget->getSeekable()->isSynchronized()) { lastSyncMemoryWidget = memoryWidget; } lastMemoryWidget = memoryWidget; } MemoryDockWidget *MainWindow::getLastMemoryWidget() { return lastMemoryWidget; } MemoryDockWidget *MainWindow::addNewMemoryWidget(MemoryWidgetType type, RVA address, bool synchronized) { MemoryDockWidget *memoryWidget = nullptr; switch (type) { case MemoryWidgetType::Graph: memoryWidget = new GraphWidget(this); break; case MemoryWidgetType::Hexdump: memoryWidget = new HexdumpWidget(this); break; case MemoryWidgetType::Disassembly: memoryWidget = new DisassemblyWidget(this); break; case MemoryWidgetType::Decompiler: memoryWidget = new DecompilerWidget(this); break; case MemoryWidgetType::CallGraph: memoryWidget = new CallGraphWidget(this, false); break; case MemoryWidgetType::GlobalCallGraph: memoryWidget = new CallGraphWidget(this, true); break; } auto seekable = memoryWidget->getSeekable(); seekable->setSynchronization(synchronized); seekable->seek(address); addExtraWidget(memoryWidget); return memoryWidget; } void MainWindow::initBackForwardMenu() { auto prepareButtonMenu = [this](QAction *action) -> QMenu * { QToolButton *button = qobject_cast<QToolButton *>(ui->mainToolBar->widgetForAction(action)); if (!button) { return nullptr; } QMenu *menu = new QMenu(button); button->setMenu(menu); button->setPopupMode(QToolButton::DelayedPopup); button->setContextMenuPolicy(Qt::CustomContextMenu); connect(button, &QWidget::customContextMenuRequested, button, [menu, button](const QPoint &pos) { menu->exec(button->mapToGlobal(pos)); }); QFontMetrics metrics(font()); // Roughly 10-16 lines depending on padding size, no need to calculate more precisely menu->setMaximumHeight(metrics.lineSpacing() * 20); menu->setToolTipsVisible(true); return menu; }; if (auto menu = prepareButtonMenu(ui->actionBackward)) { menu->setObjectName("historyMenu"); connect(menu, &QMenu::aboutToShow, menu, [this, menu]() { updateHistoryMenu(menu, false); }); } if (auto menu = prepareButtonMenu(ui->actionForward)) { menu->setObjectName("forwardHistoryMenu"); connect(menu, &QMenu::aboutToShow, menu, [this, menu]() { updateHistoryMenu(menu, true); }); } } void MainWindow::updateHistoryMenu(QMenu *menu, bool redo) { // Not too long so that whole screen doesn't get covered, // not too short so that reasonable length c++ names can be seen most of the time const int MAX_NAME_LENGTH = 64; RzListIter *it; RzCoreSeekItem *undo; RzCoreLocked core(Core()); RzList *list = rz_core_seek_list(core); bool history = true; QList<QAction *> actions; CutterRzListForeach (list, it, RzCoreSeekItem, undo) { RzFlagItem *f = rz_flag_get_at(core->flags, undo->offset, true); char *fname = NULL; if (f) { if (f->offset != undo->offset) { fname = rz_str_newf("%s+%" PFMT64d, f->name, undo->offset - f->offset); } else { fname = strdup(f->name); } } QString name = fname; RVA offset = undo->offset; bool current = undo->is_current; if (current) { history = false; } if (history != redo || current) { // Include current in both directions QString addressString = RzAddressString(offset); QString toolTip = QString("%1 %2").arg(addressString, name); // show non truncated name in tooltip name.truncate(MAX_NAME_LENGTH); // TODO:#1904 use common name shortening function QString label = QString("%1 (%2)").arg(name, addressString); if (current) { label = QString("current position (%1)").arg(addressString); } QAction *action = new QAction(label, menu); action->setToolTip(toolTip); actions.push_back(action); if (current) { QFont font; font.setBold(true); action->setFont(font); } } } if (!redo) { std::reverse(actions.begin(), actions.end()); } menu->clear(); menu->addActions(actions); int steps = 0; for (QAction *item : menu->actions()) { if (redo) { connect(item, &QAction::triggered, item, [steps]() { for (int i = 0; i < steps; i++) { Core()->seekNext(); } }); } else { connect(item, &QAction::triggered, item, [steps]() { for (int i = 0; i < steps; i++) { Core()->seekPrev(); } }); } ++steps; } } void MainWindow::updateLayoutsMenu() { ui->menuLayouts->clear(); for (auto it = layouts.begin(), end = layouts.end(); it != end; ++it) { QString name = it.key(); if (isBuiltinLayoutName(name)) { continue; } auto action = new QAction(it.key(), ui->menuLayouts); connect(action, &QAction::triggered, this, [this, name]() { setViewLayout(getViewLayout(name)); }); ui->menuLayouts->addAction(action); } } void MainWindow::saveNamedLayout() { bool ok = false; QString name; QStringList names = layouts.keys(); names.removeAll(LAYOUT_DEBUG); names.removeAll(LAYOUT_DEFAULT); while (name.isEmpty() || isBuiltinLayoutName(name)) { if (ok) { QMessageBox::warning(this, tr("Save layout error"), tr("'%1' is not a valid name.").arg(name)); } name = QInputDialog::getItem(this, tr("Save layout"), tr("Enter name"), names, -1, true, &ok); if (!ok) { return; } } layouts[name] = getViewLayout(); updateLayoutsMenu(); saveSettings(); } void MainWindow::manageLayouts() { LayoutManager layoutManger(layouts, this); layoutManger.exec(); updateLayoutsMenu(); } void MainWindow::addWidget(CutterDockWidget *widget) { dockWidgets.push_back(widget); } void MainWindow::addMemoryDockWidget(MemoryDockWidget *widget) { connect(widget, &QDockWidget::visibilityChanged, this, [this, widget](bool visibility) { if (visibility) { setCurrentMemoryWidget(widget); } }); } void MainWindow::removeWidget(CutterDockWidget *widget) { dockWidgets.removeAll(widget); pluginDocks.removeAll(widget); if (lastSyncMemoryWidget == widget) { lastSyncMemoryWidget = nullptr; } if (lastMemoryWidget == widget) { lastMemoryWidget = nullptr; } } void MainWindow::showZenDocks() { const QList<QDockWidget *> zenDocks = { functionsDock, dashboardDock, stringsDock, searchDock, importsDock }; functionDockWidthToRestore = functionsDock->maximumWidth(); functionsDock->setMaximumWidth(200); for (auto w : dockWidgets) { if (zenDocks.contains(w) || isExtraMemoryWidget(w)) { w->show(); } } dashboardDock->raise(); } void MainWindow::showDebugDocks() { QList<QDockWidget *> debugDocks = { functionsDock, stringsDock, searchDock, stackDock, registersDock, backtraceDock, threadsDock, memoryMapDock, breakpointDock, }; if (QSysInfo::kernelType() == "linux" || Core()->currentlyRemoteDebugging) { debugDocks.append(heapDock); } functionDockWidthToRestore = functionsDock->maximumWidth(); functionsDock->setMaximumWidth(200); auto registerWidth = qhelpers::forceWidth(registersDock, std::min(500, this->width() / 4)); auto registerHeight = qhelpers::forceHeight(registersDock, std::max(100, height() / 2)); QDockWidget *widgetToFocus = nullptr; for (auto w : dockWidgets) { if (debugDocks.contains(w) || isExtraMemoryWidget(w)) { w->show(); } if (qobject_cast<DisassemblyWidget *>(w)) { widgetToFocus = w; } } registerHeight.restoreHeight(registersDock); registerWidth.restoreWidth(registersDock); if (widgetToFocus) { widgetToFocus->raise(); } } void MainWindow::dockOnMainArea(QDockWidget *widget) { QDockWidget *best = nullptr; float bestScore = 1; // choose best existing area for placing the new widget for (auto dock : dockWidgets) { if (dock->isHidden() || dock == widget || dock->isFloating() || // tabifying onto floating dock using code doesn't work well dock->parentWidget() != this) { // floating group isn't considered floating continue; } float newScore = 0; if (isExtraMemoryWidget(dock)) { newScore += 10000000; // prefer existing disssasembly and graph widgets } newScore += dock->width() * dock->height(); // the bigger the better if (newScore > bestScore) { bestScore = newScore; best = dock; } } if (best) { tabifyDockWidget(best, widget); } else { addDockWidget(Qt::TopDockWidgetArea, widget, Qt::Orientation::Horizontal); } } void MainWindow::enableDebugWidgetsMenu(bool enable) { for (QAction *action : ui->menuAddDebugWidgets->actions()) { // The breakpoints menu should be available outside of debug if (!action->text().contains("Breakpoints")) { action->setEnabled(enable); } } } CutterLayout MainWindow::getViewLayout() { CutterLayout layout; layout.geometry = saveGeometry(); layout.state = saveState(); for (auto dock : dockWidgets) { QVariantMap properties; if (auto cutterDock = qobject_cast<CutterDockWidget *>(dock)) { properties = cutterDock->serializeViewProprties(); } layout.viewProperties.insert(dock->objectName(), std::move(properties)); } return layout; } CutterLayout MainWindow::getViewLayout(const QString &name) { auto it = layouts.find(name); if (it != layouts.end()) { return *it; } return {}; } void MainWindow::setViewLayout(const CutterLayout &layout) { bool isDefault = layout.state.isEmpty() || layout.geometry.isEmpty(); bool isDebug = Core()->currentlyDebugging; // make a copy to avoid iterating over container from which items are being removed auto widgetsToClose = dockWidgets; for (auto dock : widgetsToClose) { dock->hide(); dock->close(); dock->setFloating(false); // tabifyDockWidget doesn't work if dock is floating removeDockWidget(dock); } QStringList docksToCreate; if (isDefault) { docksToCreate = QStringList { DisassemblyWidget::getWidgetType(), GraphWidget::getWidgetType(), HexdumpWidget::getWidgetType(), DecompilerWidget::getWidgetType() }; } else { docksToCreate = layout.viewProperties.keys(); } for (const auto &it : docksToCreate) { if (std::none_of(dockWidgets.constBegin(), dockWidgets.constEnd(), [&it](QDockWidget *w) { return w->objectName() == it; })) { auto className = it.split(';').at(0); if (widgetTypeToConstructorMap.contains(className)) { auto widget = widgetTypeToConstructorMap[className](this); widget->setObjectName(it); addExtraWidget(widget); } } } restoreDocks(); QList<QDockWidget *> newDocks; for (auto dock : dockWidgets) { auto properties = layout.viewProperties.find(dock->objectName()); if (properties != layout.viewProperties.end()) { dock->deserializeViewProperties(*properties); } else { dock->deserializeViewProperties({}); // call with empty properties to reset the widget newDocks.push_back(dock); } dock->ignoreVisibilityStatus(true); } if (!isDefault) { restoreState(layout.state); for (auto dock : newDocks) { dock->hide(); // hide to prevent dockOnMainArea putting them on each other } for (auto dock : newDocks) { dockOnMainArea(dock); // Show any new docks by default. // Showing new builtin docks helps discovering features added in latest release. // Installing a new plugin hints that usre will likely want to use it. dock->show(); } } else { if (isDebug) { showDebugDocks(); } else { showZenDocks(); } } for (auto dock : dockWidgets) { dock->ignoreVisibilityStatus(false); } lastSyncMemoryWidget = nullptr; lastMemoryWidget = nullptr; } void MainWindow::loadLayouts(QSettings &settings) { this->layouts.clear(); int size = settings.beginReadArray("layouts"); for (int i = 0; i < size; i++) { CutterLayout layout; settings.setArrayIndex(i); QString name = settings.value("name", "layout").toString(); layout.geometry = settings.value("geometry").toByteArray(); layout.state = settings.value("state").toByteArray(); auto docks = settings.value("docks").toMap(); for (auto it = docks.begin(), end = docks.end(); it != end; it++) { layout.viewProperties.insert(it.key(), it.value().toMap()); } layouts.insert(name, std::move(layout)); } settings.endArray(); updateLayoutsMenu(); } void MainWindow::saveLayouts(QSettings &settings) { settings.beginWriteArray("layouts", layouts.size()); int arrayIndex = 0; for (auto it = layouts.begin(), end = layouts.end(); it != end; ++it, ++arrayIndex) { settings.setArrayIndex(arrayIndex); settings.setValue("name", it.key()); auto &layout = it.value(); settings.setValue("state", layout.state); settings.setValue("geometry", layout.geometry); QVariantMap properties; for (auto it = layout.viewProperties.begin(), end = layout.viewProperties.end(); it != end; ++it) { properties.insert(it.key(), it.value()); } settings.setValue("docks", properties); } settings.endArray(); } void MainWindow::on_actionDefault_triggered() { if (core->currentlyDebugging) { layouts[LAYOUT_DEBUG] = {}; setViewLayout(layouts[LAYOUT_DEBUG]); } else { layouts[LAYOUT_DEFAULT] = {}; setViewLayout(layouts[LAYOUT_DEFAULT]); } } /** * @brief MainWindow::on_actionNew_triggered * Open a new Cutter session. */ void MainWindow::on_actionNew_triggered() { // Create a new Cutter process static_cast<CutterApplication *>(qApp)->launchNewInstance(); } void MainWindow::on_actionSave_triggered() { showProjectSaveError(saveProject(nullptr)); } void MainWindow::on_actionSaveAs_triggered() { showProjectSaveError(saveProjectAs(nullptr)); } void MainWindow::on_actionRun_Script_triggered() { QFileDialog dialog(this); dialog.setFileMode(QFileDialog::ExistingFile); dialog.setViewMode(QFileDialog::Detail); dialog.setDirectory(QDir::home()); const QString &fileName = QDir::toNativeSeparators(dialog.getOpenFileName(this, tr("Select Rizin script"))); if (fileName.isEmpty()) // Cancel was pressed return; RunScriptTask *runScriptTask = new RunScriptTask(); runScriptTask->setFileName(fileName); AsyncTask::Ptr runScriptTaskPtr(runScriptTask); AsyncTaskDialog *taskDialog = new AsyncTaskDialog(runScriptTaskPtr, this); taskDialog->setInterruptOnClose(true); taskDialog->setAttribute(Qt::WA_DeleteOnClose); taskDialog->show(); Core()->getAsyncTaskManager()->start(runScriptTaskPtr); } /** * @brief MainWindow::on_actionOpen_triggered * Open a file as in "load (add) a file in current session". */ void MainWindow::on_actionMap_triggered() { MapFileDialog dialog(this); dialog.exec(); } void MainWindow::toggleResponsive(bool maybe) { this->responsive = maybe; // Save options in settings QSettings settings; settings.setValue("responsive", this->responsive); } void MainWindow::on_actionTabs_on_Top_triggered() { this->on_actionTabs_triggered(); } void MainWindow::on_actionReset_settings_triggered() { QMessageBox::StandardButton ret = (QMessageBox::StandardButton)QMessageBox::question( this, APPNAME, tr("Do you really want to clear all settings?"), QMessageBox::Ok | QMessageBox::Cancel); if (ret == QMessageBox::Ok) { Config()->resetAll(); readSettings(); setViewLayout(getViewLayout(Core()->currentlyDebugging ? LAYOUT_DEBUG : LAYOUT_DEFAULT)); } } void MainWindow::on_actionQuit_triggered() { close(); } void MainWindow::on_actionBackward_triggered() { core->seekPrev(); } void MainWindow::on_actionForward_triggered() { core->seekNext(); } void MainWindow::on_actionDisasAdd_comment_triggered() { CommentsDialog c(this); c.exec(); } void MainWindow::on_actionRefresh_contents_triggered() { refreshAll(); } void MainWindow::on_actionPreferences_triggered() { if (!findChild<PreferencesDialog *>()) { auto dialog = new PreferencesDialog(this); dialog->show(); } } void MainWindow::on_actionTabs_triggered() { tabsOnTop = !tabsOnTop; setTabLocation(); } void MainWindow::on_actionBaseFind_triggered() { auto dialog = new BaseFindDialog(this); dialog->show(); } void MainWindow::on_actionAbout_triggered() { AboutDialog *a = new AboutDialog(this); a->setAttribute(Qt::WA_DeleteOnClose); a->open(); } void MainWindow::on_actionIssue_triggered() { openIssue(); } void MainWindow::documentationClicked() { QDesktopServices::openUrl(QUrl("https://cutter.re/docs/user-docs")); } void MainWindow::on_actionRefresh_Panels_triggered() { this->refreshAll(); } /** * @brief A signal that creates an AsyncTask to re-analyze the current file */ void MainWindow::on_actionAnalyze_triggered() { auto *analysisTask = new AnalysisTask(); InitialOptions options; options.analysisCmd = { { "aaa", "Auto analysis" } }; analysisTask->setOptions(options); AsyncTask::Ptr analysisTaskPtr(analysisTask); auto *taskDialog = new AsyncTaskDialog(analysisTaskPtr); taskDialog->setInterruptOnClose(true); taskDialog->setAttribute(Qt::WA_DeleteOnClose); taskDialog->show(); connect(analysisTask, &AnalysisTask::finished, this, &MainWindow::refreshAll); Core()->getAsyncTaskManager()->start(analysisTaskPtr); } void MainWindow::on_actionImportPDB_triggered() { QFileDialog dialog(this); dialog.setWindowTitle(tr("Select PDB file")); dialog.setNameFilters({ tr("PDB file (*.pdb)"), tr("All files (*)") }); if (!dialog.exec()) { return; } const QString &pdbFile = QDir::toNativeSeparators(dialog.selectedFiles().first()); if (!pdbFile.isEmpty()) { core->loadPDB(pdbFile); core->message(tr("%1 loaded.").arg(pdbFile)); this->refreshAll(); } } #define TYPE_BIG_ENDIAN(type, big_endian) big_endian ? type##_BE : type##_LE void MainWindow::on_actionExport_as_code_triggered() { QStringList filters; QMap<QString, RzLangByteArrayType> typMap; const bool big_endian = Core()->getConfigb("big_endian"); filters << tr("C uin8_t array (*.c)"); typMap[filters.last()] = RZ_LANG_BYTE_ARRAY_C_CPP_BYTES; filters << tr("C uin16_t array (*.c)"); typMap[filters.last()] = TYPE_BIG_ENDIAN(RZ_LANG_BYTE_ARRAY_C_CPP_HALFWORDS, big_endian); filters << tr("C uin32_t array (*.c)"); typMap[filters.last()] = TYPE_BIG_ENDIAN(RZ_LANG_BYTE_ARRAY_C_CPP_WORDS, big_endian); filters << tr("C uin64_t array (*.c)"); typMap[filters.last()] = TYPE_BIG_ENDIAN(RZ_LANG_BYTE_ARRAY_C_CPP_DOUBLEWORDS, big_endian); filters << tr("Go array (*.go)"); typMap[filters.last()] = RZ_LANG_BYTE_ARRAY_GOLANG; filters << tr("Java array (*.java)"); typMap[filters.last()] = RZ_LANG_BYTE_ARRAY_JAVA; filters << tr("JSON array (*.json)"); typMap[filters.last()] = RZ_LANG_BYTE_ARRAY_JSON; filters << tr("Kotlin array (*.kt)"); typMap[filters.last()] = RZ_LANG_BYTE_ARRAY_KOTLIN; filters << tr("Javascript array (*.js)"); typMap[filters.last()] = RZ_LANG_BYTE_ARRAY_NODEJS; filters << tr("ObjectiveC array (*.m)"); typMap[filters.last()] = RZ_LANG_BYTE_ARRAY_OBJECTIVE_C; filters << tr("Python array (*.py)"); typMap[filters.last()] = RZ_LANG_BYTE_ARRAY_PYTHON; filters << tr("Rust array (*.rs)"); typMap[filters.last()] = RZ_LANG_BYTE_ARRAY_RUST; filters << tr("Swift array (*.swift)"); typMap[filters.last()] = RZ_LANG_BYTE_ARRAY_SWIFT; filters << tr("Print 'wx' Rizin commands (*.rz)"); typMap[filters.last()] = RZ_LANG_BYTE_ARRAY_RIZIN; filters << tr("Shell-script that reconstructs the bin (*.sh)"); typMap[filters.last()] = RZ_LANG_BYTE_ARRAY_BASH; filters << tr("GAS .byte blob (*.asm, *.s)"); typMap[filters.last()] = RZ_LANG_BYTE_ARRAY_ASM; filters << tr("Yara (*.yar)"); typMap[filters.last()] = RZ_LANG_BYTE_ARRAY_YARA; /* special case */ QString instructionsInComments = tr(".bytes with instructions in comments (*.txt)"); filters << instructionsInComments; QFileDialog dialog(this, tr("Export as code")); dialog.setAcceptMode(QFileDialog::AcceptSave); dialog.setFileMode(QFileDialog::AnyFile); dialog.setNameFilters(filters); dialog.selectFile("dump"); dialog.setDefaultSuffix("c"); if (!dialog.exec()) return; QFile file(dialog.selectedFiles()[0]); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { qWarning() << tr("Can't open file"); return; } TempConfig tempConfig; tempConfig.set("io.va", false); QTextStream fileOut(&file); auto ps = core->seekTemp(0); auto rc = core->core(); const auto size = static_cast<int>(rz_io_fd_size(rc->io, rc->file->fd)); auto buffer = std::vector<ut8>(size); if (!rz_io_read_at(Core()->core()->io, 0, buffer.data(), size)) { return; } auto string = fromOwned( dialog.selectedNameFilter() != instructionsInComments ? rz_lang_byte_array(buffer.data(), size, typMap[dialog.selectedNameFilter()]) : rz_core_print_bytes_with_inst(rc, buffer.data(), 0, size)); fileOut << string.get(); } void MainWindow::on_actionApplySigFromFile_triggered() { QStringList filters; filters << tr("Signature File (*.sig)"); filters << tr("Pattern File (*.pat)"); QFileDialog dialog(this); dialog.setWindowTitle(tr("Apply Signature From File")); dialog.setNameFilters(filters); if (!dialog.exec()) { return; } const QString &sigfile = QDir::toNativeSeparators(dialog.selectedFiles().first()); if (!sigfile.isEmpty()) { core->applySignature(sigfile); this->refreshAll(); } } void MainWindow::on_actionCreateNewSig_triggered() { QStringList filters; filters << tr("Signature File (*.sig)"); filters << tr("Pattern File (*.pat)"); QFileDialog dialog(this, tr("Create New Signature File")); dialog.setAcceptMode(QFileDialog::AcceptSave); dialog.setFileMode(QFileDialog::AnyFile); dialog.setNameFilters(filters); dialog.selectFile(""); dialog.setDefaultSuffix("sig"); if (!dialog.exec()) return; const QString &sigfile = QDir::toNativeSeparators(dialog.selectedFiles().first()); if (!sigfile.isEmpty()) { core->createSignature(sigfile); } } void MainWindow::on_actionGrouped_dock_dragging_triggered(bool checked) { #if QT_VERSION >= QT_VERSION_CHECK(5, 7, 0) auto options = dockOptions(); options.setFlag(QMainWindow::DockOption::GroupedDragging, checked); setDockOptions(options); #else Q_UNUSED(checked); #endif } void MainWindow::seekToFunctionLastInstruction() { Core()->seek(Core()->getLastFunctionInstruction(Core()->getOffset())); } void MainWindow::seekToFunctionStart() { Core()->seek(Core()->getFunctionStart(Core()->getOffset())); } void MainWindow::toggleDebugView() { MemoryWidgetType memType = getMemoryWidgetTypeToRestore(); if (Core()->currentlyDebugging) { layouts[LAYOUT_DEFAULT] = getViewLayout(); setViewLayout(getViewLayout(LAYOUT_DEBUG)); enableDebugWidgetsMenu(true); } else { layouts[LAYOUT_DEBUG] = getViewLayout(); setViewLayout(getViewLayout(LAYOUT_DEFAULT)); enableDebugWidgetsMenu(false); } showMemoryWidget(memType); } void MainWindow::mousePressEvent(QMouseEvent *event) { switch (event->button()) { case Qt::BackButton: core->seekPrev(); break; case Qt::ForwardButton: core->seekNext(); break; default: break; } } bool MainWindow::eventFilter(QObject *obj, QEvent *event) { // For every create event - disable context help and proceed to next event check if (event->type() == QEvent::Create) { if (obj->isWidgetType()) { auto w = static_cast<QWidget *>(obj); w->setWindowFlags(w->windowFlags() & (~Qt::WindowContextHelpButtonHint)); } } if (event->type() == QEvent::MouseButtonPress) { QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event); if (mouseEvent->button() == Qt::ForwardButton || mouseEvent->button() == Qt::BackButton) { mousePressEvent(mouseEvent); return true; } } return false; } bool MainWindow::event(QEvent *event) { if (event->type() == QEvent::FontChange || event->type() == QEvent::StyleChange || event->type() == QEvent::PaletteChange) { #if QT_VERSION < QT_VERSION_CHECK(5, 10, 0) QMetaObject::invokeMethod(Config(), "refreshFont", Qt::ConnectionType::QueuedConnection); #else QMetaObject::invokeMethod(Config(), &Configuration::refreshFont, Qt::ConnectionType::QueuedConnection); #endif } return QMainWindow::event(event); } /** * @brief Show a warning message box. * * This API can either be used in Cutter internals, or by Python plugins. */ void MainWindow::messageBoxWarning(QString title, QString message) { QMessageBox mb(this); mb.setIcon(QMessageBox::Warning); mb.setStandardButtons(QMessageBox::Ok); mb.setWindowTitle(title); mb.setText(message); mb.exec(); } /** * @brief When theme changed, change icons which have a special version for the theme. */ void MainWindow::chooseThemeIcons() { // List of QActions which have alternative icons in different themes const QList<QPair<void *, QString>> kSupportedIconsNames { { ui->actionForward, QStringLiteral("arrow_right.svg") }, { ui->actionBackward, QStringLiteral("arrow_left.svg") }, }; // Set the correct icon for the QAction qhelpers::setThemeIcons(kSupportedIconsNames, [](void *obj, const QIcon &icon) { static_cast<QAction *>(obj)->setIcon(icon); }); } void MainWindow::onZoomIn() { Config()->setZoomFactor(Config()->getZoomFactor() + 0.1); } void MainWindow::onZoomOut() { Config()->setZoomFactor(Config()->getZoomFactor() - 0.1); } void MainWindow::onZoomReset() { Config()->setZoomFactor(1.0); } QMenu *MainWindow::getContextMenuExtensions(ContextMenuType type) { switch (type) { case ContextMenuType::Disassembly: return disassemblyContextMenuExtensions; case ContextMenuType::Addressable: return addressableContextMenuExtensions; default: return nullptr; } } void MainWindow::setAvailableIOModeOptions() { switch (ioModesController.getIOMode()) { case IOModesController::Mode::WRITE: ui->actionWriteMode->setChecked(true); break; case IOModesController::Mode::CACHE: ui->actionCacheMode->setChecked(true); break; default: ui->actionReadOnly->setChecked(true); } }
65,050
C++
.cpp
1,758
30.843572
100
0.672461
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,489
Basefind.cpp
rizinorg_cutter/src/core/Basefind.cpp
#include "Basefind.h" bool Basefind::threadCallback(const RzBaseFindThreadInfo *info, void *user) { auto th = reinterpret_cast<Basefind *>(user); return th->updateProgress(info); } Basefind::Basefind(CutterCore *core) : core(core), scores(nullptr), continue_run(true) #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) , mutex(QMutex::Recursive) #endif { memset(&options, 0, sizeof(RzBaseFindOpt)); } Basefind::~Basefind() { cancel(); wait(); rz_list_free(scores); } bool Basefind::setOptions(const RzBaseFindOpt *opts) { mutex.lock(); options.max_threads = opts->max_threads; options.pointer_size = opts->pointer_size; options.start_address = opts->start_address; options.end_address = opts->end_address; options.alignment = opts->alignment; options.min_score = opts->min_score; options.min_string_len = opts->min_string_len; mutex.unlock(); if (options.start_address >= options.end_address) { qWarning() << tr("Start address is >= end address"); return false; } else if (options.alignment < RZ_BASEFIND_BASE_ALIGNMENT) { qWarning() << tr("Alignment must be at least ") << QString::asprintf("0x%x", RZ_BASEFIND_BASE_ALIGNMENT); return false; } else if (options.min_score < 1) { qWarning() << tr("Min score must be at least 1"); return false; } else if (options.min_string_len < 1) { qWarning() << tr("Min string length must be at least 1"); return false; } return true; } void Basefind::run() { qRegisterMetaType<BasefindCoreStatusDescription>(); mutex.lock(); rz_list_free(scores); scores = nullptr; continue_run = true; mutex.unlock(); core->coreMutex.lock(); options.callback = threadCallback; options.user = this; scores = rz_basefind(core->core_, &options); core->coreMutex.unlock(); emit complete(); } void Basefind::cancel() { mutex.lock(); continue_run = false; mutex.unlock(); } QList<BasefindResultDescription> Basefind::results() { QList<BasefindResultDescription> pairs; RzListIter *it; RzBaseFindScore *pair; CutterRzListForeach (scores, it, RzBaseFindScore, pair) { BasefindResultDescription desc; desc.candidate = pair->candidate; desc.score = pair->score; pairs.push_back(desc); } return pairs; } bool Basefind::updateProgress(const RzBaseFindThreadInfo *info) { mutex.lock(); BasefindCoreStatusDescription status; status.index = info->thread_idx; status.percentage = info->percentage; emit progress(status); bool ret = continue_run; mutex.unlock(); return ret; }
2,731
C++
.cpp
95
23.989474
76
0.667429
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,490
Cutter.cpp
rizinorg_cutter/src/core/Cutter.cpp
#include <QJsonArray> #include <QJsonObject> #include <QRegularExpression> #include <QDir> #include <QCoreApplication> #include <QVector> #include <QStringList> #include <QStandardPaths> #include <cassert> #include <memory> #include "common/TempConfig.h" #include "common/BasicInstructionHighlighter.h" #include "common/Configuration.h" #include "common/AsyncTask.h" #include "common/RizinTask.h" #include "dialogs/RizinTaskDialog.h" #include "common/Json.h" #include "core/Cutter.h" #include "Decompiler.h" #include <rz_asm.h> #include <rz_cmd.h> #include <sdb.h> static CutterCore *uniqueInstance; #define RZ_JSON_KEY(name) static const QString name = QStringLiteral(#name) namespace RJsonKey { RZ_JSON_KEY(addr); RZ_JSON_KEY(addrs); RZ_JSON_KEY(addr_end); RZ_JSON_KEY(arrow); RZ_JSON_KEY(baddr); RZ_JSON_KEY(bind); RZ_JSON_KEY(blocks); RZ_JSON_KEY(blocksize); RZ_JSON_KEY(bytes); RZ_JSON_KEY(calltype); RZ_JSON_KEY(cc); RZ_JSON_KEY(classname); RZ_JSON_KEY(code); RZ_JSON_KEY(comment); RZ_JSON_KEY(comments); RZ_JSON_KEY(cost); RZ_JSON_KEY(data); RZ_JSON_KEY(description); RZ_JSON_KEY(ebbs); RZ_JSON_KEY(edges); RZ_JSON_KEY(enabled); RZ_JSON_KEY(entropy); RZ_JSON_KEY(fcn_addr); RZ_JSON_KEY(fcn_name); RZ_JSON_KEY(fields); RZ_JSON_KEY(file); RZ_JSON_KEY(flags); RZ_JSON_KEY(flagname); RZ_JSON_KEY(format); RZ_JSON_KEY(from); RZ_JSON_KEY(functions); RZ_JSON_KEY(graph); RZ_JSON_KEY(haddr); RZ_JSON_KEY(hw); RZ_JSON_KEY(in_functions); RZ_JSON_KEY(index); RZ_JSON_KEY(jump); RZ_JSON_KEY(laddr); RZ_JSON_KEY(lang); RZ_JSON_KEY(len); RZ_JSON_KEY(length); RZ_JSON_KEY(license); RZ_JSON_KEY(methods); RZ_JSON_KEY(name); RZ_JSON_KEY(realname); RZ_JSON_KEY(nargs); RZ_JSON_KEY(nbbs); RZ_JSON_KEY(nlocals); RZ_JSON_KEY(offset); RZ_JSON_KEY(opcode); RZ_JSON_KEY(opcodes); RZ_JSON_KEY(ordinal); RZ_JSON_KEY(libname); RZ_JSON_KEY(outdegree); RZ_JSON_KEY(paddr); RZ_JSON_KEY(path); RZ_JSON_KEY(perm); RZ_JSON_KEY(pid); RZ_JSON_KEY(plt); RZ_JSON_KEY(prot); RZ_JSON_KEY(ref); RZ_JSON_KEY(refs); RZ_JSON_KEY(reg); RZ_JSON_KEY(rwx); RZ_JSON_KEY(section); RZ_JSON_KEY(sections); RZ_JSON_KEY(size); RZ_JSON_KEY(stackframe); RZ_JSON_KEY(status); RZ_JSON_KEY(string); RZ_JSON_KEY(strings); RZ_JSON_KEY(symbols); RZ_JSON_KEY(text); RZ_JSON_KEY(to); RZ_JSON_KEY(trace); RZ_JSON_KEY(type); RZ_JSON_KEY(uid); RZ_JSON_KEY(vaddr); RZ_JSON_KEY(value); RZ_JSON_KEY(vsize); } #undef RZ_JSON_KEY static void updateOwnedCharPtr(char *&variable, const QString &newValue) { auto data = newValue.toUtf8(); RZ_FREE(variable) variable = strdup(data.data()); } static bool reg_sync(RzCore *core, RzRegisterType type, bool write) { if (rz_core_is_debug(core)) { return rz_debug_reg_sync(core->dbg, type, write); } return true; } RzCoreLocked::RzCoreLocked(CutterCore *core) : core(core) { core->coreMutex.lock(); assert(core->coreLockDepth >= 0); core->coreLockDepth++; if (core->coreLockDepth == 1) { assert(core->coreBed); rz_cons_sleep_end(core->coreBed); core->coreBed = nullptr; } } RzCoreLocked::~RzCoreLocked() { assert(core->coreLockDepth > 0); core->coreLockDepth--; if (core->coreLockDepth == 0) { core->coreBed = rz_cons_sleep_begin(); } core->coreMutex.unlock(); } RzCoreLocked::operator RzCore *() const { return core->core_; } RzCore *RzCoreLocked::operator->() const { return core->core_; } #define CORE_LOCK() RzCoreLocked core(this) static void cutterREventCallback(RzEvent *, int type, void *user, void *data) { auto core = reinterpret_cast<CutterCore *>(user); core->handleREvent(type, data); } CutterCore::CutterCore(QObject *parent) : QObject(parent) #if QT_VERSION < QT_VERSION_CHECK(5, 14, 0) , coreMutex(QMutex::Recursive) #endif { if (uniqueInstance) { throw std::logic_error("Only one instance of CutterCore must exist"); } uniqueInstance = this; } CutterCore *CutterCore::instance() { return uniqueInstance; } void CutterCore::initialize(bool loadPlugins) { #if defined(MACOS_RZ_BUNDLED) auto app_path = QDir(QCoreApplication::applicationDirPath()); app_path.cdUp(); app_path.cd("Resources"); qInfo() << "Setting Rizin prefix =" << app_path.absolutePath() << " for macOS Application Bundle."; rz_path_set_prefix(app_path.absolutePath().toUtf8().constData()); #endif rz_cons_new(); // initialize console core_ = rz_core_new(); rz_core_task_sync_begin(&core_->tasks); coreBed = rz_cons_sleep_begin(); CORE_LOCK(); rz_event_hook(core_->analysis->ev, RZ_EVENT_ALL, cutterREventCallback, this); if (loadPlugins) { setConfig("cfg.plugins", true); rz_core_loadlibs(this->core_, RZ_CORE_LOADLIBS_ALL); } else { setConfig("cfg.plugins", false); } // IMPLICIT rz_bin_iobind (core_->bin, core_->io); // Otherwise Rizin may ask the user for input and Cutter would freeze setConfig("scr.interactive", false); // Temporary workaround for https://github.com/rizinorg/rizin/issues/2741 // Otherwise sometimes disassembly is truncated. // The blocksize here is a rather arbitrary value larger than the default 0x100. rz_core_block_size(core, 0x400); // Initialize graph node highlighter bbHighlighter = new BasicBlockHighlighter(); // Initialize Async tasks manager asyncTaskManager = new AsyncTaskManager(this); } CutterCore::~CutterCore() { delete bbHighlighter; rz_cons_sleep_end(coreBed); rz_core_task_sync_end(&core_->tasks); rz_core_free(this->core_); rz_cons_free(); assert(uniqueInstance == this); uniqueInstance = nullptr; } RzCoreLocked CutterCore::core() { return RzCoreLocked(this); } QDir CutterCore::getCutterRCDefaultDirectory() const { return QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation); } QVector<QString> CutterCore::getCutterRCFilePaths() const { QVector<QString> result; result.push_back(QFileInfo(QDir::home(), ".cutterrc").absoluteFilePath()); QStringList locations = QStandardPaths::standardLocations(QStandardPaths::AppConfigLocation); for (auto &location : locations) { result.push_back(QFileInfo(QDir(location), ".cutterrc").absoluteFilePath()); } result.push_back(QFileInfo(getCutterRCDefaultDirectory(), "rc") .absoluteFilePath()); // File in config editor is from this path return result; } void CutterCore::loadCutterRC() { CORE_LOCK(); const auto result = getCutterRCFilePaths(); for (auto &cutterRCFilePath : result) { auto cutterRCFileInfo = QFileInfo(cutterRCFilePath); if (!cutterRCFileInfo.exists() || !cutterRCFileInfo.isFile()) { continue; } qInfo() << tr("Loading initialization file from ") << cutterRCFilePath; rz_core_cmd_file(core, cutterRCFilePath.toUtf8().constData()); rz_cons_flush(); } } void CutterCore::loadDefaultCutterRC() { CORE_LOCK(); auto cutterRCFilePath = QFileInfo(getCutterRCDefaultDirectory(), "rc").absoluteFilePath(); const auto cutterRCFileInfo = QFileInfo(cutterRCFilePath); if (!cutterRCFileInfo.exists() || !cutterRCFileInfo.isFile()) { return; } qInfo() << tr("Loading initialization file from ") << cutterRCFilePath; rz_core_cmd_file(core, cutterRCFilePath.toUtf8().constData()); rz_cons_flush(); } QList<QString> CutterCore::sdbList(QString path) { CORE_LOCK(); QList<QString> list = QList<QString>(); Sdb *root = sdb_ns_path(core->sdb, path.toUtf8().constData(), 0); if (root && root->ns) { for (const auto &nsi : CutterRzList<SdbNs>(root->ns)) { list << nsi->name; } } return list; } using PVectorPtr = std::unique_ptr<RzPVector, decltype(&rz_pvector_free)>; static PVectorPtr makePVectorPtr(RzPVector *vec) { return { vec, rz_pvector_free }; } static bool foreach_keys_cb(void *user, const SdbKv *kv) { auto list = reinterpret_cast<QList<QString> *>(user); *list << kv->base.key; return true; } QList<QString> CutterCore::sdbListKeys(QString path) { CORE_LOCK(); QList<QString> list = QList<QString>(); Sdb *root = sdb_ns_path(core->sdb, path.toUtf8().constData(), 0); if (root) { sdb_foreach(root, foreach_keys_cb, &list); } return list; } QString CutterCore::sdbGet(QString path, QString key) { CORE_LOCK(); Sdb *db = sdb_ns_path(core->sdb, path.toUtf8().constData(), 0); if (db) { const char *val = sdb_const_get(db, key.toUtf8().constData()); if (val && *val) return val; } return QString(); } bool CutterCore::sdbSet(QString path, QString key, QString val) { CORE_LOCK(); Sdb *db = sdb_ns_path(core->sdb, path.toUtf8().constData(), 1); if (!db) return false; return sdb_set(db, key.toUtf8().constData(), val.toUtf8().constData()); } QString CutterCore::sanitizeStringForCommand(QString s) { static const QRegularExpression regexp(";|@"); return s.replace(regexp, QStringLiteral("_")); } QString CutterCore::cmd(const char *str) { CORE_LOCK(); RVA offset = core->offset; char *res = rz_core_cmd_str(core, str); QString o = fromOwnedCharPtr(res); if (offset != core->offset) { updateSeek(); } return o; } QString CutterCore::getFunctionExecOut(const std::function<bool(RzCore *)> &fcn, const RVA addr) { CORE_LOCK(); RVA offset = core->offset; seekSilent(addr); QString o = {}; rz_cons_push(); bool is_pipe = core->is_pipe; core->is_pipe = true; if (!fcn(core)) { core->is_pipe = is_pipe; rz_cons_pop(); goto clean_return; } core->is_pipe = is_pipe; rz_cons_filter(); o = rz_cons_get_buffer(); rz_cons_pop(); rz_cons_echo(NULL); clean_return: if (offset != core->offset) { seekSilent(offset); } return o; } bool CutterCore::isRedirectableDebugee() { if (!currentlyDebugging || currentlyAttachedToPID != -1) { return false; } // We are only able to redirect locally debugged unix processes RzCoreLocked core(Core()); RzList *descs = rz_id_storage_list(core->io->files); RzListIter *it; RzIODesc *desc; CutterRzListForeach (descs, it, RzIODesc, desc) { QString URI = QString(desc->uri); if (URI.contains("ptrace") || URI.contains("mach")) { return true; } } return false; } bool CutterCore::isDebugTaskInProgress() { if (!debugTask.isNull()) { return true; } return false; } bool CutterCore::asyncTask(std::function<void *(RzCore *)> fcn, QSharedPointer<RizinTask> &task) { if (!task.isNull()) { return false; } CORE_LOCK(); RVA offset = core->offset; task = QSharedPointer<RizinTask>(new RizinFunctionTask(std::move(fcn), true)); connect(task.data(), &RizinTask::finished, task.data(), [this, offset, task]() { CORE_LOCK(); if (offset != core->offset) { updateSeek(); } }); return true; } void CutterCore::functionTask(std::function<void *(RzCore *)> fcn) { auto task = std::unique_ptr<RizinTask>(new RizinFunctionTask(std::move(fcn), true)); task->startTask(); task->joinTask(); } QString CutterCore::cmdRawAt(const char *cmd, RVA address) { QString res; RVA oldOffset = getOffset(); seekSilent(address); res = cmdRaw(cmd); seekSilent(oldOffset); return res; } QString CutterCore::cmdRaw(const char *cmd) { QString res; CORE_LOCK(); return rz_core_cmd_str(core, cmd); } CutterJson CutterCore::cmdj(const char *str) { char *res; { CORE_LOCK(); res = rz_core_cmd_str(core, str); } return parseJson("cmdj", res, str); } QString CutterCore::cmdTask(const QString &str) { RizinCmdTask task(str); task.startTask(); task.joinTask(); return task.getResult(); } CutterJson CutterCore::parseJson(const char *name, char *res, const char *cmd) { if (RZ_STR_ISEMPTY(res)) { return CutterJson(); } RzJson *doc = rz_json_parse(res); if (!doc) { if (cmd) { RZ_LOG_ERROR("%s: Failed to parse JSON for command \"%s\"\n%s\n", name, cmd, res); } else { RZ_LOG_ERROR("%s: Failed to parse JSON %s\n", name, res); } RZ_LOG_ERROR("%s: %s\n", name, res); } return CutterJson(doc, QSharedPointer<CutterJsonOwner>::create(doc, res)); } QStringList CutterCore::autocomplete(const QString &cmd, RzLinePromptType promptType) { RzLineBuffer buf; int c = snprintf(buf.data, sizeof(buf.data), "%s", cmd.toUtf8().constData()); if (c < 0) { return {}; } buf.index = buf.length = std::min((int)(sizeof(buf.data) - 1), c); RzLineNSCompletionResult *compr = rz_core_autocomplete_rzshell(core(), &buf, promptType); QStringList r; auto optslen = rz_pvector_len(&compr->options); r.reserve(optslen); for (size_t i = 0; i < optslen; i++) { r.push_back(QString::fromUtf8( reinterpret_cast<const char *>(rz_pvector_at(&compr->options, i)))); } rz_line_ns_completion_result_free(compr); return r; } /** * @brief CutterCore::loadFile * Load initial file. * @param path File path * @param baddr Base (RzBin) address * @param mapaddr Map address * @param perms * @param va * @param loadbin Load RzBin information * @param forceBinPlugin * @return */ bool CutterCore::loadFile(QString path, ut64 baddr, ut64 mapaddr, int perms, int va, bool loadbin, const QString &forceBinPlugin) { CORE_LOCK(); RzCoreFile *f; rz_config_set_i(core->config, "io.va", va); f = rz_core_file_open(core, path.toUtf8().constData(), perms, mapaddr); if (!f) { eprintf("rz_core_file_open failed\n"); return false; } if (!forceBinPlugin.isNull()) { rz_bin_force_plugin(rz_core_get_bin(core), forceBinPlugin.toUtf8().constData()); } if (loadbin && va) { if (!rz_core_bin_load(core, path.toUtf8().constData(), baddr)) { eprintf("CANNOT GET RBIN INFO\n"); } #if HAVE_MULTIPLE_RBIN_FILES_INSIDE_SELECT_WHICH_ONE if (!rz_core_file_open(core, path.toUtf8(), RZ_IO_READ | (rw ? RZ_IO_WRITE : 0, mapaddr))) { eprintf("Cannot open file\n"); } else { // load RzBin information // XXX only for sub-bins rz_core_bin_load(core, path.toUtf8(), baddr); rz_bin_select_idx(core->bin, NULL, idx); } #endif } auto iod = core->io ? core->io->desc : NULL; auto debug = core->file && iod && (core->file->fd == iod->fd) && iod->plugin && iod->plugin->isdbg; if (!debug && rz_flag_get(core->flags, "entry0")) { ut64 addr = rz_num_math(core->num, "entry0"); rz_core_seek_and_save(core, addr, true); } if (perms & RZ_PERM_W) { RzPVector *maps = rz_io_maps(core->io); for (auto map : CutterPVector<RzIOMap>(maps)) { map->perm |= RZ_PERM_W; } } rz_cons_flush(); fflush(stdout); return true; } bool CutterCore::tryFile(QString path, bool rw) { if (path.isEmpty()) { // opening no file is always possible return true; } CORE_LOCK(); RzCoreFile *cf; int flags = RZ_PERM_R; if (rw) flags = RZ_PERM_RW; cf = rz_core_file_open(core, path.toUtf8().constData(), flags, 0LL); if (!cf) { return false; } rz_core_file_close(cf); return true; } /** * @brief Maps a file using Rizin API * @param path Path to file * @param mapaddr Map Address * @return bool */ bool CutterCore::mapFile(QString path, RVA mapaddr) { CORE_LOCK(); RVA addr = mapaddr != RVA_INVALID ? mapaddr : 0; ut64 baddr = rz_bin_get_baddr(core->bin); if (rz_core_file_open(core, path.toUtf8().constData(), RZ_PERM_RX, addr)) { rz_core_bin_load(core, path.toUtf8().constData(), baddr); } else { return false; } return true; } void CutterCore::renameFunction(const RVA offset, const QString &newName) { CORE_LOCK(); rz_core_analysis_function_rename(core, offset, newName.toStdString().c_str()); emit functionRenamed(offset, newName); } void CutterCore::delFunction(RVA addr) { CORE_LOCK(); rz_core_analysis_undefine(core, addr); emit functionsChanged(); } void CutterCore::renameFlag(QString old_name, QString new_name) { CORE_LOCK(); RzFlagItem *flag = rz_flag_get(core->flags, old_name.toStdString().c_str()); if (!flag) return; rz_flag_rename(core->flags, flag, new_name.toStdString().c_str()); emit flagsChanged(); } void CutterCore::renameFunctionVariable(QString newName, QString oldName, RVA functionAddress) { CORE_LOCK(); RzAnalysisFunction *function = rz_analysis_get_function_at(core->analysis, functionAddress); RzAnalysisVar *variable = rz_analysis_function_get_var_byname(function, oldName.toUtf8().constData()); if (variable) { rz_analysis_var_rename(variable, newName.toUtf8().constData(), true); } emit refreshCodeViews(); } void CutterCore::delFlag(RVA addr) { CORE_LOCK(); rz_flag_unset_off(core->flags, addr); emit flagsChanged(); } void CutterCore::delFlag(const QString &name) { CORE_LOCK(); rz_flag_unset_name(core->flags, name.toStdString().c_str()); emit flagsChanged(); } CutterRzIter<RzAnalysisBytes> CutterCore::getRzAnalysisBytesSingle(RVA addr) { CORE_LOCK(); ut8 buf[128]; rz_io_read_at(core->io, addr, buf, sizeof(buf)); // Warning! only safe to use with stack buffer, due to instruction count being 1 auto result = CutterRzIter<RzAnalysisBytes>(rz_core_analysis_bytes(core, addr, buf, sizeof(buf), 1)); return result; } QString CutterCore::getInstructionBytes(RVA addr) { auto ab = getRzAnalysisBytesSingle(addr); return ab ? ab->bytes : ""; } QString CutterCore::getInstructionOpcode(RVA addr) { auto ab = getRzAnalysisBytesSingle(addr); return ab ? ab->opcode : ""; } void CutterCore::editInstruction(RVA addr, const QString &inst, bool fillWithNops) { CORE_LOCK(); if (fillWithNops) { rz_core_write_assembly_fill(core, addr, inst.trimmed().toStdString().c_str()); } else { rz_core_write_assembly(core, addr, inst.trimmed().toStdString().c_str()); } emit instructionChanged(addr); } void CutterCore::nopInstruction(RVA addr) { CORE_LOCK(); { auto seek = seekTemp(addr); rz_core_hack(core, "nop"); } emit instructionChanged(addr); } void CutterCore::jmpReverse(RVA addr) { CORE_LOCK(); { auto seek = seekTemp(addr); rz_core_hack(core, "recj"); } emit instructionChanged(addr); } void CutterCore::editBytes(RVA addr, const QString &bytes) { CORE_LOCK(); rz_core_write_hexpair(core, addr, bytes.toUtf8().constData()); emit instructionChanged(addr); } void CutterCore::editBytesEndian(RVA addr, const QString &bytes) { CORE_LOCK(); ut64 value = rz_num_math(core->num, bytes.toUtf8().constData()); if (core->num->nc.errors) { return; } rz_core_write_value_at(core, addr, value, 0); emit stackChanged(); } void CutterCore::setToCode(RVA addr) { CORE_LOCK(); rz_meta_del(core->analysis, RZ_META_TYPE_STRING, core->offset, 1); rz_meta_del(core->analysis, RZ_META_TYPE_DATA, core->offset, 1); emit instructionChanged(addr); } void CutterCore::setAsString(RVA addr, int size, StringTypeFormats type) { if (RVA_INVALID == addr) { return; } RzStrEnc encoding; switch (type) { case StringTypeFormats::None: { encoding = RZ_STRING_ENC_GUESS; break; } case StringTypeFormats::ASCII_LATIN1: { encoding = RZ_STRING_ENC_8BIT; break; } case StringTypeFormats::UTF8: { encoding = RZ_STRING_ENC_UTF8; break; } default: return; } CORE_LOCK(); seekAndShow(addr); rz_core_meta_string_add(core, addr, size, encoding, nullptr); emit instructionChanged(addr); } void CutterCore::removeString(RVA addr) { CORE_LOCK(); rz_meta_del(core->analysis, RZ_META_TYPE_STRING, addr, 1); emit instructionChanged(addr); } QString CutterCore::getString(RVA addr) { CORE_LOCK(); return getString(addr, core->blocksize, rz_str_guess_encoding_from_buffer(core->block, core->blocksize)); } QString CutterCore::getString(RVA addr, uint64_t len, RzStrEnc encoding, bool escape_nl) { CORE_LOCK(); RzStrStringifyOpt opt = {}; opt.buffer = core->block; opt.length = len; opt.encoding = encoding; opt.escape_nl = escape_nl; auto seek = seekTemp(addr); return fromOwnedCharPtr(rz_str_stringify_raw_buffer(&opt, NULL)); } QString CutterCore::getMetaString(RVA addr) { CORE_LOCK(); return rz_meta_get_string(core->analysis, RZ_META_TYPE_STRING, addr); } void CutterCore::setToData(RVA addr, int size, int repeat) { if (size <= 0 || repeat <= 0) { return; } CORE_LOCK(); RVA address = addr; for (int i = 0; i < repeat; ++i, address += size) { rz_meta_set(core->analysis, RZ_META_TYPE_DATA, address, size, nullptr); } emit instructionChanged(addr); } int CutterCore::sizeofDataMeta(RVA addr) { ut64 size; CORE_LOCK(); rz_meta_get_at(core->analysis, addr, RZ_META_TYPE_DATA, &size); return (int)size; } void CutterCore::setComment(RVA addr, const QString &cmt) { CORE_LOCK(); rz_meta_set_string(core->analysis, RZ_META_TYPE_COMMENT, addr, cmt.toStdString().c_str()); emit commentsChanged(addr); } void CutterCore::delComment(RVA addr) { CORE_LOCK(); rz_meta_del(core->analysis, RZ_META_TYPE_COMMENT, addr, 1); emit commentsChanged(addr); } /** * @brief Gets the comment present at a specific address * @param addr The address to be checked * @return String containing comment */ QString CutterCore::getCommentAt(RVA addr) { CORE_LOCK(); return rz_meta_get_string(core->analysis, RZ_META_TYPE_COMMENT, addr); } void CutterCore::setImmediateBase(const QString &rzBaseName, RVA offset) { if (offset == RVA_INVALID) { offset = getOffset(); } CORE_LOCK(); int base = (int)rz_num_base_of_string(core->num, rzBaseName.toUtf8().constData()); rz_analysis_hint_set_immbase(core->analysis, offset, base); emit instructionChanged(offset); } void CutterCore::setCurrentBits(int bits, RVA offset) { if (offset == RVA_INVALID) { offset = getOffset(); } CORE_LOCK(); rz_analysis_hint_set_bits(core->analysis, offset, bits); emit instructionChanged(offset); } void CutterCore::applyStructureOffset(const QString &structureOffset, RVA offset) { if (offset == RVA_INVALID) { offset = getOffset(); } { CORE_LOCK(); auto seek = seekTemp(offset); rz_core_analysis_hint_set_offset(core, structureOffset.toUtf8().constData()); } emit instructionChanged(offset); } void CutterCore::seekSilent(ut64 offset) { CORE_LOCK(); if (offset == RVA_INVALID) { return; } rz_core_seek(core, offset, true); } void CutterCore::seek(ut64 offset) { // Slower than using the API, but the API is not complete // which means we either have to duplicate code from rizin // here, or refactor rizin API. CORE_LOCK(); if (offset == RVA_INVALID) { return; } RVA o_offset = core->offset; rz_core_seek_and_save(core, offset, true); if (o_offset != core->offset) { updateSeek(); } } void CutterCore::showMemoryWidget() { emit showMemoryWidgetRequested(); } void CutterCore::seekAndShow(ut64 offset) { seek(offset); showMemoryWidget(); } void CutterCore::seekAndShow(QString offset) { seek(offset); showMemoryWidget(); } void CutterCore::seek(QString thing) { CORE_LOCK(); ut64 addr = rz_num_math(core->num, thing.toUtf8().constData()); if (core->num->nc.errors) { return; } rz_core_seek_and_save(core, addr, true); updateSeek(); } void CutterCore::seekPrev() { CORE_LOCK(); rz_core_seek_undo(core); updateSeek(SeekHistoryType::Undo); } void CutterCore::seekNext() { CORE_LOCK(); rz_core_seek_redo(core); updateSeek(SeekHistoryType::Redo); } void CutterCore::updateSeek(SeekHistoryType type) { emit seekChanged(getOffset(), type); } RVA CutterCore::prevOpAddr(RVA startAddr, int count) { CORE_LOCK(); return rz_core_prevop_addr_force(core, startAddr, count); } RVA CutterCore::nextOpAddr(RVA startAddr, int count) { CORE_LOCK(); auto seek = seekTemp(startAddr); auto consumed = rz_core_analysis_ops_size(core, core->offset, core->block, (int)core->blocksize, count); RVA addr = startAddr + consumed; return addr; } RVA CutterCore::getOffset() { return core_->offset; } void CutterCore::applySignature(const QString &filepath) { CORE_LOCK(); int old_cnt, new_cnt; const char *arch = rz_config_get(core->config, "asm.arch"); ut8 expected_arch = rz_core_flirt_arch_from_name(arch); if (expected_arch == RZ_FLIRT_SIG_ARCH_ANY && filepath.endsWith(".sig", Qt::CaseInsensitive)) { QMessageBox::warning(nullptr, tr("Signatures"), tr("Cannot apply signature file because the requested arch is not " "supported by .sig " "files")); return; } old_cnt = rz_flag_count(core->flags, "flirt"); if (rz_sign_flirt_apply(core->analysis, filepath.toStdString().c_str(), expected_arch)) { new_cnt = rz_flag_count(core->flags, "flirt"); QMessageBox::information(nullptr, tr("Signatures"), tr("Found %1 matching signatures!").arg(new_cnt - old_cnt)); return; } QMessageBox::warning( nullptr, tr("Signatures"), tr("Failed to apply signature file!\nPlease check the console for more details.")); } void CutterCore::createSignature(const QString &filepath) { CORE_LOCK(); ut32 n_modules = 0; if (!rz_core_flirt_create_file(core, filepath.toStdString().c_str(), &n_modules)) { QMessageBox::warning( nullptr, tr("Signatures"), tr("Cannot create signature file (check the console for more details).")); return; } QMessageBox::information(nullptr, tr("Signatures"), tr("Written %1 signatures to %2.").arg(n_modules).arg(filepath)); } ut64 CutterCore::math(const QString &expr) { CORE_LOCK(); return rz_num_math(core ? core->num : NULL, expr.toUtf8().constData()); } ut64 CutterCore::num(const QString &expr) { CORE_LOCK(); return rz_num_get(core ? core->num : NULL, expr.toUtf8().constData()); } QString CutterCore::itoa(ut64 num, int rdx) { return QString::number(num, rdx); } void CutterCore::setConfig(const char *k, const char *v) { CORE_LOCK(); rz_config_set(core->config, k, v); } void CutterCore::setConfig(const QString &k, const char *v) { CORE_LOCK(); rz_config_set(core->config, k.toUtf8().constData(), v); } void CutterCore::setConfig(const char *k, const QString &v) { CORE_LOCK(); rz_config_set(core->config, k, v.toUtf8().constData()); } void CutterCore::setConfig(const char *k, int v) { CORE_LOCK(); rz_config_set_i(core->config, k, static_cast<ut64>(v)); } void CutterCore::setConfig(const char *k, bool v) { CORE_LOCK(); rz_config_set_i(core->config, k, v ? 1 : 0); } int CutterCore::getConfigi(const char *k) { CORE_LOCK(); return static_cast<int>(rz_config_get_i(core->config, k)); } ut64 CutterCore::getConfigut64(const char *k) { CORE_LOCK(); return rz_config_get_i(core->config, k); } bool CutterCore::getConfigb(const char *k) { CORE_LOCK(); return rz_config_get_i(core->config, k) != 0; } QString CutterCore::getConfigDescription(const char *k) { CORE_LOCK(); RzConfigNode *node = rz_config_node_get(core->config, k); return node ? QString(node->desc) : QString("Unrecognized configuration key"); } void CutterCore::triggerRefreshAll() { emit refreshAll(); } void CutterCore::triggerAsmOptionsChanged() { emit asmOptionsChanged(); } void CutterCore::triggerGraphOptionsChanged() { emit graphOptionsChanged(); } void CutterCore::message(const QString &msg, bool debug) { if (msg.isEmpty()) return; if (debug) { qDebug() << msg; emit newDebugMessage(msg); return; } emit newMessage(msg); } QString CutterCore::getConfig(const char *k) { CORE_LOCK(); return { rz_config_get(core->config, k) }; } QStringList CutterCore::getConfigOptions(const char *k) { CORE_LOCK(); RzConfigNode *node = rz_config_node_get(core->config, k); if (!(node && node->options)) { return {}; } QStringList list; for (const auto &s : CutterRzList<char>(node->options)) { list << s; } return list; } void CutterCore::setConfig(const char *k, const QVariant &v) { switch (v.type()) { case QVariant::Type::Bool: setConfig(k, v.toBool()); break; case QVariant::Type::Int: setConfig(k, v.toInt()); break; default: setConfig(k, v.toString()); break; } } void CutterCore::setCPU(QString arch, QString cpu, int bits) { if (arch != nullptr) { setConfig("asm.arch", arch); } if (cpu != nullptr) { setConfig("asm.cpu", cpu); } setConfig("asm.bits", bits); } void CutterCore::setEndianness(bool big) { setConfig("cfg.bigendian", big); } QByteArray CutterCore::assemble(const QString &code) { CORE_LOCK(); RzAsmCode *ac = rz_asm_massemble(core->rasm, code.toUtf8().constData()); QByteArray res; if (ac && ac->bytes) { res = QByteArray(reinterpret_cast<const char *>(ac->bytes), ac->len); } rz_asm_code_free(ac); return res; } QString CutterCore::disassemble(const QByteArray &data) { CORE_LOCK(); RzAsmCode *ac = rz_asm_mdisassemble(core->rasm, reinterpret_cast<const ut8 *>(data.constData()), data.length()); QString code; if (ac && ac->assembly) { code = QString::fromUtf8(ac->assembly); } rz_asm_code_free(ac); return code; } QString CutterCore::disassembleSingleInstruction(RVA addr) { auto ab = getRzAnalysisBytesSingle(addr); return QString(ab->disasm).simplified(); } RzAnalysisFunction *CutterCore::functionIn(ut64 addr) { CORE_LOCK(); RzAnalysisFunction *fcn = rz_analysis_get_function_at(core->analysis, addr); if (fcn) { return fcn; } RzList *fcns = rz_analysis_get_functions_in(core->analysis, addr); fcn = !rz_list_empty(fcns) ? reinterpret_cast<RzAnalysisFunction *>(rz_list_first(fcns)) : nullptr; rz_list_free(fcns); return fcn; } RzAnalysisFunction *CutterCore::functionAt(ut64 addr) { CORE_LOCK(); return rz_analysis_get_function_at(core->analysis, addr); } /** * @brief finds the start address of a function in a given address * @param addr - an address which belongs to a function * @returns if function exists, return its start address. Otherwise return RVA_INVALID */ RVA CutterCore::getFunctionStart(RVA addr) { CORE_LOCK(); RzAnalysisFunction *fcn = Core()->functionIn(addr); return fcn ? fcn->addr : RVA_INVALID; } /** * @brief finds the end address of a function in a given address * @param addr - an address which belongs to a function * @returns if function exists, return its end address. Otherwise return RVA_INVALID */ RVA CutterCore::getFunctionEnd(RVA addr) { CORE_LOCK(); RzAnalysisFunction *fcn = Core()->functionIn(addr); return fcn ? fcn->addr : RVA_INVALID; } /** * @brief finds the last instruction of a function in a given address * @param addr - an address which belongs to a function * @returns if function exists, return the address of its last instruction. Otherwise return * RVA_INVALID */ RVA CutterCore::getLastFunctionInstruction(RVA addr) { CORE_LOCK(); RzAnalysisFunction *fcn = Core()->functionIn(addr); if (!fcn) { return RVA_INVALID; } RzAnalysisBlock *lastBB = (RzAnalysisBlock *)rz_pvector_tail(fcn->bbs); return lastBB ? rz_analysis_block_get_op_addr(lastBB, lastBB->ninstr - 1) : RVA_INVALID; } QString CutterCore::flagAt(RVA addr) { CORE_LOCK(); RzFlagItem *f = rz_flag_get_at(core->flags, addr, true); if (!f) { return {}; } return core->flags->realnames && f->realname ? f->realname : f->name; } void CutterCore::createFunctionAt(RVA addr) { createFunctionAt(addr, ""); } void CutterCore::createFunctionAt(RVA addr, QString name) { if (!name.isEmpty() && !name.isNull()) { static const QRegularExpression regExp("[^a-zA-Z0-9_.]"); name.remove(regExp); } CORE_LOCK(); bool analyze_recursively = rz_config_get_i(core->config, "analysis.calls"); rz_core_analysis_function_add(core, name.toStdString().c_str(), addr, analyze_recursively); emit functionsChanged(); } RVA CutterCore::getOffsetJump(RVA addr) { auto ab = getRzAnalysisBytesSingle(addr); return ab && ab->op ? ab->op->jump : RVA_INVALID; } QList<Decompiler *> CutterCore::getDecompilers() { return decompilers; } Decompiler *CutterCore::getDecompilerById(const QString &id) { for (Decompiler *dec : decompilers) { if (dec->getId() == id) { return dec; } } return nullptr; } bool CutterCore::registerDecompiler(Decompiler *decompiler) { if (getDecompilerById(decompiler->getId())) { return false; } decompiler->setParent(this); decompilers.push_back(decompiler); return true; } CutterJson CutterCore::getSignatureInfo() { CORE_LOCK(); RzBinFile *cur = rz_bin_cur(core->bin); RzBinPlugin *plg = rz_bin_file_cur_plugin(cur); if (!plg || !plg->signature) { return {}; } char *signature = plg->signature(cur, true); if (!signature) { return {}; } return parseJson("signature", signature, nullptr); } bool CutterCore::existsFileInfo() { CORE_LOCK(); RzBinObject *bobj = rz_bin_cur_object(core->bin); if (!bobj) { return false; } const RzBinInfo *info = rz_bin_object_get_info(bobj); if (!(info && info->rclass)) { return false; } return strncmp("pe", info->rclass, 2) == 0 || strncmp("elf", info->rclass, 3) == 0; } // Utility function to check if a telescoped item exists and add it with prefixes to the desc static inline const QString appendVar(QString &dst, const QString val, const QString prepend_val, const QString append_val) { if (!val.isEmpty()) { dst += prepend_val + val + append_val; } return val; } RefDescription CutterCore::formatRefDesc(const QSharedPointer<AddrRefs> &refItem) { RefDescription desc; if (refItem->addr == RVA_INVALID) { return desc; } QString str = refItem->string; if (!str.isEmpty()) { desc.ref = str; desc.refColor = ConfigColor("comment"); } else { QSharedPointer<const AddrRefs> cursor(refItem); QString type, string; while (true) { desc.ref += " ->"; appendVar(desc.ref, cursor->reg, " @", ""); appendVar(desc.ref, cursor->mapname, " (", ")"); appendVar(desc.ref, cursor->section, " (", ")"); appendVar(desc.ref, cursor->fcn, " ", ""); type = appendVar(desc.ref, cursor->type, " ", ""); appendVar(desc.ref, cursor->perms, " ", ""); appendVar(desc.ref, cursor->asm_op, " \"", "\""); string = appendVar(desc.ref, cursor->string, " ", ""); if (!string.isNull()) { // There is no point in adding ascii and addr info after a string break; } if (cursor->has_value) { appendVar(desc.ref, RzAddressString(cursor->value), " ", ""); } if (!cursor->ref) { break; } cursor = cursor->ref; } // Set the ref's color according to the last item type if (type == "ascii" || !string.isEmpty()) { desc.refColor = ConfigColor("comment"); } else if (type == "program") { desc.refColor = ConfigColor("fname"); } else if (type == "library") { desc.refColor = ConfigColor("floc"); } else if (type == "stack") { desc.refColor = ConfigColor("offset"); } } return desc; } RzReg *CutterCore::getReg() { CORE_LOCK(); if (currentlyDebugging && currentlyEmulating) { return core->analysis->reg; } else if (currentlyDebugging) { return core->dbg->reg; } return core->analysis->reg; } QList<RegisterRef> CutterCore::getRegisterRefs(int depth) { QList<RegisterRef> ret; if (!currentlyDebugging) { return ret; } CORE_LOCK(); RzList *ritems = rz_core_reg_filter_items_sync(core, getReg(), reg_sync, nullptr); if (!ritems) { return ret; } RzListIter *it; RzRegItem *ri; CutterRzListForeach (ritems, it, RzRegItem, ri) { RegisterRef reg; reg.value = rz_reg_get_value(getReg(), ri); reg.ref = getAddrRefs(reg.value, depth); reg.name = ri->name; ret.append(reg); } rz_list_free(ritems); return ret; } QList<AddrRefs> CutterCore::getStack(int size, int depth) { QList<AddrRefs> stack; if (!currentlyDebugging) { return stack; } CORE_LOCK(); RVA addr = rz_core_reg_getv_by_role_or_name(core, "SP"); if (addr == RVA_INVALID) { return stack; } int base = core->analysis->bits; for (int i = 0; i < size; i += base / 8) { if ((base == 32 && addr + i >= UT32_MAX) || (base == 16 && addr + i >= UT16_MAX)) { break; } stack.append(getAddrRefs(addr + i, depth)); } return stack; } AddrRefs CutterCore::getAddrRefs(RVA addr, int depth) { AddrRefs refs; if (depth < 1 || addr == UT64_MAX) { refs.addr = RVA_INVALID; return refs; } CORE_LOCK(); int bits = core->rasm->bits; QByteArray buf = QByteArray(); ut64 type = rz_core_analysis_address(core, addr); refs.addr = addr; // Search for the section the addr is in, avoid duplication for heap/stack with type if (!(type & RZ_ANALYSIS_ADDR_TYPE_HEAP || type & RZ_ANALYSIS_ADDR_TYPE_STACK)) { // Attempt to find the address within a map RzDebugMap *map = rz_debug_map_get(core->dbg, addr); if (map && map->name && map->name[0]) { refs.mapname = map->name; } RzBinSection *sect = rz_bin_get_section_at(rz_bin_cur_object(core->bin), addr, true); if (sect && sect->name[0]) { refs.section = sect->name; } } // Check if the address points to a register RzFlagItem *fi = rz_flag_get_i(core->flags, addr); if (fi) { RzRegItem *r = rz_reg_get(getReg(), fi->name, -1); if (r) { refs.reg = r->name; } } // Attempt to find the address within a function RzAnalysisFunction *fcn = rz_analysis_get_fcn_in(core->analysis, addr, 0); if (fcn) { refs.fcn = fcn->name; } // Update type and permission information if (type != 0) { if (type & RZ_ANALYSIS_ADDR_TYPE_HEAP) { refs.type = "heap"; } else if (type & RZ_ANALYSIS_ADDR_TYPE_STACK) { refs.type = "stack"; } else if (type & RZ_ANALYSIS_ADDR_TYPE_PROGRAM) { refs.type = "program"; } else if (type & RZ_ANALYSIS_ADDR_TYPE_LIBRARY) { refs.type = "library"; } else if (type & RZ_ANALYSIS_ADDR_TYPE_ASCII) { refs.type = "ascii"; } else if (type & RZ_ANALYSIS_ADDR_TYPE_SEQUENCE) { refs.type = "sequence"; } QString perms = ""; if (type & RZ_ANALYSIS_ADDR_TYPE_READ) { perms += "r"; } if (type & RZ_ANALYSIS_ADDR_TYPE_WRITE) { perms += "w"; } if (type & RZ_ANALYSIS_ADDR_TYPE_EXEC) { RzAsmOp op; buf.resize(32); perms += "x"; // Instruction disassembly rz_io_read_at(core->io, addr, (unsigned char *)buf.data(), buf.size()); rz_asm_set_pc(core->rasm, addr); rz_asm_disassemble(core->rasm, &op, (unsigned char *)buf.data(), buf.size()); refs.asm_op = rz_asm_op_get_asm(&op); } if (!perms.isEmpty()) { refs.perms = perms; } } // Try to telescope further if depth permits it if ((type & RZ_ANALYSIS_ADDR_TYPE_READ)) { buf.resize(64); ut32 *n32 = (ut32 *)buf.data(); ut64 *n64 = (ut64 *)buf.data(); rz_io_read_at(core->io, addr, (unsigned char *)buf.data(), buf.size()); ut64 n = (bits == 64) ? *n64 : *n32; // The value of the next address will serve as an indication that there's more to // telescope if we have reached the depth limit refs.value = n; refs.has_value = true; if (depth && n != addr && !(type & RZ_ANALYSIS_ADDR_TYPE_EXEC)) { // Make sure we aren't telescoping the same address AddrRefs ref = getAddrRefs(n, depth - 1); if (!ref.type.isNull()) { // If the dereference of the current pointer is an ascii character we // might have a string in this address if (ref.type.contains("ascii")) { buf.resize(128); rz_io_read_at(core->io, addr, (unsigned char *)buf.data(), buf.size()); QString strVal = QString(buf); // Indicate that the string is longer than the printed value if (strVal.size() == buf.size()) { strVal += "..."; } refs.string = strVal; } refs.ref = QSharedPointer<AddrRefs>::create(ref); } } } return refs; } QVector<Chunk> CutterCore::getHeapChunks(RVA arena_addr) { CORE_LOCK(); QVector<Chunk> chunks_vector; ut64 m_arena; if (!arena_addr) { // if arena_addr is zero get base address of main arena RzList *arenas = rz_heap_arenas_list(core); if (arenas->length == 0) { rz_list_free(arenas); return chunks_vector; } m_arena = ((RzArenaListItem *)rz_list_first(arenas))->addr; rz_list_free(arenas); } else { m_arena = arena_addr; } // Get chunks using api and store them in a chunks_vector RzList *chunks = rz_heap_chunks_list(core, m_arena); RzListIter *iter; RzHeapChunkListItem *data; CutterRzListForeach (chunks, iter, RzHeapChunkListItem, data) { Chunk chunk; chunk.offset = data->addr; chunk.size = (int)data->size; chunk.status = QString(data->status); chunks_vector.append(chunk); } rz_list_free(chunks); return chunks_vector; } int CutterCore::getArchBits() { CORE_LOCK(); return core->dbg->bits; } QVector<Arena> CutterCore::getArenas() { CORE_LOCK(); QVector<Arena> arena_vector; // get arenas using API and store them in arena_vector RzList *arenas = rz_heap_arenas_list(core); RzListIter *iter; RzArenaListItem *data; CutterRzListForeach (arenas, iter, RzArenaListItem, data) { Arena arena; arena.offset = data->addr; arena.type = QString(data->type); arena.last_remainder = data->arena->last_remainder; arena.top = data->arena->top; arena.next = data->arena->next; arena.next_free = data->arena->next_free; arena.system_mem = data->arena->system_mem; arena.max_system_mem = data->arena->max_system_mem; arena_vector.append(arena); } rz_list_free(arenas); return arena_vector; } RzHeapChunkSimple *CutterCore::getHeapChunk(ut64 addr) { CORE_LOCK(); return rz_heap_chunk(core, addr); } QVector<RzHeapBin *> CutterCore::getHeapBins(ut64 arena_addr) { CORE_LOCK(); QVector<RzHeapBin *> bins_vector; MallocState *arena = rz_heap_get_arena(core, arena_addr); if (!arena) { return bins_vector; } // get small, large, unsorted bins for (int i = 0; i <= NBINS - 2; i++) { RzHeapBin *bin = rz_heap_bin_content(core, arena, i, arena_addr); if (!bin) { continue; } if (!rz_list_length(bin->chunks)) { rz_heap_bin_free_64(bin); continue; } bins_vector.append(bin); } // get fastbins for (int i = 0; i < 10; i++) { RzHeapBin *bin = rz_heap_fastbin_content(core, arena, i); if (!bin) { continue; } if (!rz_list_length(bin->chunks)) { rz_heap_bin_free_64(bin); continue; } bins_vector.append(bin); } // get tcache bins RzList *tcache_bins = rz_heap_tcache_content(core, arena_addr); RzListIter *iter; RzHeapBin *bin; CutterRzListForeach (tcache_bins, iter, RzHeapBin, bin) { if (!bin) { continue; } if (!rz_list_length(bin->chunks)) { rz_heap_bin_free_64(bin); continue; } bins_vector.append(bin); } return bins_vector; } bool CutterCore::writeHeapChunk(RzHeapChunkSimple *chunk_simple) { CORE_LOCK(); return rz_heap_write_chunk(core, chunk_simple); } QList<VariableDescription> CutterCore::getVariables(RVA at) { QList<VariableDescription> ret; CORE_LOCK(); RzAnalysisFunction *fcn = functionIn(at); if (!fcn) { return ret; } for (auto var : CutterPVector<RzAnalysisVar>(&fcn->vars)) { VariableDescription desc; desc.storageType = var->storage.type; if (!var->name || !var->type) { continue; } desc.name = QString::fromUtf8(var->name); char *tn = rz_type_as_string(core->analysis->typedb, var->type); if (!tn) { continue; } desc.type = QString::fromUtf8(tn); rz_mem_free(tn); if (char *v = rz_core_analysis_var_display(core, var, false)) { desc.value = QString::fromUtf8(v).trimmed(); rz_mem_free(v); } ret.push_back(desc); } return ret; } QList<GlobalDescription> CutterCore::getAllGlobals() { CORE_LOCK(); RzListIter *it; QList<GlobalDescription> ret; RzAnalysisVarGlobal *glob; if (core && core->analysis && core->analysis->typedb) { const RzList *globals = rz_analysis_var_global_get_all(core->analysis); CutterRzListForeach (globals, it, RzAnalysisVarGlobal, glob) { const char *gtype = rz_type_as_string(core->analysis->typedb, glob->type); if (!gtype) { continue; } GlobalDescription global; global.addr = glob->addr; global.name = QString(glob->name); global.type = QString(gtype); ret << global; } } return ret; } QVector<RegisterRefValueDescription> CutterCore::getRegisterRefValues() { QVector<RegisterRefValueDescription> result; CORE_LOCK(); RzList *ritems = rz_core_reg_filter_items_sync(core, getReg(), reg_sync, nullptr); if (!ritems) { return result; } RzListIter *it; RzRegItem *ri; CutterRzListForeach (ritems, it, RzRegItem, ri) { RegisterRefValueDescription desc; desc.name = ri->name; ut64 value = rz_reg_get_value(getReg(), ri); desc.value = "0x" + QString::number(value, 16); desc.ref = rz_core_analysis_hasrefs(core, value, true); result.push_back(desc); } rz_list_free(ritems); return result; } QString CutterCore::getRegisterName(QString registerRole) { if (!currentlyDebugging) { return ""; } CORE_LOCK(); return rz_reg_get_name_by_type(getReg(), registerRole.toUtf8().constData()); } RVA CutterCore::getProgramCounterValue() { if (currentlyDebugging) { CORE_LOCK(); return rz_core_reg_getv_by_role_or_name(core, "PC"); } return RVA_INVALID; } void CutterCore::setRegister(QString regName, QString regValue) { if (!currentlyDebugging) { return; } CORE_LOCK(); ut64 val = rz_num_math(core->num, regValue.toUtf8().constData()); rz_core_reg_assign_sync(core, getReg(), reg_sync, regName.toUtf8().constData(), val); emit registersChanged(); emit refreshCodeViews(); } void CutterCore::setCurrentDebugThread(int tid) { if (!asyncTask( [=](RzCore *core) { rz_debug_select(core->dbg, core->dbg->pid, tid); return (void *)NULL; }, debugTask)) { return; } emit debugTaskStateChanged(); connect(debugTask.data(), &RizinTask::finished, this, [this]() { debugTask.clear(); emit registersChanged(); emit refreshCodeViews(); emit stackChanged(); syncAndSeekProgramCounter(); emit switchedThread(); emit debugTaskStateChanged(); }); debugTask->startTask(); } void CutterCore::setCurrentDebugProcess(int pid) { if (!currentlyDebugging || !asyncTask( [=](RzCore *core) { rz_debug_select(core->dbg, pid, core->dbg->tid); core->dbg->main_pid = pid; return (void *)NULL; }, debugTask)) { return; } emit debugTaskStateChanged(); connect(debugTask.data(), &RizinTask::finished, this, [this]() { debugTask.clear(); emit registersChanged(); emit refreshCodeViews(); emit stackChanged(); emit flagsChanged(); syncAndSeekProgramCounter(); emit switchedProcess(); emit debugTaskStateChanged(); }); debugTask->startTask(); } void CutterCore::startDebug() { if (!currentlyDebugging) { offsetPriorDebugging = getOffset(); } currentlyOpenFile = getConfig("file.path"); if (!asyncTask( [](RzCore *core) { rz_core_file_reopen_debug(core, ""); return nullptr; }, debugTask)) { return; } emit debugTaskStateChanged(); connect(debugTask.data(), &RizinTask::finished, this, [this]() { delete debugTaskDialog; debugTask.clear(); emit registersChanged(); if (!currentlyDebugging) { setConfig("asm.flags", false); currentlyDebugging = true; emit toggleDebugView(); emit refreshCodeViews(); } emit codeRebased(); emit stackChanged(); emit debugTaskStateChanged(); }); debugTaskDialog = new RizinTaskDialog(debugTask); debugTaskDialog->setBreakOnClose(true); debugTaskDialog->setAttribute(Qt::WA_DeleteOnClose); debugTaskDialog->setDesc(tr("Starting native debug...")); debugTaskDialog->show(); debugTask->startTask(); } void CutterCore::startEmulation() { if (!currentlyDebugging) { offsetPriorDebugging = getOffset(); } // clear registers, init esil state, stack, progcounter at current seek asyncTask( [&](RzCore *core) { rz_core_analysis_esil_reinit(core); rz_core_analysis_esil_init_mem(core, NULL, UT64_MAX, UT32_MAX); rz_core_analysis_esil_init_regs(core); return nullptr; }, debugTask); emit debugTaskStateChanged(); connect(debugTask.data(), &RizinTask::finished, this, [this]() { delete debugTaskDialog; debugTask.clear(); if (!currentlyDebugging || !currentlyEmulating) { // prevent register flags from appearing during debug/emul setConfig("asm.flags", false); // allows to view self-modifying code changes or other binary changes setConfig("io.cache", true); currentlyDebugging = true; currentlyEmulating = true; emit toggleDebugView(); } emit registersChanged(); emit stackChanged(); emit codeRebased(); emit refreshCodeViews(); emit debugTaskStateChanged(); }); debugTaskDialog = new RizinTaskDialog(debugTask); debugTaskDialog->setBreakOnClose(true); debugTaskDialog->setAttribute(Qt::WA_DeleteOnClose); debugTaskDialog->setDesc(tr("Starting emulation...")); debugTaskDialog->show(); debugTask->startTask(); } void CutterCore::attachRemote(const QString &uri) { if (!currentlyDebugging) { offsetPriorDebugging = getOffset(); } // connect to a debugger with the given plugin if (!asyncTask( [&](RzCore *core) { setConfig("cfg.debug", true); rz_core_file_reopen_remote_debug(core, uri.toStdString().c_str(), 0); return nullptr; }, debugTask)) { return; } emit debugTaskStateChanged(); connect(debugTask.data(), &RizinTask::finished, this, [this, uri]() { delete debugTaskDialog; debugTask.clear(); // Check if we actually connected bool connected = false; RzCoreLocked core(Core()); RzList *descs = rz_id_storage_list(core->io->files); RzListIter *it; RzIODesc *desc; CutterRzListForeach (descs, it, RzIODesc, desc) { QString fileUri = QString(desc->uri); if (!fileUri.compare(uri)) { connected = true; } } seekAndShow(getProgramCounterValue()); if (!connected) { emit attachedRemote(false); emit debugTaskStateChanged(); return; } emit registersChanged(); if (!currentlyDebugging || !currentlyEmulating) { // prevent register flags from appearing during debug/emul setConfig("asm.flags", false); currentlyDebugging = true; emit toggleDebugView(); } currentlyRemoteDebugging = true; emit codeRebased(); emit attachedRemote(true); emit debugTaskStateChanged(); }); debugTaskDialog = new RizinTaskDialog(debugTask); debugTaskDialog->setBreakOnClose(true); debugTaskDialog->setAttribute(Qt::WA_DeleteOnClose); debugTaskDialog->setDesc(tr("Connecting to: ") + uri); debugTaskDialog->show(); debugTask->startTask(); } void CutterCore::attachDebug(int pid) { if (!currentlyDebugging) { offsetPriorDebugging = getOffset(); } if (!asyncTask( [&](RzCore *core) { // cannot use setConfig because core is // already locked, which causes a deadlock rz_config_set_b(core->config, "cfg.debug", true); auto uri = rz_str_newf("dbg://%d", pid); if (currentlyOpenFile.isEmpty()) { rz_core_file_open_load(core, uri, 0, RZ_PERM_R, false); } else { rz_core_file_reopen_remote_debug(core, uri, 0); } free(uri); return nullptr; }, debugTask)) { return; } emit debugTaskStateChanged(); connect(debugTask.data(), &RizinTask::finished, this, [this, pid]() { delete debugTaskDialog; debugTask.clear(); syncAndSeekProgramCounter(); if (!currentlyDebugging || !currentlyEmulating) { // prevent register flags from appearing during debug/emul setConfig("asm.flags", false); currentlyDebugging = true; currentlyOpenFile = getConfig("file.path"); currentlyAttachedToPID = pid; emit toggleDebugView(); } emit codeRebased(); emit debugTaskStateChanged(); }); debugTaskDialog = new RizinTaskDialog(debugTask); debugTaskDialog->setBreakOnClose(true); debugTaskDialog->setAttribute(Qt::WA_DeleteOnClose); debugTaskDialog->setDesc(tr("Attaching to process (") + QString::number(pid) + ")..."); debugTaskDialog->show(); debugTask->startTask(); } void CutterCore::suspendDebug() { debugTask->breakTask(); debugTask->joinTask(); } void CutterCore::stopDebug() { if (!currentlyDebugging) { return; } if (!debugTask.isNull()) { suspendDebug(); } currentlyDebugging = false; currentlyTracing = false; currentlyRemoteDebugging = false; emit debugTaskStateChanged(); CORE_LOCK(); if (currentlyEmulating) { rz_core_analysis_esil_init_mem_del(core, NULL, UT64_MAX, UT32_MAX); rz_core_analysis_esil_deinit(core); resetWriteCache(); rz_core_debug_clear_register_flags(core); rz_core_analysis_esil_trace_stop(core); currentlyEmulating = false; } else { // ensure we have opened a file. if (core->io->desc) { rz_core_debug_process_close(core); } currentlyAttachedToPID = -1; } syncAndSeekProgramCounter(); setConfig("asm.flags", true); setConfig("io.cache", false); emit codeRebased(); emit toggleDebugView(); offsetPriorDebugging = getOffset(); emit debugTaskStateChanged(); } void CutterCore::syncAndSeekProgramCounter() { seekAndShow(getProgramCounterValue()); emit registersChanged(); } void CutterCore::continueDebug() { if (!currentlyDebugging) { return; } if (currentlyEmulating) { if (!asyncTask( [](RzCore *core) { rz_core_esil_step(core, UT64_MAX, "0", NULL, false); rz_core_reg_update_flags(core); return nullptr; }, debugTask)) { return; } } else { if (!asyncTask( [](RzCore *core) { rz_debug_continue(core->dbg); return nullptr; }, debugTask)) { return; } } emit debugTaskStateChanged(); connect(debugTask.data(), &RizinTask::finished, this, [this]() { debugTask.clear(); syncAndSeekProgramCounter(); emit refreshCodeViews(); emit debugTaskStateChanged(); }); debugTask->startTask(); } void CutterCore::continueBackDebug() { if (!currentlyDebugging) { return; } if (currentlyEmulating) { if (!asyncTask( [](RzCore *core) { rz_core_esil_continue_back(core); rz_core_reg_update_flags(core); return nullptr; }, debugTask)) { return; } } else { if (!asyncTask( [](RzCore *core) { rz_debug_continue_back(core->dbg); return nullptr; }, debugTask)) { return; } } emit debugTaskStateChanged(); connect(debugTask.data(), &RizinTask::finished, this, [this]() { debugTask.clear(); syncAndSeekProgramCounter(); emit refreshCodeViews(); emit debugTaskStateChanged(); }); debugTask->startTask(); } void CutterCore::continueUntilDebug(ut64 offset) { if (!currentlyDebugging) { return; } if (currentlyEmulating) { if (!asyncTask( [=](RzCore *core) { rz_core_esil_step(core, offset, NULL, NULL, false); rz_core_reg_update_flags(core); return nullptr; }, debugTask)) { return; } } else { if (!asyncTask( [=](RzCore *core) { rz_core_debug_continue_until(core, offset, offset); return nullptr; }, debugTask)) { return; } } emit debugTaskStateChanged(); connect(debugTask.data(), &RizinTask::finished, this, [this]() { debugTask.clear(); syncAndSeekProgramCounter(); emit refreshCodeViews(); emit debugTaskStateChanged(); }); debugTask->startTask(); } void CutterCore::continueUntilCall() { if (!currentlyDebugging) { return; } if (currentlyEmulating) { if (!asyncTask( [](RzCore *core) { rz_core_analysis_continue_until_call(core); return nullptr; }, debugTask)) { return; } } else { if (!asyncTask( [](RzCore *core) { rz_core_debug_step_one(core, 0); return nullptr; }, debugTask)) { return; } } emit debugTaskStateChanged(); connect(debugTask.data(), &RizinTask::finished, this, [this]() { debugTask.clear(); syncAndSeekProgramCounter(); emit refreshCodeViews(); emit debugTaskStateChanged(); }); debugTask->startTask(); } void CutterCore::continueUntilSyscall() { if (!currentlyDebugging) { return; } if (currentlyEmulating) { if (!asyncTask( [](RzCore *core) { rz_core_analysis_continue_until_syscall(core); return nullptr; }, debugTask)) { return; } } else { if (!asyncTask( [](RzCore *core) { rz_cons_break_push( [](void *x) { rz_debug_stop(reinterpret_cast<RzDebug *>(x)); }, core->dbg); rz_reg_arena_swap(core->dbg->reg, true); rz_debug_continue_syscalls(core->dbg, NULL, 0); rz_cons_break_pop(); rz_core_dbg_follow_seek_register(core); return nullptr; }, debugTask)) { return; } } emit debugTaskStateChanged(); connect(debugTask.data(), &RizinTask::finished, this, [this]() { debugTask.clear(); syncAndSeekProgramCounter(); emit refreshCodeViews(); emit debugTaskStateChanged(); }); debugTask->startTask(); } void CutterCore::stepDebug() { if (!currentlyDebugging) { return; } if (currentlyEmulating) { if (!asyncTask( [](RzCore *core) { rz_core_esil_step(core, UT64_MAX, NULL, NULL, false); rz_core_reg_update_flags(core); return nullptr; }, debugTask)) { return; } } else { if (!asyncTask( [](RzCore *core) { rz_core_debug_step_one(core, 1); return nullptr; }, debugTask)) { return; } } emit debugTaskStateChanged(); connect(debugTask.data(), &RizinTask::finished, this, [this]() { debugTask.clear(); syncAndSeekProgramCounter(); emit refreshCodeViews(); emit debugTaskStateChanged(); }); debugTask->startTask(); } void CutterCore::stepOverDebug() { if (!currentlyDebugging) { return; } if (currentlyEmulating) { if (!asyncTask( [&](RzCore *core) { rz_core_analysis_esil_step_over(core); return nullptr; }, debugTask)) { return; } } else { bool ret; asyncTask( [&](RzCore *core) { ret = rz_core_debug_step_over(core, 1); rz_core_dbg_follow_seek_register(core); return nullptr; }, debugTask); if (!ret) { return; } } emit debugTaskStateChanged(); connect(debugTask.data(), &RizinTask::finished, this, [this]() { debugTask.clear(); syncAndSeekProgramCounter(); emit refreshCodeViews(); emit debugTaskStateChanged(); }); debugTask->startTask(); } void CutterCore::stepOutDebug() { if (!currentlyDebugging) { return; } emit debugTaskStateChanged(); bool ret; asyncTask( [&](RzCore *core) { ret = rz_core_debug_step_until_frame(core); rz_core_dbg_follow_seek_register(core); return nullptr; }, debugTask); if (!ret) { return; } connect(debugTask.data(), &RizinTask::finished, this, [this]() { debugTask.clear(); syncAndSeekProgramCounter(); emit refreshCodeViews(); emit debugTaskStateChanged(); }); debugTask->startTask(); } void CutterCore::stepBackDebug() { if (!currentlyDebugging) { return; } if (currentlyEmulating) { if (!asyncTask( [](RzCore *core) { rz_core_esil_step_back(core); rz_core_reg_update_flags(core); return nullptr; }, debugTask)) { return; } } else { bool ret; asyncTask( [&](RzCore *core) { ret = rz_core_debug_step_back(core, 1); rz_core_dbg_follow_seek_register(core); return nullptr; }, debugTask); if (!ret) { return; } } emit debugTaskStateChanged(); connect(debugTask.data(), &RizinTask::finished, this, [this]() { debugTask.clear(); syncAndSeekProgramCounter(); emit refreshCodeViews(); emit debugTaskStateChanged(); }); debugTask->startTask(); } QStringList CutterCore::getDebugPlugins() { QStringList plugins; RzListIter *iter; RzDebugPlugin *plugin; CORE_LOCK(); CutterRzListForeach (core->dbg->plugins, iter, RzDebugPlugin, plugin) { plugins << plugin->name; } return plugins; } QString CutterCore::getActiveDebugPlugin() { return getConfig("dbg.backend"); } void CutterCore::setDebugPlugin(QString plugin) { setConfig("dbg.backend", plugin); } void CutterCore::startTraceSession() { if (!currentlyDebugging || currentlyTracing) { return; } if (currentlyEmulating) { if (!asyncTask( [](RzCore *core) { rz_core_analysis_esil_trace_start(core); return nullptr; }, debugTask)) { return; } } else { if (!asyncTask( [](RzCore *core) { core->dbg->session = rz_debug_session_new(); rz_debug_add_checkpoint(core->dbg); return nullptr; }, debugTask)) { return; } } emit debugTaskStateChanged(); connect(debugTask.data(), &RizinTask::finished, this, [this]() { delete debugTaskDialog; debugTask.clear(); currentlyTracing = true; emit debugTaskStateChanged(); }); debugTaskDialog = new RizinTaskDialog(debugTask); debugTaskDialog->setBreakOnClose(true); debugTaskDialog->setAttribute(Qt::WA_DeleteOnClose); debugTaskDialog->setDesc(tr("Creating debug tracepoint...")); debugTaskDialog->show(); debugTask->startTask(); } void CutterCore::stopTraceSession() { if (!currentlyDebugging || !currentlyTracing) { return; } if (currentlyEmulating) { if (!asyncTask( [](RzCore *core) { rz_core_analysis_esil_trace_stop(core); return nullptr; }, debugTask)) { return; } } else { if (!asyncTask( [](RzCore *core) { rz_debug_session_free(core->dbg->session); core->dbg->session = NULL; return nullptr; }, debugTask)) { return; } } emit debugTaskStateChanged(); connect(debugTask.data(), &RizinTask::finished, this, [this]() { delete debugTaskDialog; debugTask.clear(); currentlyTracing = false; emit debugTaskStateChanged(); }); debugTaskDialog = new RizinTaskDialog(debugTask); debugTaskDialog->setBreakOnClose(true); debugTaskDialog->setAttribute(Qt::WA_DeleteOnClose); debugTaskDialog->setDesc(tr("Stopping debug session...")); debugTaskDialog->show(); debugTask->startTask(); } void CutterCore::toggleBreakpoint(RVA addr) { CORE_LOCK(); rz_core_debug_breakpoint_toggle(core, addr); emit breakpointsChanged(addr); } void CutterCore::addBreakpoint(const BreakpointDescription &config) { CORE_LOCK(); RzBreakpointItem *breakpoint = nullptr; int watchpoint_prot = 0; if (config.hw) { watchpoint_prot = config.permission & ~(RZ_PERM_X); } auto address = config.addr; char *module = nullptr; QByteArray moduleNameData; if (config.type == BreakpointDescription::Named) { address = Core()->math(config.positionExpression); } else if (config.type == BreakpointDescription::Module) { address = 0; moduleNameData = config.positionExpression.toUtf8(); module = moduleNameData.data(); } breakpoint = rz_debug_bp_add(core->dbg, address, config.size, config.hw, (watchpoint_prot != 0), watchpoint_prot, module, config.moduleDelta); if (!breakpoint) { QMessageBox::critical(nullptr, tr("Breakpoint error"), tr("Failed to create breakpoint")); return; } if (config.type == BreakpointDescription::Named) { updateOwnedCharPtr(breakpoint->expr, config.positionExpression); } if (config.hw) { breakpoint->size = config.size; } if (config.type == BreakpointDescription::Named) { updateOwnedCharPtr(breakpoint->name, config.positionExpression); } int index = std::find(core->dbg->bp->bps_idx, core->dbg->bp->bps_idx + core->dbg->bp->bps_idx_count, breakpoint) - core->dbg->bp->bps_idx; breakpoint->enabled = config.enabled; if (config.trace) { setBreakpointTrace(index, config.trace); } if (!config.condition.isEmpty()) { updateOwnedCharPtr(breakpoint->cond, config.condition); } if (!config.command.isEmpty()) { updateOwnedCharPtr(breakpoint->data, config.command); } emit breakpointsChanged(breakpoint->addr); } void CutterCore::updateBreakpoint(int index, const BreakpointDescription &config) { CORE_LOCK(); if (auto bp = rz_bp_get_index(core->dbg->bp, index)) { rz_bp_del(core->dbg->bp, bp->addr); } // Delete by index currently buggy, // required for breakpoints with non address based position // rz_bp_del_index(core->dbg->bp, index); addBreakpoint(config); } void CutterCore::delBreakpoint(RVA addr) { CORE_LOCK(); rz_bp_del(core->dbg->bp, addr); emit breakpointsChanged(addr); } void CutterCore::delAllBreakpoints() { CORE_LOCK(); rz_bp_del_all(core->dbg->bp); emit refreshCodeViews(); } void CutterCore::enableBreakpoint(RVA addr) { CORE_LOCK(); rz_bp_enable(core->dbg->bp, addr, true, 1); emit breakpointsChanged(addr); } void CutterCore::disableBreakpoint(RVA addr) { CORE_LOCK(); rz_bp_enable(core->dbg->bp, addr, false, 1); emit breakpointsChanged(addr); } void CutterCore::setBreakpointTrace(int index, bool enabled) { CORE_LOCK(); RzBreakpointItem *bpi = rz_bp_get_index(core->dbg->bp, index); bpi->trace = enabled; } static BreakpointDescription breakpointDescriptionFromRizin(int index, rz_bp_item_t *bpi) { BreakpointDescription bp; bp.addr = bpi->addr; bp.index = index; bp.size = bpi->size; if (bpi->expr) { bp.positionExpression = bpi->expr; bp.type = BreakpointDescription::Named; } bp.name = bpi->name; bp.permission = bpi->perm; bp.command = bpi->data; bp.condition = bpi->cond; bp.hw = bpi->hw; bp.trace = bpi->trace; bp.enabled = bpi->enabled; return bp; } int CutterCore::breakpointIndexAt(RVA addr) { CORE_LOCK(); return rz_bp_get_index_at(core->dbg->bp, addr); } BreakpointDescription CutterCore::getBreakpointAt(RVA addr) { CORE_LOCK(); int index = rz_bp_get_index_at(core->dbg->bp, addr); auto bp = rz_bp_get_index(core->dbg->bp, index); if (bp) { return breakpointDescriptionFromRizin(index, bp); } return BreakpointDescription(); } QList<BreakpointDescription> CutterCore::getBreakpoints() { CORE_LOCK(); QList<BreakpointDescription> ret; // TODO: use higher level API, don't touch rizin bps_idx directly for (int i = 0; i < core->dbg->bp->bps_idx_count; i++) { if (auto bpi = core->dbg->bp->bps_idx[i]) { ret.push_back(breakpointDescriptionFromRizin(i, bpi)); } } return ret; } QList<RVA> CutterCore::getBreakpointsAddresses() { QList<RVA> bpAddresses; for (const BreakpointDescription &bp : getBreakpoints()) { bpAddresses << bp.addr; } return bpAddresses; } QList<RVA> CutterCore::getBreakpointsInFunction(RVA funcAddr) { QList<RVA> allBreakpoints = getBreakpointsAddresses(); QList<RVA> functionBreakpoints; // Use std manipulations to take only the breakpoints that belong to this function std::copy_if(allBreakpoints.begin(), allBreakpoints.end(), std::back_inserter(functionBreakpoints), [this, funcAddr](RVA BPadd) { return getFunctionStart(BPadd) == funcAddr; }); return functionBreakpoints; } bool CutterCore::isBreakpoint(const QList<RVA> &breakpoints, RVA addr) { return breakpoints.contains(addr); } QList<ProcessDescription> CutterCore::getProcessThreads(int pid = -1) { CORE_LOCK(); RzList *list = rz_debug_pids(core->dbg, pid != -1 ? pid : core->dbg->pid); RzListIter *iter; RzDebugPid *p; QList<ProcessDescription> ret; CutterRzListForeach (list, iter, RzDebugPid, p) { ProcessDescription proc; proc.current = core->dbg->pid == p->pid; proc.ppid = p->ppid; proc.pid = p->pid; proc.uid = p->uid; proc.status = static_cast<RzDebugPidState>(p->status); proc.path = p->path; ret << proc; } rz_list_free(list); return ret; } QList<ProcessDescription> CutterCore::getAllProcesses() { return getProcessThreads(0); } QList<MemoryMapDescription> CutterCore::getMemoryMap() { CORE_LOCK(); RzList *list0 = rz_debug_map_list(core->dbg, false); RzList *list1 = rz_debug_map_list(core->dbg, true); rz_list_join(list0, list1); QList<MemoryMapDescription> ret; RzListIter *it; RzDebugMap *map; CutterRzListForeach (list0, it, RzDebugMap, map) { MemoryMapDescription memMap; memMap.name = map->name; memMap.fileName = map->file; memMap.addrStart = map->addr; memMap.addrEnd = map->addr_end; memMap.type = map->user ? "u" : "s"; memMap.permission = rz_str_rwx_i(map->perm); ret << memMap; } return ret; } void CutterCore::setGraphEmpty(bool empty) { emptyGraph = empty; } bool CutterCore::isGraphEmpty() { return emptyGraph; } void CutterCore::getRegs() { CORE_LOCK(); this->regs = {}; const RzList *rs = rz_reg_get_list(getReg(), RZ_REG_TYPE_ANY); if (!rs) { return; } for (const auto &r : CutterRzList<RzRegItem>(rs)) { this->regs.push_back(r->name); } } void CutterCore::setSettings() { setConfig("scr.interactive", false); setConfig("hex.pairs", false); setConfig("asm.xrefs", false); setConfig("asm.tabs.once", true); setConfig("asm.flags.middle", 2); setConfig("analysis.hasnext", false); setConfig("asm.lines.call", false); // Colors setConfig("scr.color", COLOR_MODE_DISABLED); // Don't show hits setConfig("search.flags", false); } QList<RVA> CutterCore::getSeekHistory() { CORE_LOCK(); QList<RVA> ret; RzListIter *it; RzCoreSeekItem *undo; RzList *list = rz_core_seek_list(core); CutterRzListForeach (list, it, RzCoreSeekItem, undo) { ret << undo->offset; } return ret; } QStringList CutterCore::getAsmPluginNames() { CORE_LOCK(); RzListIter *it; QStringList ret; RzAsmPlugin *ap; CutterRzListForeach (core->rasm->plugins, it, RzAsmPlugin, ap) { ret << ap->name; } return ret; } QStringList CutterCore::getAnalysisPluginNames() { CORE_LOCK(); RzListIter *it; QStringList ret; RzAnalysisPlugin *ap; CutterRzListForeach (core->analysis->plugins, it, RzAnalysisPlugin, ap) { ret << ap->name; } return ret; } QList<RzBinPluginDescription> CutterCore::getBinPluginDescriptions(bool bin, bool xtr) { CORE_LOCK(); QList<RzBinPluginDescription> ret; RzListIter *it; if (bin) { RzBinPlugin *bp; CutterRzListForeach (core->bin->plugins, it, RzBinPlugin, bp) { RzBinPluginDescription desc; desc.name = bp->name ? bp->name : ""; desc.description = bp->desc ? bp->desc : ""; desc.license = bp->license ? bp->license : ""; desc.type = "bin"; ret.append(desc); } } if (xtr) { RzBinXtrPlugin *bx; CutterRzListForeach (core->bin->binxtrs, it, RzBinXtrPlugin, bx) { RzBinPluginDescription desc; desc.name = bx->name ? bx->name : ""; desc.description = bx->desc ? bx->desc : ""; desc.license = bx->license ? bx->license : ""; desc.type = "xtr"; ret.append(desc); } } return ret; } QList<RzIOPluginDescription> CutterCore::getRIOPluginDescriptions() { CORE_LOCK(); QList<RzIOPluginDescription> ret; RzListIter *it; RzIOPlugin *p; CutterRzListForeach (core->io->plugins, it, RzIOPlugin, p) { RzIOPluginDescription desc; desc.name = p->name ? p->name : ""; desc.description = p->desc ? p->desc : ""; desc.license = p->license ? p->license : ""; desc.permissions = QString("r") + (p->write ? "w" : "_") + (p->isdbg ? "d" : "_"); if (p->uris) { desc.uris = QString::fromUtf8(p->uris).split(","); } ret.append(desc); } return ret; } QList<RzCorePluginDescription> CutterCore::getRCorePluginDescriptions() { CORE_LOCK(); QList<RzCorePluginDescription> ret; RzListIter *it; RzCorePlugin *p; CutterRzListForeach (core->plugins, it, RzCorePlugin, p) { RzCorePluginDescription desc; desc.name = p->name ? p->name : ""; desc.description = p->desc ? p->desc : ""; desc.license = p->license ? p->license : ""; ret.append(desc); } return ret; } QList<RzAsmPluginDescription> CutterCore::getRAsmPluginDescriptions() { CORE_LOCK(); RzListIter *it; QList<RzAsmPluginDescription> ret; RzAsmPlugin *ap; CutterRzListForeach (core->rasm->plugins, it, RzAsmPlugin, ap) { RzAsmPluginDescription plugin; plugin.name = ap->name; plugin.architecture = ap->arch; plugin.author = ap->author; plugin.version = ap->version; plugin.cpus = ap->cpus; plugin.description = ap->desc; plugin.license = ap->license; ret << plugin; } return ret; } QList<FunctionDescription> CutterCore::getAllFunctions() { CORE_LOCK(); QList<FunctionDescription> funcList; funcList.reserve(rz_list_length(core->analysis->fcns)); RzListIter *iter; RzAnalysisFunction *fcn; CutterRzListForeach (core->analysis->fcns, iter, RzAnalysisFunction, fcn) { FunctionDescription function; function.offset = fcn->addr; function.linearSize = rz_analysis_function_linear_size(fcn); function.nargs = rz_analysis_arg_count(fcn); function.nlocals = rz_analysis_var_local_count(fcn); function.nbbs = rz_pvector_len(fcn->bbs); function.calltype = fcn->cc ? QString::fromUtf8(fcn->cc) : QString(); function.name = fcn->name ? QString::fromUtf8(fcn->name) : QString(); function.edges = rz_analysis_function_count_edges(fcn, nullptr); function.stackframe = fcn->maxstack; funcList.append(function); } return funcList; } static inline uint64_t rva(RzBinObject *o, uint64_t paddr, uint64_t vaddr, int va) { return va ? rz_bin_object_get_vaddr(o, paddr, vaddr) : paddr; } QList<ImportDescription> CutterCore::getAllImports() { CORE_LOCK(); RzBinFile *bf = rz_bin_cur(core->bin); if (!bf) { return {}; } const RzPVector *imports = rz_bin_object_get_imports(bf->o); if (!imports) { return {}; } QList<ImportDescription> qList; bool va = core->io->va || core->bin->is_debugger; for (const auto &import : CutterPVector<RzBinImport>(imports)) { if (RZ_STR_ISEMPTY(import->name)) { continue; } ImportDescription importDescription; RzBinSymbol *sym = rz_bin_object_get_symbol_of_import(bf->o, import); ut64 addr = sym ? rva(bf->o, sym->paddr, sym->vaddr, va) : UT64_MAX; QString name { import->name }; if (RZ_STR_ISNOTEMPTY(import->classname)) { name = QString("%1.%2").arg(import->classname, import->name); } if (core->bin->prefix) { name = QString("%1.%2").arg(core->bin->prefix, name); } importDescription.ordinal = (int)import->ordinal; importDescription.bind = import->bind; importDescription.type = import->type; importDescription.libname = import->libname; importDescription.name = name; importDescription.plt = addr; qList << importDescription; } return qList; } QList<ExportDescription> CutterCore::getAllExports() { CORE_LOCK(); RzBinFile *bf = rz_bin_cur(core->bin); if (!bf) { return {}; } const RzPVector *symbols = rz_bin_object_get_symbols(bf->o); if (!symbols) { return {}; } bool va = core->io->va || core->bin->is_debugger; bool demangle = rz_config_get_b(core->config, "bin.demangle"); QList<ExportDescription> ret; for (const auto &symbol : CutterPVector<RzBinSymbol>(symbols)) { if (!(symbol->name && rz_core_sym_is_export(symbol))) { continue; } RzBinSymNames sn = {}; rz_core_sym_name_init(&sn, symbol, demangle); ExportDescription exportDescription; exportDescription.vaddr = rva(bf->o, symbol->paddr, symbol->vaddr, va); exportDescription.paddr = symbol->paddr; exportDescription.size = symbol->size; exportDescription.type = symbol->type; exportDescription.name = sn.symbolname; exportDescription.flag_name = sn.nameflag; ret << exportDescription; rz_core_sym_name_fini(&sn); } return ret; } QList<SymbolDescription> CutterCore::getAllSymbols() { CORE_LOCK(); RzBinFile *bf = rz_bin_cur(core->bin); if (!bf) { return {}; } QList<SymbolDescription> ret; const RzPVector *symbols = rz_bin_object_get_symbols(bf->o); if (symbols) { for (const auto &bs : CutterPVector<RzBinSymbol>(symbols)) { QString type = QString(bs->bind) + " " + QString(bs->type); SymbolDescription symbol; symbol.vaddr = bs->vaddr; symbol.name = QString(bs->name); symbol.bind = QString(bs->bind); symbol.type = QString(bs->type); ret << symbol; } } const RzPVector *entries = rz_bin_object_get_entries(bf->o); if (symbols) { /* list entrypoints as symbols too */ int n = 0; for (const auto &entry : CutterPVector<RzBinAddr>(entries)) { SymbolDescription symbol; symbol.vaddr = entry->vaddr; symbol.name = QString("entry") + QString::number(n++); symbol.bind.clear(); symbol.type = "entry"; ret << symbol; } } return ret; } QList<HeaderDescription> CutterCore::getAllHeaders() { CORE_LOCK(); RzBinFile *bf = rz_bin_cur(core->bin); if (!bf) { return {}; } const RzPVector *fields = rz_bin_object_get_fields(bf->o); if (!fields) { return {}; } QList<HeaderDescription> ret; for (auto field : CutterPVector<RzBinField>(fields)) { HeaderDescription header; header.vaddr = field->vaddr; header.paddr = field->paddr; header.value = RZ_STR_ISEMPTY(field->comment) ? "" : field->comment; header.name = field->name; ret << header; } return ret; } QList<FlirtDescription> CutterCore::getSignaturesDB() { CORE_LOCK(); void *ptr = NULL; RzListIter *iter = NULL; QList<FlirtDescription> sigdb; RzList *list = rz_core_analysis_sigdb_list(core, true); rz_list_foreach(list, iter, ptr) { RzSigDBEntry *sig = static_cast<RzSigDBEntry *>(ptr); FlirtDescription flirt; flirt.bin_name = sig->bin_name; flirt.arch_name = sig->arch_name; flirt.base_name = sig->base_name; flirt.short_path = sig->short_path; flirt.file_path = sig->file_path; flirt.details = sig->details; flirt.n_modules = QString::number(sig->n_modules); flirt.arch_bits = QString::number(sig->arch_bits); sigdb << flirt; } rz_list_free(list); return sigdb; } QList<CommentDescription> CutterCore::getAllComments(const QString &filterType) { CORE_LOCK(); QList<CommentDescription> qList; RzIntervalTreeIter it; void *pVoid; RzAnalysisMetaItem *item; RzSpace *spaces = rz_spaces_current(&core->analysis->meta_spaces); rz_interval_tree_foreach(&core->analysis->meta, it, pVoid) { item = reinterpret_cast<RzAnalysisMetaItem *>(pVoid); if (item->type != RZ_META_TYPE_COMMENT) { continue; } if (spaces && spaces != item->space) { continue; } if (filterType != rz_meta_type_to_string(item->type)) { continue; } RzIntervalNode *node = rz_interval_tree_iter_get(&it); CommentDescription comment; comment.offset = node->start; comment.name = fromOwnedCharPtr(rz_str_escape(item->str)); qList << comment; } return qList; } QList<RelocDescription> CutterCore::getAllRelocs() { CORE_LOCK(); QList<RelocDescription> ret; if (core && core->bin && core->bin->cur && core->bin->cur->o) { auto relocs = rz_bin_object_patch_relocs(core->bin->cur, core->bin->cur->o); if (!relocs) { return ret; } for (size_t i = 0; i < relocs->relocs_count; i++) { RzBinReloc *reloc = relocs->relocs[i]; RelocDescription desc; desc.vaddr = reloc->vaddr; desc.paddr = reloc->paddr; desc.type = (reloc->additive ? "ADD_" : "SET_") + QString::number(reloc->type); if (reloc->import) desc.name = reloc->import->name; else desc.name = QString("reloc_%1").arg(QString::number(reloc->vaddr, 16)); ret << desc; } } return ret; } QList<StringDescription> CutterCore::getAllStrings() { CORE_LOCK(); RzBinFile *bf = rz_bin_cur(core->bin); if (!bf) { return {}; } RzBinObject *obj = rz_bin_cur_object(core->bin); if (!obj) { return {}; } RzPVector *strings = rz_core_bin_whole_strings(core, bf); if (!strings) { return {}; } int va = core->io->va || core->bin->is_debugger; RzStrEscOptions opt = {}; opt.show_asciidot = false; opt.esc_bslash = true; opt.esc_double_quotes = true; QList<StringDescription> ret; for (const auto &str : CutterPVector<RzBinString>(strings)) { auto section = obj ? rz_bin_get_section_at(obj, str->paddr, 0) : NULL; StringDescription string; string.string = rz_str_escape_utf8_keep_printable(str->string, &opt); string.vaddr = obj ? rva(obj, str->paddr, str->vaddr, va) : str->paddr; string.type = rz_str_enc_as_string(str->type); string.size = str->size; string.length = str->length; string.section = section ? section->name : ""; ret << string; } return ret; } QList<FlagspaceDescription> CutterCore::getAllFlagspaces() { CORE_LOCK(); QList<FlagspaceDescription> flagspaces; RzSpaceIter it; RzSpace *space; rz_flag_space_foreach(core->flags, it, space) { FlagspaceDescription flagspace; flagspace.name = space->name; flagspaces << flagspace; } return flagspaces; } QList<FlagDescription> CutterCore::getAllFlags(QString flagspace) { CORE_LOCK(); QList<FlagDescription> flags; std::string name = flagspace.isEmpty() || flagspace.isNull() ? "*" : flagspace.toStdString(); RzSpace *space = rz_flag_space_get(core->flags, name.c_str()); rz_flag_foreach_space( core->flags, space, [](RzFlagItem *item, void *user) { FlagDescription flag; flag.offset = item->offset; flag.size = item->size; flag.name = item->name; flag.realname = item->name; reinterpret_cast<QList<FlagDescription> *>(user)->append(flag); return true; }, &flags); return flags; } QList<SectionDescription> CutterCore::getAllSections() { CORE_LOCK(); QList<SectionDescription> sections; RzBinObject *o = rz_bin_cur_object(core->bin); if (!o) { return sections; } RzPVector *sects = rz_bin_object_get_sections(o); if (!sects) { return sections; } RzList *hashnames = rz_list_newf(free); if (!hashnames) { return sections; } rz_list_push(hashnames, rz_str_dup("entropy")); for (const auto &sect : CutterPVector<RzBinSection>(sects)) { if (RZ_STR_ISEMPTY(sect->name)) continue; SectionDescription section; section.name = sect->name; section.vaddr = sect->vaddr; section.vsize = sect->vsize; section.paddr = sect->paddr; section.size = sect->size; section.perm = rz_str_rwx_i(sect->perm); if (sect->size > 0) { HtSS *digests = rz_core_bin_create_digests(core, sect->paddr, sect->size, hashnames); if (!digests) { continue; } const char *entropy = (const char *)ht_ss_find(digests, "entropy", NULL); section.entropy = rz_str_get(entropy); ht_ss_free(digests); } sections << section; } rz_pvector_free(sects); return sections; } QStringList CutterCore::getSectionList() { CORE_LOCK(); QStringList ret; RzBinObject *o = rz_bin_cur_object(core->bin); if (!o) { return ret; } RzPVector *sects = rz_bin_object_get_sections(o); if (!sects) { return ret; } for (const auto &sect : CutterPVector<RzBinSection>(sects)) { ret << sect->name; } rz_pvector_free(sects); return ret; } static inline QString perms_str(int perms) { return QString((perms & RZ_PERM_SHAR) ? 's' : '-') + rz_str_rwx_i(perms); } QList<SegmentDescription> CutterCore::getAllSegments() { CORE_LOCK(); RzBinFile *bf = rz_bin_cur(core->bin); if (!bf) { return {}; } RzPVector *segments = rz_bin_object_get_segments(bf->o); if (!segments) { return {}; } QList<SegmentDescription> ret; for (const auto &segment : CutterPVector<RzBinSection>(segments)) { SegmentDescription segDesc; segDesc.name = segment->name; segDesc.vaddr = segment->vaddr; segDesc.paddr = segment->paddr; segDesc.size = segment->size; segDesc.vsize = segment->vsize; segDesc.perm = perms_str(segment->perm); ret << segDesc; } rz_pvector_free(segments); return ret; } QList<EntrypointDescription> CutterCore::getAllEntrypoint() { CORE_LOCK(); RzBinFile *bf = rz_bin_cur(core->bin); if (!bf) { return {}; } bool va = core->io->va || core->bin->is_debugger; ut64 baddr = rz_bin_get_baddr(core->bin); ut64 laddr = rz_bin_get_laddr(core->bin); QList<EntrypointDescription> qList; const RzPVector *entries = rz_bin_object_get_entries(bf->o); for (const auto &entry : CutterPVector<RzBinAddr>(entries)) { if (entry->type != RZ_BIN_ENTRY_TYPE_PROGRAM) { continue; } const char *type = rz_bin_entry_type_string(entry->type); EntrypointDescription entrypointDescription; entrypointDescription.vaddr = rva(bf->o, entry->paddr, entry->vaddr, va); entrypointDescription.paddr = entry->paddr; entrypointDescription.baddr = baddr; entrypointDescription.laddr = laddr; entrypointDescription.haddr = entry->hpaddr ? entry->hpaddr : UT64_MAX; entrypointDescription.type = type ? type : "unknown"; qList << entrypointDescription; } return qList; } QList<BinClassDescription> CutterCore::getAllClassesFromBin() { CORE_LOCK(); RzBinFile *bf = rz_bin_cur(core->bin); if (!bf) { return {}; } const RzPVector *cs = rz_bin_object_get_classes(bf->o); if (!cs) { return {}; } QList<BinClassDescription> qList; RzListIter *iter2, *iter3; RzBinSymbol *sym; RzBinClassField *f; for (const auto &c : CutterPVector<RzBinClass>(cs)) { BinClassDescription classDescription; classDescription.name = c->name; classDescription.addr = c->addr; CutterRzListForeach (c->methods, iter2, RzBinSymbol, sym) { BinClassMethodDescription methodDescription; methodDescription.name = sym->name; methodDescription.addr = sym->vaddr; classDescription.methods << methodDescription; } CutterRzListForeach (c->fields, iter3, RzBinClassField, f) { BinClassFieldDescription fieldDescription; fieldDescription.name = f->name; fieldDescription.addr = f->vaddr; classDescription.fields << fieldDescription; } qList << classDescription; } return qList; } QList<BinClassDescription> CutterCore::getAllClassesFromFlags() { static const QRegularExpression classFlagRegExp("^class\\.(.*)$"); static const QRegularExpression methodFlagRegExp("^method\\.([^\\.]*)\\.(.*)$"); CORE_LOCK(); QList<BinClassDescription> ret; QMap<QString, BinClassDescription *> classesCache; for (const auto &item : getAllFlags("classes")) { QRegularExpressionMatch match = classFlagRegExp.match(item.name); if (match.hasMatch()) { QString className = match.captured(1); BinClassDescription *desc = nullptr; auto it = classesCache.find(className); if (it == classesCache.end()) { BinClassDescription cls = {}; ret << cls; desc = &ret.last(); classesCache[className] = desc; } else { desc = it.value(); } desc->name = match.captured(1); desc->addr = item.offset; continue; } match = methodFlagRegExp.match(item.name); if (match.hasMatch()) { QString className = match.captured(1); BinClassDescription *classDesc = nullptr; auto it = classesCache.find(className); if (it == classesCache.end()) { // add a new stub class, will be replaced if class flag comes after it BinClassDescription cls; cls.name = tr("Unknown (%1)").arg(className); cls.addr = RVA_INVALID; ret << cls; classDesc = &ret.last(); classesCache[className] = classDesc; } else { classDesc = it.value(); } BinClassMethodDescription meth; meth.name = match.captured(2); meth.addr = item.offset; classDesc->methods << meth; continue; } } return ret; } QList<QString> CutterCore::getAllAnalysisClasses(bool sorted) { CORE_LOCK(); QList<QString> ret; PVectorPtr l = makePVectorPtr(rz_analysis_class_get_all(core->analysis, sorted)); if (!l) { return ret; } ret.reserve(static_cast<int>(rz_pvector_len(l.get()))); for (const auto &kv : CutterPVector<SdbKv>(l.get())) { ret.append(QString::fromUtf8(reinterpret_cast<const char *>(kv->base.key))); } return ret; } QList<AnalysisMethodDescription> CutterCore::getAnalysisClassMethods(const QString &cls) { CORE_LOCK(); QList<AnalysisMethodDescription> ret; RzVector *meths = rz_analysis_class_method_get_all(core->analysis, cls.toUtf8().constData()); if (!meths) { return ret; } ret.reserve(static_cast<int>(meths->len)); RzAnalysisMethod *meth; CutterRzVectorForeach(meths, meth, RzAnalysisMethod) { AnalysisMethodDescription desc; desc.name = QString::fromUtf8(meth->name); desc.realName = QString::fromUtf8(meth->real_name); desc.addr = meth->addr; desc.vtableOffset = meth->vtable_offset; ret.append(desc); } rz_vector_free(meths); return ret; } QList<AnalysisBaseClassDescription> CutterCore::getAnalysisClassBaseClasses(const QString &cls) { CORE_LOCK(); QList<AnalysisBaseClassDescription> ret; RzVector *bases = rz_analysis_class_base_get_all(core->analysis, cls.toUtf8().constData()); if (!bases) { return ret; } ret.reserve(static_cast<int>(bases->len)); RzAnalysisBaseClass *base; CutterRzVectorForeach(bases, base, RzAnalysisBaseClass) { AnalysisBaseClassDescription desc; desc.id = QString::fromUtf8(base->id); desc.offset = base->offset; desc.className = QString::fromUtf8(base->class_name); ret.append(desc); } rz_vector_free(bases); return ret; } QList<AnalysisVTableDescription> CutterCore::getAnalysisClassVTables(const QString &cls) { CORE_LOCK(); QList<AnalysisVTableDescription> acVtables; RzVector *vtables = rz_analysis_class_vtable_get_all(core->analysis, cls.toUtf8().constData()); if (!vtables) { return acVtables; } acVtables.reserve(static_cast<int>(vtables->len)); RzAnalysisVTable *vtable; CutterRzVectorForeach(vtables, vtable, RzAnalysisVTable) { AnalysisVTableDescription desc; desc.id = QString::fromUtf8(vtable->id); desc.offset = vtable->offset; desc.addr = vtable->addr; acVtables.append(desc); } rz_vector_free(vtables); return acVtables; } void CutterCore::createNewClass(const QString &cls) { CORE_LOCK(); rz_analysis_class_create(core->analysis, cls.toUtf8().constData()); } void CutterCore::renameClass(const QString &oldName, const QString &newName) { CORE_LOCK(); rz_analysis_class_rename(core->analysis, oldName.toUtf8().constData(), newName.toUtf8().constData()); } void CutterCore::deleteClass(const QString &cls) { CORE_LOCK(); rz_analysis_class_delete(core->analysis, cls.toUtf8().constData()); } bool CutterCore::getAnalysisMethod(const QString &cls, const QString &meth, AnalysisMethodDescription *desc) { CORE_LOCK(); RzAnalysisMethod analysisMeth; if (rz_analysis_class_method_get(core->analysis, cls.toUtf8().constData(), meth.toUtf8().constData(), &analysisMeth) != RZ_ANALYSIS_CLASS_ERR_SUCCESS) { return false; } desc->name = QString::fromUtf8(analysisMeth.name); desc->realName = QString::fromUtf8(analysisMeth.real_name); desc->addr = analysisMeth.addr; desc->vtableOffset = analysisMeth.vtable_offset; rz_analysis_class_method_fini(&analysisMeth); return true; } void CutterCore::setAnalysisMethod(const QString &className, const AnalysisMethodDescription &meth) { CORE_LOCK(); RzAnalysisMethod analysisMeth; analysisMeth.name = rz_str_dup(meth.name.toUtf8().constData()); analysisMeth.real_name = rz_str_dup(meth.realName.toUtf8().constData()); analysisMeth.addr = meth.addr; analysisMeth.vtable_offset = meth.vtableOffset; rz_analysis_class_method_set(core->analysis, className.toUtf8().constData(), &analysisMeth); rz_analysis_class_method_fini(&analysisMeth); } void CutterCore::renameAnalysisMethod(const QString &className, const QString &oldMethodName, const QString &newMethodName) { CORE_LOCK(); rz_analysis_class_method_rename(core->analysis, className.toUtf8().constData(), oldMethodName.toUtf8().constData(), newMethodName.toUtf8().constData()); } QList<ResourcesDescription> CutterCore::getAllResources() { CORE_LOCK(); RzBinFile *bf = rz_bin_cur(core->bin); if (!bf) { return {}; } const RzPVector *resources = rz_bin_object_get_resources(bf->o); if (!resources) { return {}; } QList<ResourcesDescription> resourcesDescriptions; for (const auto &resource : CutterPVector<RzBinResource>(resources)) { ResourcesDescription description; description.name = resource->name; description.vaddr = resource->vaddr; description.index = resource->index; description.type = resource->type; description.size = resource->size; description.lang = resource->language; resourcesDescriptions << description; } return resourcesDescriptions; } QList<VTableDescription> CutterCore::getAllVTables() { CORE_LOCK(); QList<VTableDescription> vtableDescs; RVTableContext context; rz_analysis_vtable_begin(core->analysis, &context); RzList *vtables = rz_analysis_vtable_search(&context); RzListIter *iter; RVTableInfo *table; RVTableMethodInfo *method; CutterRzListForeach (vtables, iter, RVTableInfo, table) { VTableDescription tableDesc; tableDesc.addr = table->saddr; CutterRzVectorForeach(&table->methods, method, RVTableMethodInfo) { BinClassMethodDescription methodDesc; RzAnalysisFunction *fcn = rz_analysis_get_fcn_in(core->analysis, method->addr, 0); const char *fname = fcn ? fcn->name : nullptr; methodDesc.addr = method->addr; methodDesc.name = fname ? fname : "No Name found"; tableDesc.methods << methodDesc; } vtableDescs << tableDesc; } rz_list_free(vtables); return vtableDescs; } QList<TypeDescription> CutterCore::getAllTypes() { QList<TypeDescription> types; types.append(getAllPrimitiveTypes()); types.append(getAllUnions()); types.append(getAllStructs()); types.append(getAllEnums()); types.append(getAllTypedefs()); return types; } QList<TypeDescription> CutterCore::getBaseType(RzBaseTypeKind kind, const char *category) { CORE_LOCK(); QList<TypeDescription> types; RzList *ts = rz_type_db_get_base_types_of_kind(core->analysis->typedb, kind); RzBaseType *type; RzListIter *iter; CutterRzListForeach (ts, iter, RzBaseType, type) { TypeDescription exp; exp.type = type->name; exp.size = rz_type_db_base_get_bitsize(core->analysis->typedb, type); exp.format = rz_base_type_as_format(core->analysis->typedb, type); exp.category = tr(category); types << exp; } rz_list_free(ts); return types; } QList<TypeDescription> CutterCore::getAllPrimitiveTypes() { return getBaseType(RZ_BASE_TYPE_KIND_ATOMIC, "Primitive"); } QList<TypeDescription> CutterCore::getAllUnions() { return getBaseType(RZ_BASE_TYPE_KIND_UNION, "Union"); } QList<TypeDescription> CutterCore::getAllStructs() { return getBaseType(RZ_BASE_TYPE_KIND_STRUCT, "Struct"); } QList<TypeDescription> CutterCore::getAllEnums() { return getBaseType(RZ_BASE_TYPE_KIND_ENUM, "Enum"); } QList<TypeDescription> CutterCore::getAllTypedefs() { return getBaseType(RZ_BASE_TYPE_KIND_TYPEDEF, "Typedef"); } QString CutterCore::getTypeAsC(QString name) { CORE_LOCK(); QString output = "Failed to fetch the output."; if (name.isEmpty()) { return output; } char *earg = rz_cmd_escape_arg(name.toUtf8().constData(), RZ_CMD_ESCAPE_ONE_ARG); QString result = fromOwnedCharPtr(rz_core_types_as_c(core, earg, true)); free(earg); return result; } bool CutterCore::isAddressMapped(RVA addr) { CORE_LOCK(); return rz_io_map_get(core->io, addr); } QList<SearchDescription> CutterCore::getAllSearch(QString searchFor, QString space, QString in) { CORE_LOCK(); QList<SearchDescription> searchRef; CutterJson searchArray; { TempConfig cfg; cfg.set("search.in", in); searchArray = cmdj(QString("%1 %2").arg(space, searchFor)); } if (space == "/Rj") { for (CutterJson searchObject : searchArray) { SearchDescription exp; exp.code.clear(); for (CutterJson gadget : searchObject[RJsonKey::opcodes]) { exp.code += gadget[RJsonKey::opcode].toString() + "; "; } exp.offset = searchObject[RJsonKey::opcodes].first()[RJsonKey::offset].toRVA(); exp.size = searchObject[RJsonKey::size].toUt64(); searchRef << exp; } } else { for (CutterJson searchObject : searchArray) { SearchDescription exp; exp.offset = searchObject[RJsonKey::offset].toRVA(); exp.size = searchObject[RJsonKey::len].toUt64(); exp.code = searchObject[RJsonKey::code].toString(); exp.data = searchObject[RJsonKey::data].toString(); searchRef << exp; } } return searchRef; } QList<XrefDescription> CutterCore::getXRefsForVariable(QString variableName, bool findWrites, RVA offset) { CORE_LOCK(); auto fcn = functionIn(offset); if (!fcn) { return {}; } const auto typ = findWrites ? RZ_ANALYSIS_VAR_ACCESS_TYPE_WRITE : RZ_ANALYSIS_VAR_ACCESS_TYPE_READ; QList<XrefDescription> xrefList = QList<XrefDescription>(); for (const auto &v : CutterPVector<RzAnalysisVar>(&fcn->vars)) { if (variableName != v->name) { continue; } RzAnalysisVarAccess *acc; CutterRzVectorForeach(&v->accesses, acc, RzAnalysisVarAccess) { if (!(acc->type & typ)) { continue; } XrefDescription xref; RVA addr = fcn->addr + acc->offset; xref.from = addr; xref.to = addr; if (findWrites) { xref.from_str = RzAddressString(addr); } else { xref.to_str = RzAddressString(addr); } xrefList << xref; } } return xrefList; } QList<XrefDescription> CutterCore::getXRefs(RVA addr, bool to, bool whole_function, const QString &filterType) { QList<XrefDescription> xrefList = QList<XrefDescription>(); RzList *xrefs = nullptr; { CORE_LOCK(); if (to) { xrefs = rz_analysis_xrefs_get_to(core->analysis, addr); } else { xrefs = rz_analysis_xrefs_get_from(core->analysis, addr); } } RzListIter *it; RzAnalysisXRef *xref; CutterRzListForeach (xrefs, it, RzAnalysisXRef, xref) { XrefDescription xd; xd.from = xref->from; xd.to = xref->to; xd.type = rz_analysis_xrefs_type_tostring(xref->type); if (!filterType.isNull() && filterType != xd.type) continue; if (!whole_function && !to && xd.from != addr) { continue; } xd.from_str = RzAddressString(xd.from); xd.to_str = Core()->flagAt(xd.to); xrefList << xd; } rz_list_free(xrefs); return xrefList; } void CutterCore::addGlobalVariable(RVA offset, QString name, QString typ) { name = sanitizeStringForCommand(name); CORE_LOCK(); char *errmsg = NULL; RzType *globType = rz_type_parse_string_single(core->analysis->typedb->parser, typ.toStdString().c_str(), &errmsg); if (errmsg) { qWarning() << tr("Error parsing type: \"%1\" message: ").arg(typ) << errmsg; free(errmsg); return; } if (!rz_analysis_var_global_create(core->analysis, name.toStdString().c_str(), globType, offset)) { qWarning() << tr("Error creating global variable: \"%1\"").arg(name); return; } emit globalVarsChanged(); } void CutterCore::modifyGlobalVariable(RVA offset, QString name, QString typ) { name = sanitizeStringForCommand(name); CORE_LOCK(); RzAnalysisVarGlobal *glob = rz_analysis_var_global_get_byaddr_at(core->analysis, offset); if (!glob) { return; } // Compare if the name is not the same - also rename it if (name.compare(glob->name)) { rz_analysis_var_global_rename(core->analysis, glob->name, name.toStdString().c_str()); } char *errmsg = NULL; RzType *globType = rz_type_parse_string_single(core->analysis->typedb->parser, typ.toStdString().c_str(), &errmsg); if (errmsg) { qWarning() << tr("Error parsing type: \"%1\" message: ").arg(typ) << errmsg; free(errmsg); return; } rz_analysis_var_global_set_type(glob, globType); emit globalVarsChanged(); } void CutterCore::delGlobalVariable(QString name) { name = sanitizeStringForCommand(name); CORE_LOCK(); rz_analysis_var_global_delete_byname(core->analysis, name.toStdString().c_str()); emit globalVarsChanged(); } void CutterCore::delGlobalVariable(RVA offset) { CORE_LOCK(); rz_analysis_var_global_delete_byaddr_at(core->analysis, offset); emit globalVarsChanged(); } QString CutterCore::getGlobalVariableType(QString name) { name = sanitizeStringForCommand(name); CORE_LOCK(); RzAnalysisVarGlobal *glob = rz_analysis_var_global_get_byname(core->analysis, name.toStdString().c_str()); if (!glob) { return QString(""); } const char *gtype = rz_type_as_string(core->analysis->typedb, glob->type); if (!gtype) { return QString(""); } return QString(gtype); } QString CutterCore::getGlobalVariableType(RVA offset) { CORE_LOCK(); RzAnalysisVarGlobal *glob = rz_analysis_var_global_get_byaddr_at(core->analysis, offset); if (!glob) { return QString(""); } const char *gtype = rz_type_as_string(core->analysis->typedb, glob->type); if (!gtype) { return QString(""); } return QString(gtype); } void CutterCore::addFlag(RVA offset, QString name, RVA size) { name = sanitizeStringForCommand(name); CORE_LOCK(); rz_flag_set(core->flags, name.toStdString().c_str(), offset, size); emit flagsChanged(); } /** * @brief Gets all the flags present at a specific address * @param addr The address to be checked * @return String containing all the flags which are comma-separated */ QString CutterCore::listFlagsAsStringAt(RVA addr) { CORE_LOCK(); char *flagList = rz_flag_get_liststr(core->flags, addr); QString result = fromOwnedCharPtr(flagList); return result; } QString CutterCore::nearestFlag(RVA offset, RVA *flagOffsetOut) { CORE_LOCK(); auto r = rz_flag_get_at(core->flags, offset, true); if (!r) { return {}; } if (flagOffsetOut) { *flagOffsetOut = r->offset; } return r->name; } void CutterCore::handleREvent(int type, void *data) { switch (type) { case RZ_EVENT_CLASS_NEW: { auto ev = reinterpret_cast<RzEventClass *>(data); emit classNew(QString::fromUtf8(ev->name)); break; } case RZ_EVENT_CLASS_DEL: { auto ev = reinterpret_cast<RzEventClass *>(data); emit classDeleted(QString::fromUtf8(ev->name)); break; } case RZ_EVENT_CLASS_RENAME: { auto ev = reinterpret_cast<RzEventClassRename *>(data); emit classRenamed(QString::fromUtf8(ev->name_old), QString::fromUtf8(ev->name_new)); break; } case RZ_EVENT_CLASS_ATTR_SET: { auto ev = reinterpret_cast<RzEventClassAttrSet *>(data); emit classAttrsChanged(QString::fromUtf8(ev->attr.class_name)); break; } case RZ_EVENT_CLASS_ATTR_DEL: { auto ev = reinterpret_cast<RzEventClassAttr *>(data); emit classAttrsChanged(QString::fromUtf8(ev->class_name)); break; } case RZ_EVENT_CLASS_ATTR_RENAME: { auto ev = reinterpret_cast<RzEventClassAttrRename *>(data); emit classAttrsChanged(QString::fromUtf8(ev->attr.class_name)); break; } case RZ_EVENT_DEBUG_PROCESS_FINISHED: { auto ev = reinterpret_cast<RzEventDebugProcessFinished *>(data); emit debugProcessFinished(ev->pid); break; } default: break; } } void CutterCore::triggerFlagsChanged() { emit flagsChanged(); } void CutterCore::triggerVarsChanged() { emit varsChanged(); } void CutterCore::triggerFunctionRenamed(const RVA offset, const QString &newName) { emit functionRenamed(offset, newName); } void CutterCore::loadPDB(const QString &file) { CORE_LOCK(); rz_core_bin_pdb_load(core, file.toUtf8().constData()); } QList<DisassemblyLine> CutterCore::disassembleLines(RVA offset, int lines) { CORE_LOCK(); auto vec = fromOwned( rz_pvector_new(reinterpret_cast<RzPVectorFree>(rz_analysis_disasm_text_free))); if (!vec) { return {}; } RzCoreDisasmOptions options = {}; options.cbytes = 1; options.vec = vec.get(); { auto restoreSeek = seekTemp(offset); if (rz_cons_singleton()->is_html) { rz_cons_singleton()->is_html = false; rz_cons_singleton()->was_html = true; } rz_core_print_disasm(core, offset, core->block, core->blocksize, lines, NULL, &options); } QList<DisassemblyLine> r; for (const auto &t : CutterPVector<RzAnalysisDisasmText>(vec.get())) { QString text = t->text; QStringList tokens = text.split('\n'); // text might contain multiple lines // so we split them and keep only one // arrow/jump to addr. for (const auto &tok : tokens) { DisassemblyLine line; line.offset = t->offset; line.text = ansiEscapeToHtml(tok); line.arrow = t->arrow; r << line; // only the first one. t->arrow = RVA_INVALID; } } return r; } /** * @brief return hexdump of <size> from an <offset> by a given formats * @param address - the address from which to print the hexdump * @param size - number of bytes to print * @param format - the type of hexdump (qwords, words. decimal, etc) */ QString CutterCore::hexdump(RVA address, int size, HexdumpFormats format) { CORE_LOCK(); char *res = nullptr; switch (format) { case HexdumpFormats::Normal: res = rz_core_print_hexdump_or_hexdiff_str(core, RZ_OUTPUT_MODE_STANDARD, address, size, false); break; case HexdumpFormats::Half: res = rz_core_print_dump_str(core, RZ_OUTPUT_MODE_STANDARD, address, 2, size, RZ_CORE_PRINT_FORMAT_TYPE_HEXADECIMAL); break; case HexdumpFormats::Word: res = rz_core_print_dump_str(core, RZ_OUTPUT_MODE_STANDARD, address, 4, size, RZ_CORE_PRINT_FORMAT_TYPE_HEXADECIMAL); break; case HexdumpFormats::Quad: res = rz_core_print_dump_str(core, RZ_OUTPUT_MODE_STANDARD, address, 8, size, RZ_CORE_PRINT_FORMAT_TYPE_HEXADECIMAL); break; case HexdumpFormats::Signed: res = rz_core_print_dump_str(core, RZ_OUTPUT_MODE_STANDARD, address, 1, size, RZ_CORE_PRINT_FORMAT_TYPE_INTEGER); break; case HexdumpFormats::Octal: res = rz_core_print_dump_str(core, RZ_OUTPUT_MODE_STANDARD, address, 1, size, RZ_CORE_PRINT_FORMAT_TYPE_OCTAL); break; } return fromOwnedCharPtr(res); } QByteArray CutterCore::hexStringToBytes(const QString &hex) { QByteArray hexChars = hex.toUtf8(); QByteArray bytes; bytes.reserve(hexChars.length() / 2); int size = rz_hex_str2bin(hexChars.constData(), reinterpret_cast<ut8 *>(bytes.data())); bytes.resize(size); return bytes; } QString CutterCore::bytesToHexString(const QByteArray &bytes) { QByteArray hex; hex.resize(bytes.length() * 2); rz_hex_bin2str(reinterpret_cast<const ut8 *>(bytes.constData()), bytes.size(), hex.data()); return QString::fromUtf8(hex); } void CutterCore::loadScript(const QString &scriptname) { { CORE_LOCK(); rz_core_cmd_file(core, scriptname.toUtf8().constData()); rz_cons_flush(); } triggerRefreshAll(); } QString CutterCore::getRizinVersionReadable(const char *program) { return fromOwnedCharPtr(rz_version_str(program)); } QString CutterCore::getVersionInformation() { int i; QString versionInfo; struct vcs_t { const char *name; const char *(*callback)(); } vcs[] = { { "rz_arch", &rz_arch_version }, { "rz_lib", &rz_lib_version }, { "rz_egg", &rz_egg_version }, { "rz_bin", &rz_bin_version }, { "rz_cons", &rz_cons_version }, { "rz_flag", &rz_flag_version }, { "rz_core", &rz_core_version }, { "rz_crypto", &rz_crypto_version }, { "rz_bp", &rz_bp_version }, { "rz_debug", &rz_debug_version }, { "rz_hash", &rz_hash_version }, { "rz_io", &rz_io_version }, #if !USE_LIB_MAGIC { "rz_magic", &rz_magic_version }, #endif { "rz_reg", &rz_reg_version }, { "rz_sign", &rz_sign_version }, { "rz_search", &rz_search_version }, { "rz_syscall", &rz_syscall_version }, { "rz_util", &rz_util_version }, /* ... */ { NULL, NULL } }; versionInfo.append(getRizinVersionReadable()); versionInfo.append("\n"); for (i = 0; vcs[i].name; i++) { struct vcs_t *v = &vcs[i]; const char *name = v->callback(); versionInfo.append(QString("%1 %2\n").arg(name, v->name)); } return versionInfo; } QStringList CutterCore::getColorThemes() { QStringList r; CORE_LOCK(); RzPVector *themes_list = rz_core_get_themes(core); if (!themes_list) { return r; } for (const auto &th : CutterPVector<char>(themes_list)) { r << fromOwnedCharPtr(rz_str_trim_dup(th)); } rz_pvector_free(themes_list); return r; } QHash<QString, QColor> CutterCore::getTheme() { QHash<QString, QColor> theme; for (int i = 0;; ++i) { const char *k = rz_cons_pal_get_name(i); if (!k) { break; } RzColor color = rz_cons_pal_get_i(i); theme.insert(k, QColor(color.r, color.g, color.b)); } return theme; } QStringList CutterCore::getThemeKeys() { QStringList stringList; for (int i = 0;; ++i) { const char *k = rz_cons_pal_get_name(i); if (!k) { break; } stringList << k; } return stringList; } bool CutterCore::setColor(const QString &key, const QString &color) { if (!rz_cons_pal_set(key.toUtf8().constData(), color.toUtf8().constData())) { return false; } rz_cons_pal_update_event(); return true; } QString CutterCore::ansiEscapeToHtml(const QString &text) { int len; QString r = text; r.replace("\t", " "); char *html = rz_cons_html_filter(r.toUtf8().constData(), &len); if (!html) { return {}; } r = QString::fromUtf8(html, len); rz_mem_free(html); return r; } BasicBlockHighlighter *CutterCore::getBBHighlighter() { return bbHighlighter; } BasicInstructionHighlighter *CutterCore::getBIHighlighter() { return &biHighlighter; } void CutterCore::setIOCache(bool enabled) { if (enabled) { // disable write mode when cache is enabled setWriteMode(false); } setConfig("io.cache", enabled); this->iocache = enabled; emit ioCacheChanged(enabled); emit ioModeChanged(); } bool CutterCore::isIOCacheEnabled() const { return iocache; } void CutterCore::commitWriteCache() { CORE_LOCK(); // Temporarily disable cache mode TempConfig tempConfig; tempConfig.set("io.cache", false); auto desc = core->io->desc; bool reopen = !isWriteModeEnabled() && desc; if (reopen) { rz_core_io_file_reopen(core, desc->fd, RZ_PERM_RW); } rz_io_cache_commit(core->io, 0, UT64_MAX); rz_core_block_read(core); if (reopen) { rz_core_io_file_open(core, desc->fd); } } void CutterCore::resetWriteCache() { CORE_LOCK(); rz_io_cache_reset(core->io, core->io->cached); } // Enable or disable write-mode. Avoid unecessary changes if not need. void CutterCore::setWriteMode(bool enabled) { bool writeModeState = isWriteModeEnabled(); if (writeModeState == enabled && !this->iocache) { // New mode is the same as current and IO Cache is disabled. Do nothing. return; } CORE_LOCK(); // Change from read-only to write-mode RzIODesc *desc = core->io->desc; if (desc) { if (enabled) { if (!writeModeState) { rz_core_io_file_reopen(core, desc->fd, RZ_PERM_RW); } } else { // Change from write-mode to read-only rz_core_io_file_open(core, desc->fd); } } // Disable cache mode because we specifically set write or // read-only modes. if (this->iocache) { setIOCache(false); } emit writeModeChanged(enabled); emit ioModeChanged(); } bool CutterCore::isWriteModeEnabled() { CORE_LOCK(); RzListIter *it; RzCoreFile *cf; CutterRzListForeach (core->files, it, RzCoreFile, cf) { RzIODesc *desc = rz_io_desc_get(core->io, cf->fd); if (!desc) { continue; } if (desc->perm & RZ_PERM_W) { return true; } } return false; } /** * @brief get a compact disassembly preview for tooltips * @param address - the address from which to print the disassembly * @param num_of_lines - number of instructions to print */ QStringList CutterCore::getDisassemblyPreview(RVA address, int num_of_lines) { QList<DisassemblyLine> disassemblyLines; { // temporarily simplify the disasm output to get it colorful and simple to read TempConfig tempConfig; tempConfig.set("scr.color", COLOR_MODE_16M) .set("asm.lines", false) .set("asm.var", false) .set("asm.comments", false) .set("asm.bytes", false) .set("asm.lines.fcn", false) .set("asm.lines.out", false) .set("asm.lines.bb", false) .set("asm.bb.line", false); disassemblyLines = disassembleLines(address, num_of_lines + 1); } QStringList disasmPreview; for (const DisassemblyLine &line : disassemblyLines) { disasmPreview << line.text; if (disasmPreview.length() >= num_of_lines) { disasmPreview << "..."; break; } } if (!disasmPreview.isEmpty()) { return disasmPreview; } else { return QStringList(); } } /** * @brief get a compact hexdump preview for tooltips * @param address - the address from which to print the hexdump * @param size - number of bytes to print */ QString CutterCore::getHexdumpPreview(RVA address, int size) { // temporarily simplify the disasm output to get it colorful and simple to read TempConfig tempConfig; tempConfig.set("scr.color", COLOR_MODE_16M) .set("asm.offset", true) .set("hex.header", false) .set("hex.cols", 16); return ansiEscapeToHtml(hexdump(address, size, HexdumpFormats::Normal)) .replace(QLatin1Char('\n'), "<br>"); } QByteArray CutterCore::ioRead(RVA addr, int len) { CORE_LOCK(); QByteArray array; if (len <= 0) return array; /* Zero-copy */ array.resize(len); if (!rz_io_read_at(core->io, addr, (uint8_t *)array.data(), len)) { array.fill(0xff); } return array; } QStringList CutterCore::getConfigVariableSpaces(const QString &key) { CORE_LOCK(); RzList *list = rz_core_config_in_space(core, key.toUtf8().constData()); if (!list) { return {}; } QStringList stringList; for (const auto &x : CutterRzList<char>(list)) { stringList << x; } rz_list_free(list); return stringList; } char *CutterCore::getTextualGraphAt(RzCoreGraphType type, RzCoreGraphFormat format, RVA address) { CORE_LOCK(); char *string = nullptr; RzGraph *graph = rz_core_graph(core, type, address); if (!graph) { if (address == RVA_INVALID) { qWarning() << tr("Cannot get global graph"); } else { qWarning() << tr("Cannot get graph at ") << RzAddressString(address); } return nullptr; } core->graph->is_callgraph = type == RZ_CORE_GRAPH_TYPE_FUNCALL; switch (format) { case RZ_CORE_GRAPH_FORMAT_CMD: { string = rz_graph_drawable_to_cmd(graph); break; } case RZ_CORE_GRAPH_FORMAT_DOT: { string = rz_core_graph_to_dot_str(core, graph); break; } case RZ_CORE_GRAPH_FORMAT_JSON: /* fall-thru */ case RZ_CORE_GRAPH_FORMAT_JSON_DISASM: { string = rz_graph_drawable_to_json_str(graph, true); break; } case RZ_CORE_GRAPH_FORMAT_GML: { string = rz_graph_drawable_to_gml(graph); break; } default: break; } rz_graph_free(graph); if (!string) { qWarning() << tr("Failed to generate graph"); } return string; } void CutterCore::writeGraphvizGraphToFile(QString path, QString format, RzCoreGraphType type, RVA address) { TempConfig tempConfig; tempConfig.set("scr.color", false); tempConfig.set("graph.gv.format", format); CORE_LOCK(); auto filepath = path.toUtf8(); if (!rz_core_graph_write(core, address, type, filepath)) { if (address == RVA_INVALID) { qWarning() << tr("Cannot get global graph"); } else { qWarning() << tr("Cannot get graph at ") << RzAddressString(address); } } } bool CutterCore::rebaseBin(RVA base_address) { CORE_LOCK(); return rz_core_bin_rebase(core, base_address); }
129,571
C++
.cpp
4,127
24.712382
100
0.614286
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,491
CutterJson.cpp
rizinorg_cutter/src/core/CutterJson.cpp
#include "core/CutterJson.h" CutterJson CutterJson::last() const { if (!has_children()) { return CutterJson(); } const RzJson *last = value->children.first; while (last->next) { last = last->next; } return CutterJson(last, owner); } QStringList CutterJson::keys() const { QStringList list; if (value && value->type == RZ_JSON_OBJECT) { for (const RzJson *child = value->children.first; child; child = child->next) { list.append(child->key); } } return list; }
550
C++
.cpp
22
19.909091
87
0.613027
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,492
EditVariablesDialog.cpp
rizinorg_cutter/src/dialogs/EditVariablesDialog.cpp
#include "EditVariablesDialog.h" #include "ui_EditVariablesDialog.h" #include <QMetaType> #include <QComboBox> #include <QMetaType> #include <QPushButton> EditVariablesDialog::EditVariablesDialog(RVA offset, QString initialVar, QWidget *parent) : QDialog(parent), ui(new Ui::EditVariablesDialog), functionAddress(RVA_INVALID) { ui->setupUi(this); connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &EditVariablesDialog::applyFields); connect<void (QComboBox::*)(int)>(ui->dropdownLocalVars, &QComboBox::currentIndexChanged, this, &EditVariablesDialog::updateFields); RzAnalysisFunction *f = rz_analysis_get_function_at(Core()->core()->analysis, offset); QString fcnName = f->name; functionAddress = offset; setWindowTitle(tr("Edit Variables in Function: %1").arg(fcnName)); variables = Core()->getVariables(offset); int currentItemIndex = -1; int index = 0; for (const VariableDescription &var : variables) { ui->dropdownLocalVars->addItem(var.name, QVariant::fromValue(var)); if (var.name == initialVar) { currentItemIndex = index; } index++; } ui->dropdownLocalVars->setCurrentIndex(currentItemIndex); if (currentItemIndex != -1) { ui->nameEdit->setFocus(); } populateTypesComboBox(); updateFields(); } EditVariablesDialog::~EditVariablesDialog() { delete ui; } bool EditVariablesDialog::empty() const { return ui->dropdownLocalVars->count() == 0; } void EditVariablesDialog::applyFields() { if (ui->dropdownLocalVars->currentIndex() < 0) { // nothing was selected or list is empty return; } VariableDescription desc = ui->dropdownLocalVars->currentData().value<VariableDescription>(); RzCoreLocked core(Core()); RzAnalysisFunction *fcn = Core()->functionIn(core->offset); if (!fcn) { return; } RzAnalysisVar *v = rz_analysis_function_get_var_byname(fcn, desc.name.toUtf8().constData()); if (!v) { return; } char *error_msg = NULL; RzType *v_type = rz_type_parse_string_single( core->analysis->typedb->parser, ui->typeComboBox->currentText().toUtf8().constData(), &error_msg); if (!v_type || error_msg) { return; } rz_analysis_var_set_type(v, v_type, true); // TODO Remove all those replace once rizin command parser is fixed QString newName = ui->nameEdit->text() .replace(QLatin1Char(' '), QLatin1Char('_')) .replace(QLatin1Char('\\'), QLatin1Char('_')) .replace(QLatin1Char('/'), QLatin1Char('_')); if (newName != desc.name) { Core()->renameFunctionVariable(newName, desc.name, functionAddress); } // Refresh the views to reflect the changes to vars emit Core()->refreshCodeViews(); } void EditVariablesDialog::updateFields() { bool hasSelection = ui->dropdownLocalVars->currentIndex() >= 0; auto okButton = ui->buttonBox->button(QDialogButtonBox::Ok); okButton->setEnabled(hasSelection); if (!hasSelection) { ui->nameEdit->clear(); return; } VariableDescription desc = ui->dropdownLocalVars->currentData().value<VariableDescription>(); ui->nameEdit->setText(desc.name); ui->typeComboBox->setCurrentText(desc.type); } static void addTypeDescriptionsToComboBox(QComboBox *comboBox, QList<TypeDescription> list) { for (const TypeDescription &thisType : list) { comboBox->addItem(thisType.type); } comboBox->insertSeparator(comboBox->count()); } void EditVariablesDialog::populateTypesComboBox() { addTypeDescriptionsToComboBox(ui->typeComboBox, Core()->getAllStructs()); addTypeDescriptionsToComboBox(ui->typeComboBox, Core()->getAllPrimitiveTypes()); addTypeDescriptionsToComboBox(ui->typeComboBox, Core()->getAllEnums()); addTypeDescriptionsToComboBox(ui->typeComboBox, Core()->getAllTypedefs()); }
4,027
C++
.cpp
104
32.759615
99
0.67955
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,493
EditInstructionDialog.cpp
rizinorg_cutter/src/dialogs/EditInstructionDialog.cpp
#include "EditInstructionDialog.h" #include "ui_EditInstructionDialog.h" #include "core/Cutter.h" #include <QCheckBox> EditInstructionDialog::EditInstructionDialog(InstructionEditMode editMode, QWidget *parent) : QDialog(parent), ui(new Ui::EditInstructionDialog), editMode(editMode) { ui->setupUi(this); ui->lineEdit->setMinimumWidth(400); ui->instructionLabel->setWordWrap(true); if (editMode == EDIT_TEXT) { ui->fillWithNops->setVisible(true); ui->fillWithNops->setCheckState(Qt::Checked); } else { ui->fillWithNops->setVisible(false); } setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); connect(ui->lineEdit, &QLineEdit::textEdited, this, &EditInstructionDialog::updatePreview); } EditInstructionDialog::~EditInstructionDialog() {} void EditInstructionDialog::on_buttonBox_accepted() {} void EditInstructionDialog::on_buttonBox_rejected() { close(); } bool EditInstructionDialog::needsNops() const { if (editMode != EDIT_TEXT) { return false; } return ui->fillWithNops->checkState() == Qt::Checked; } QString EditInstructionDialog::getInstruction() const { return ui->lineEdit->text(); } void EditInstructionDialog::setInstruction(const QString &instruction) { ui->lineEdit->setText(instruction); ui->lineEdit->selectAll(); updatePreview(instruction); } void EditInstructionDialog::updatePreview(const QString &input) { QString result; if (editMode == EDIT_NONE) { ui->instructionLabel->setText(""); return; } else if (editMode == EDIT_BYTES) { QByteArray data = CutterCore::hexStringToBytes(input); result = Core()->disassemble(data).replace('\n', "; "); } else if (editMode == EDIT_TEXT) { QByteArray data = Core()->assemble(input); result = CutterCore::bytesToHexString(data).trimmed(); } if (result.isEmpty() || result.contains("invalid")) { ui->instructionLabel->setText("Unknown Instruction"); } else { ui->instructionLabel->setText(result); } }
2,083
C++
.cpp
61
29.721311
95
0.706819
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,494
InitialOptionsDialog.cpp
rizinorg_cutter/src/dialogs/InitialOptionsDialog.cpp
#include "common/AsyncTask.h" #include "InitialOptionsDialog.h" #include "ui_InitialOptionsDialog.h" #include "core/MainWindow.h" #include "dialogs/NewFileDialog.h" #include "dialogs/AsyncTaskDialog.h" #include "common/Helpers.h" #include <QSettings> #include <QFileInfo> #include <QFileDialog> #include <QCloseEvent> #include "core/Cutter.h" #include "common/AnalysisTask.h" #include "CutterApplication.h" InitialOptionsDialog::InitialOptionsDialog(MainWindow *main) : QDialog(nullptr), // parent must not be main ui(new Ui::InitialOptionsDialog), main(main), core(Core()) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); ui->logoSvgWidget->load(Config()->getLogoFile()); // Fill the plugins combo asmPlugins = core->getRAsmPluginDescriptions(); for (const auto &plugin : asmPlugins) { ui->archComboBox->addItem(plugin.name, plugin.name); } setTooltipWithConfigHelp(ui->archComboBox, "asm.arch"); // cpu combo box ui->cpuComboBox->lineEdit()->setPlaceholderText(tr("Auto")); setTooltipWithConfigHelp(ui->cpuComboBox, "asm.cpu"); updateCPUComboBox(); // os combo box for (const auto &plugin : Core()->getConfigOptions("asm.os")) { ui->kernelComboBox->addItem(plugin, plugin); } setTooltipWithConfigHelp(ui->kernelComboBox, "asm.os"); setTooltipWithConfigHelp(ui->bitsComboBox, "asm.bits"); for (const auto &plugin : core->getBinPluginDescriptions(true, false)) { ui->formatComboBox->addItem(plugin.name, QVariant::fromValue(plugin)); } analysisCommands = { { { "aa", tr("Analyze all symbols") }, new QCheckBox(), true }, { { "aar", tr("Analyze instructions for references") }, new QCheckBox(), true }, { { "aac", tr("Analyze function calls") }, new QCheckBox(), true }, { { "aab", tr("Analyze all basic blocks") }, new QCheckBox(), false }, { { "aao", tr("Analyze all objc references") }, new QCheckBox(), false }, { { "avrr", tr("Recover class information from RTTI") }, new QCheckBox(), false }, { { "aan", tr("Autoname functions based on context") }, new QCheckBox(), false }, { { "aae", tr("Emulate code to find computed references") }, new QCheckBox(), false }, { { "aafr", tr("Analyze all consecutive functions") }, new QCheckBox(), false }, { { "aaft", tr("Type and Argument matching analysis") }, new QCheckBox(), false }, { { "aaT", tr("Analyze code after trap-sleds") }, new QCheckBox(), false }, { { "aap", tr("Analyze function preludes") }, new QCheckBox(), false }, { { "e! analysis.jmp.tbl", tr("Analyze jump tables in switch statements") }, new QCheckBox(), false }, { { "e! analysis.pushret", tr("Analyze PUSH+RET as JMP") }, new QCheckBox(), false }, { { "e! analysis.hasnext", tr("Continue analysis after each function") }, new QCheckBox(), false } }; // Per each checkbox, set a tooltip desccribing it AnalysisCommands item; foreach (item, analysisCommands) { item.checkbox->setText(item.commandDesc.description); item.checkbox->setToolTip(item.commandDesc.command); item.checkbox->setChecked(item.checked); ui->verticalLayout_7->addWidget(item.checkbox); } ui->hideFrame->setVisible(false); ui->analysisoptionsFrame->setVisible(false); ui->advancedAnlysisLine->setVisible(false); updatePDBLayout(); connect(ui->pdbCheckBox, &QCheckBox::stateChanged, this, &InitialOptionsDialog::updatePDBLayout); updateScriptLayout(); connect(ui->scriptCheckBox, &QCheckBox::stateChanged, this, &InitialOptionsDialog::updateScriptLayout); connect(ui->cancelButton, &QPushButton::clicked, this, &InitialOptionsDialog::reject); ui->programLineEdit->setText(main->getFilename()); } InitialOptionsDialog::~InitialOptionsDialog() {} void InitialOptionsDialog::updateCPUComboBox() { QString currentText = ui->cpuComboBox->lineEdit()->text(); ui->cpuComboBox->clear(); QString arch = getSelectedArch(); QStringList cpus; if (!arch.isEmpty()) { auto pluginDescr = std::find_if( asmPlugins.begin(), asmPlugins.end(), [&](const RzAsmPluginDescription &plugin) { return plugin.name == arch; }); if (pluginDescr != asmPlugins.end()) { #if QT_VERSION >= QT_VERSION_CHECK(5, 14, 0) cpus = pluginDescr->cpus.split(",", Qt::SkipEmptyParts); #else cpus = pluginDescr->cpus.split(",", QString::SkipEmptyParts); #endif } } ui->cpuComboBox->addItem(""); ui->cpuComboBox->addItems(cpus); ui->cpuComboBox->lineEdit()->setText(currentText); } QList<QString> InitialOptionsDialog::getAnalysisCommands(const InitialOptions &options) { QList<QString> commands; for (auto &commandDesc : options.analysisCmd) { commands << commandDesc.command; } return commands; } void InitialOptionsDialog::loadOptions(const InitialOptions &options) { if (options.analysisCmd.isEmpty()) { analysisLevel = 0; } else if (options.analysisCmd.first().command == "aaa") { analysisLevel = 1; } else if (options.analysisCmd.first().command == "aaaa") { analysisLevel = 2; } else { analysisLevel = 3; AnalysisCommands item; QList<QString> commands = getAnalysisCommands(options); foreach (item, analysisCommands) { qInfo() << item.commandDesc.command; item.checkbox->setChecked(commands.contains(item.commandDesc.command)); } } if (!options.script.isEmpty()) { ui->scriptCheckBox->setChecked(true); ui->scriptLineEdit->setText(options.script); analysisLevel = 0; } else { ui->scriptCheckBox->setChecked(false); ui->scriptLineEdit->setText(""); } ui->analysisSlider->setValue(analysisLevel); shellcode = options.shellcode; if (!options.forceBinPlugin.isEmpty()) { ui->formatComboBox->setCurrentText(options.forceBinPlugin); } else { ui->formatComboBox->setCurrentIndex(0); } if (options.binLoadAddr != RVA_INVALID) { ui->entry_loadOffset->setText(RzAddressString(options.binLoadAddr)); } if (options.mapAddr != RVA_INVALID) { ui->entry_mapOffset->setText(RzAddressString(options.mapAddr)); } ui->vaCheckBox->setChecked(options.useVA); ui->writeCheckBox->setChecked(options.writeEnabled); if (!options.arch.isNull() && !options.arch.isEmpty()) { ui->archComboBox->setCurrentText(options.arch); } if (!options.cpu.isNull() && !options.cpu.isEmpty()) { ui->cpuComboBox->setCurrentText(options.cpu); } if (options.bits > 0) { ui->bitsComboBox->setCurrentText(QString::asprintf("%d", options.bits)); } if (!options.os.isNull() && !options.os.isEmpty()) { ui->kernelComboBox->setCurrentText(options.os); } if (!options.forceBinPlugin.isNull() && !options.forceBinPlugin.isEmpty()) { ui->formatComboBox->setCurrentText(options.forceBinPlugin); } if (!options.loadBinInfo) { ui->binCheckBox->setChecked(false); } ui->writeCheckBox->setChecked(options.writeEnabled); switch (options.endian) { case InitialOptions::Endianness::Little: ui->endiannessComboBox->setCurrentIndex(1); break; case InitialOptions::Endianness::Big: ui->endiannessComboBox->setCurrentIndex(2); break; default: break; } ui->demangleCheckBox->setChecked(options.demangle); if (!options.pdbFile.isNull() && !options.pdbFile.isEmpty()) { ui->pdbCheckBox->setChecked(true); ui->pdbLineEdit->setText(options.pdbFile); } } void InitialOptionsDialog::setTooltipWithConfigHelp(QWidget *w, const char *config) { w->setToolTip(QString("%1 (%2)").arg(core->getConfigDescription(config)).arg(config)); } QString InitialOptionsDialog::getSelectedArch() const { QVariant archValue = ui->archComboBox->currentData(); return archValue.isValid() ? archValue.toString() : nullptr; } QString InitialOptionsDialog::getSelectedCPU() const { QString cpu = ui->cpuComboBox->currentText(); if (cpu.isNull() || cpu.isEmpty()) { return nullptr; } return cpu; } int InitialOptionsDialog::getSelectedBits() const { QString sel_bits = ui->bitsComboBox->currentText(); if (sel_bits != "Auto") { return sel_bits.toInt(); } return 0; } InitialOptions::Endianness InitialOptionsDialog::getSelectedEndianness() const { switch (ui->endiannessComboBox->currentIndex()) { case 1: return InitialOptions::Endianness::Little; case 2: return InitialOptions::Endianness::Big; default: return InitialOptions::Endianness::Auto; } } QString InitialOptionsDialog::getSelectedOS() const { QVariant os = ui->kernelComboBox->currentData(); return os.isValid() ? os.toString() : nullptr; } QList<CommandDescription> InitialOptionsDialog::getSelectedAdvancedAnalCmds() const { QList<CommandDescription> advanced = QList<CommandDescription>(); if (ui->analysisSlider->value() == 3) { AnalysisCommands item; foreach (item, analysisCommands) { if (item.checkbox->isChecked()) { advanced << item.commandDesc; } } } return advanced; } void InitialOptionsDialog::setupAndStartAnalysis() { InitialOptions options; options.filename = main->getFilename(); if (!options.filename.isEmpty()) { main->setWindowTitle("Cutter – " + options.filename); } options.shellcode = this->shellcode; // Where the bin header is located in the file (-B) if (ui->entry_loadOffset->text().length() > 0) { options.binLoadAddr = Core()->math(ui->entry_loadOffset->text()); } options.mapAddr = Core()->math(ui->entry_mapOffset->text()); // Where to map the file once loaded (-m) options.arch = getSelectedArch(); options.cpu = getSelectedCPU(); options.bits = getSelectedBits(); options.os = getSelectedOS(); options.writeEnabled = ui->writeCheckBox->isChecked(); options.loadBinInfo = !ui->binCheckBox->isChecked(); options.useVA = ui->vaCheckBox->isChecked(); QVariant forceBinPluginData = ui->formatComboBox->currentData(); if (!forceBinPluginData.isNull()) { RzBinPluginDescription pluginDesc = forceBinPluginData.value<RzBinPluginDescription>(); options.forceBinPlugin = pluginDesc.name; } options.demangle = ui->demangleCheckBox->isChecked(); if (ui->pdbCheckBox->isChecked()) { options.pdbFile = ui->pdbLineEdit->text(); } if (ui->scriptCheckBox->isChecked()) { options.script = ui->scriptLineEdit->text(); } options.endian = getSelectedEndianness(); int level = ui->analysisSlider->value(); switch (level) { case 1: options.analysisCmd = { { "aaa", "Auto analysis" } }; break; case 2: options.analysisCmd = { { "aaaa", "Auto analysis (experimental)" } }; break; case 3: options.analysisCmd = getSelectedAdvancedAnalCmds(); break; default: options.analysisCmd = {}; break; } AnalysisTask *analysisTask = new AnalysisTask(); analysisTask->setOptions(options); MainWindow *main = this->main; connect(analysisTask, &AnalysisTask::openFileFailed, main, &MainWindow::openNewFileFailed); connect(analysisTask, &AsyncTask::finished, main, [analysisTask, main]() { if (analysisTask->getOpenFileFailed()) { return; } main->finalizeOpen(); }); AsyncTask::Ptr analysisTaskPtr(analysisTask); AsyncTaskDialog *taskDialog = new AsyncTaskDialog(analysisTaskPtr); taskDialog->setInterruptOnClose(true); taskDialog->setAttribute(Qt::WA_DeleteOnClose); taskDialog->show(); Core()->getAsyncTaskManager()->start(analysisTaskPtr); done(0); static_cast<CutterApplication *>(qApp)->setInitialOptions(options); } void InitialOptionsDialog::on_okButton_clicked() { ui->okButton->setEnabled(false); setupAndStartAnalysis(); } void InitialOptionsDialog::closeEvent(QCloseEvent *event) { event->accept(); } QString InitialOptionsDialog::analysisDescription(int level) { // TODO: replace this with meaningful descriptions switch (level) { case 0: return tr("No analysis"); case 1: return tr("Auto-Analysis (aaa)"); case 2: return tr("Auto-Analysis Experimental (aaaa)"); case 3: return tr("Advanced"); default: return tr("Unknown"); } } void InitialOptionsDialog::on_analysisSlider_valueChanged(int value) { ui->analDescription->setText(tr("Level") + QString(": %1").arg(analysisDescription(value))); if (value == 0) { ui->analysisCheckBox->setChecked(false); ui->analysisCheckBox->setText(tr("Analysis: Disabled")); } else { ui->analysisCheckBox->setChecked(true); ui->analysisCheckBox->setText(tr("Analysis: Enabled")); if (value == 3) { ui->analysisoptionsFrame->setVisible(true); ui->advancedAnlysisLine->setVisible(true); } else { ui->analysisoptionsFrame->setVisible(false); ui->advancedAnlysisLine->setVisible(false); } } } void InitialOptionsDialog::on_AdvOptButton_clicked() { if (ui->AdvOptButton->isChecked()) { ui->hideFrame->setVisible(true); ui->AdvOptButton->setArrowType(Qt::DownArrow); } else { ui->hideFrame->setVisible(false); ui->AdvOptButton->setArrowType(Qt::RightArrow); } } void InitialOptionsDialog::on_analysisCheckBox_clicked(bool checked) { if (!checked) { analysisLevel = ui->analysisSlider->value(); } ui->analysisSlider->setValue(checked ? analysisLevel : 0); } void InitialOptionsDialog::on_archComboBox_currentIndexChanged(int) { updateCPUComboBox(); } void InitialOptionsDialog::updatePDBLayout() { ui->pdbWidget->setEnabled(ui->pdbCheckBox->isChecked()); } void InitialOptionsDialog::on_pdbSelectButton_clicked() { QFileDialog dialog(this); dialog.setWindowTitle(tr("Select PDB file")); dialog.setNameFilters({ tr("PDB file (*.pdb)"), tr("All files (*)") }); if (!dialog.exec()) { return; } const QString &fileName = QDir::toNativeSeparators(dialog.selectedFiles().first()); if (!fileName.isEmpty()) { ui->pdbLineEdit->setText(fileName); } } void InitialOptionsDialog::updateScriptLayout() { ui->scriptWidget->setEnabled(ui->scriptCheckBox->isChecked()); } void InitialOptionsDialog::on_scriptSelectButton_clicked() { QFileDialog dialog(this); dialog.setWindowTitle(tr("Select Rizin script file")); dialog.setNameFilters({ tr("Script file (*.rz)"), tr("All files (*)") }); if (!dialog.exec()) { return; } const QString &fileName = QDir::toNativeSeparators(dialog.selectedFiles().first()); if (!fileName.isEmpty()) { ui->scriptLineEdit->setText(fileName); } } void InitialOptionsDialog::reject() { done(0); main->displayNewFileDialog(); }
15,390
C++
.cpp
414
31.427536
96
0.671658
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,495
AboutDialog.cpp
rizinorg_cutter/src/dialogs/AboutDialog.cpp
#include "core/Cutter.h" #include "AboutDialog.h" #include "ui_AboutDialog.h" #include "RizinPluginsDialog.h" #include "common/Configuration.h" #include "common/BugReporting.h" #include <QUrl> #include <QTimer> #include <QEventLoop> #include <QJsonObject> #include <QProgressBar> #include <QProgressDialog> #include <UpdateWorker.h> #include <QtNetwork/QNetworkRequest> #include <QtNetwork/QNetworkAccessManager> #include "CutterConfig.h" AboutDialog::AboutDialog(QWidget *parent) : QDialog(parent), ui(new Ui::AboutDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & (~Qt::WindowContextHelpButtonHint)); ui->logoSvgWidget->load(Config()->getLogoFile()); QString aboutString( tr("Version") + " " CUTTER_VERSION_FULL "<br/>" + tr("Using rizin ") + Core()->getRizinVersionReadable() + "<br/>" + buildQtVersionString() + "<p><b>" + tr("Optional Features:") + "</b><br/>" + QString("Python: %1<br/>") .arg( #ifdef CUTTER_ENABLE_PYTHON "ON" #else "OFF" #endif ) + QString("Python Bindings: %2</p>") .arg( #ifdef CUTTER_ENABLE_PYTHON_BINDINGS "ON" #else "OFF" #endif ) + "<h2>" + tr("License") + "</h2>" + tr("This Software is released under the GNU General Public License v3.0") + "<h2>" + tr("Authors") + "</h2>" + tr("Cutter is developed by the community and maintained by its core and development " "teams.<br/>") + tr("Check our <a " "href='https://github.com/rizinorg/cutter/graphs/contributors'>contributors " "page</a> for the full list of contributors.")); ui->label->setText(aboutString); QSignalBlocker s(ui->updatesCheckBox); ui->updatesCheckBox->setChecked(Config()->getAutoUpdateEnabled()); if (!CUTTER_UPDATE_WORKER_AVAILABLE) { ui->updatesCheckBox->hide(); ui->checkForUpdatesButton->hide(); } } AboutDialog::~AboutDialog() {} void AboutDialog::on_buttonBox_rejected() { close(); } void AboutDialog::on_showVersionButton_clicked() { QMessageBox popup(this); popup.setWindowTitle(tr("Rizin version information")); popup.setTextInteractionFlags(Qt::TextSelectableByMouse); auto versionInformation = Core()->getVersionInformation(); popup.setText(versionInformation); popup.exec(); } void AboutDialog::on_showPluginsButton_clicked() { RizinPluginsDialog dialog(this); dialog.exec(); } void AboutDialog::on_Issue_clicked() { openIssue(); } void AboutDialog::on_checkForUpdatesButton_clicked() { #if CUTTER_UPDATE_WORKER_AVAILABLE UpdateWorker updateWorker; QProgressDialog waitDialog; QProgressBar *bar = new QProgressBar(&waitDialog); bar->setMaximum(0); waitDialog.setBar(bar); waitDialog.setLabel(new QLabel(tr("Checking for updates..."), &waitDialog)); connect(&updateWorker, &UpdateWorker::checkComplete, &waitDialog, &QProgressDialog::cancel); connect(&updateWorker, &UpdateWorker::checkComplete, [&updateWorker](const QVersionNumber &version, const QString &error) { if (!error.isEmpty()) { QMessageBox::critical(nullptr, tr("Error!"), error); } else { if (version <= UpdateWorker::currentVersionNumber()) { QMessageBox::information(nullptr, tr("Version control"), tr("Cutter is up to date!")); } else { updateWorker.showUpdateDialog(false); } } }); updateWorker.checkCurrentVersion(7000); waitDialog.exec(); #endif } void AboutDialog::on_updatesCheckBox_stateChanged(int) { Config()->setAutoUpdateEnabled(!Config()->getAutoUpdateEnabled()); } static QString compilerString() { #if defined(Q_CC_CLANG) // must be before GNU, because clang claims to be GNU too QString isAppleString; # if defined(__apple_build_version__) // Apple clang has other version numbers isAppleString = QLatin1String(" (Apple)"); # endif return QLatin1String("Clang ") + QString::number(__clang_major__) + QLatin1Char('.') + QString::number(__clang_minor__) + isAppleString; #elif defined(Q_CC_GNU) return QLatin1String("GCC ") + QLatin1String(__VERSION__); #elif defined(Q_CC_MSVC) if (_MSC_VER > 1999) return QLatin1String("MSVC <unknown>"); if (_MSC_VER >= 1910) return QLatin1String("MSVC 2017"); if (_MSC_VER >= 1900) return QLatin1String("MSVC 2015"); #endif return QLatin1String("<unknown compiler>"); } QString AboutDialog::buildQtVersionString(void) { return tr("Based on Qt %1 (%2, %3 bit)") .arg(QLatin1String(qVersion()), compilerString(), QString::number(QSysInfo::WordSize)); }
5,077
C++
.cpp
137
29.613139
99
0.626702
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
4,496
MultitypeFileSaveDialog.cpp
rizinorg_cutter/src/dialogs/MultitypeFileSaveDialog.cpp
#include "CutterConfig.h" #include "MultitypeFileSaveDialog.h" #include <QMessageBox> MultitypeFileSaveDialog::MultitypeFileSaveDialog(QWidget *parent, const QString &caption, const QString &directory) : QFileDialog(parent, caption, directory) { this->setAcceptMode(AcceptMode::AcceptSave); this->setFileMode(QFileDialog::AnyFile); connect(this, &QFileDialog::filterSelected, this, &MultitypeFileSaveDialog::onFilterSelected); } void MultitypeFileSaveDialog::setTypes( const QVector<MultitypeFileSaveDialog::TypeDescription> types, bool useDetection) { this->hasTypeDetection = useDetection; this->types.clear(); this->types.reserve(types.size() + (useDetection ? 1 : 0)); if (useDetection) { this->types.push_back(TypeDescription { tr("Detect type (*)"), "", QVariant() }); } this->types.append(types); QStringList filters; for (auto &type : this->types) { filters.append(type.description); } setNameFilters(filters); onFilterSelected(this->types.first().description); } MultitypeFileSaveDialog::TypeDescription MultitypeFileSaveDialog::selectedType() const { auto filterIt = findType(this->selectedNameFilter()); if (filterIt == this->types.end()) { return {}; } if (hasTypeDetection && filterIt == this->types.begin()) { QFileInfo info(this->selectedFiles().first()); QString currentSuffix = info.suffix(); filterIt = std::find_if(types.begin(), types.end(), [&currentSuffix](const TypeDescription &v) { return currentSuffix == v.extension; }); if (filterIt != types.end()) { return *filterIt; } return {}; } else { return *filterIt; } } void MultitypeFileSaveDialog::done(int r) { if (r == QDialog::Accepted) { QFileInfo info(selectedFiles().first()); auto selectedType = this->selectedType(); if (selectedType.extension.isEmpty()) { QMessageBox::warning(this, tr("File save error"), tr("Unrecognized extension '%1'").arg(info.suffix())); return; } } QFileDialog::done(r); } void MultitypeFileSaveDialog::onFilterSelected(const QString &filter) { auto it = findType(filter); if (it == types.end()) { return; } bool detectionSelected = hasTypeDetection && it == types.begin(); if (detectionSelected) { setDefaultSuffix(types[1].extension); } else { setDefaultSuffix(it->extension); } if (!this->selectedFiles().empty()) { QString currentSelection = this->selectedFiles().first(); QFileInfo info(currentSelection); if (!detectionSelected) { QString currentSuffix = info.suffix(); if (currentSuffix != it->extension) { selectFile(info.dir().filePath(info.completeBaseName() + "." + it->extension)); } } } } QVector<MultitypeFileSaveDialog::TypeDescription>::const_iterator MultitypeFileSaveDialog::findType(const QString &description) const { return std::find_if(types.begin(), types.end(), [&description](const TypeDescription &v) { return v.description == description; }); }
3,381
C++
.cpp
92
29.195652
98
0.632012
rizinorg/cutter
15,656
1,143
512
GPL-3.0
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false