Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/macos/include/display_device/macos/mac_api_layer.h
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ namespace display_device {
*/
[[nodiscard]] std::string getDeviceId(MacDisplayId display_id) const override;

/**
* @copydoc MacApiLayerInterface::getDeviceIdAlias
*/
[[nodiscard]] std::string getDeviceIdAlias(MacDisplayId display_id) const override;

/**
* @copydoc MacApiLayerInterface::getCurrentDisplayMode
*/
Expand Down
10 changes: 10 additions & 0 deletions src/macos/include/display_device/macos/mac_api_layer_interface.h
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,16 @@ namespace display_device {
*/
[[nodiscard]] virtual std::string getDeviceId(MacDisplayId display_id) const = 0;

/**
* @brief Get the other device id a display may have been saved under.
*
* A "macos-cg-*" id depends on whether another online display reports the same vendor, model
* and serial, so a display that stays connected can have had a different id when it was saved.
* @param display_id Display to query.
* @returns The other device id, or empty string if the display only has one.
*/
[[nodiscard]] virtual std::string getDeviceIdAlias(MacDisplayId display_id) const = 0;

/**
* @brief Get the current display mode.
* @param display_id Display to query.
Expand Down
53 changes: 53 additions & 0 deletions src/macos/include/display_device/macos/mac_api_utils.h
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@
*/
#pragma once

// system includes
#include <cstdint>
#include <optional>
#include <string>
#include <vector>

// local includes
#include "types.h"

Expand Down Expand Up @@ -33,4 +39,51 @@ namespace display_device::mac_utils {
* @returns True if resolution matches exactly and refresh rate is close enough.
*/
[[nodiscard]] bool fuzzyCompareModes(const MacDisplayMode &lhs, const MacDisplayMode &rhs);

/**
* @brief CoreGraphics values that identify a display without an EDID or IOKit metadata.
*/
struct CgDisplayInfo {
MacDisplayId m_display_id; ///< Display id (reassigned when a display reconnects).
std::uint32_t m_vendor; ///< CGDisplayVendorNumber value.
std::uint32_t m_model; ///< CGDisplayModelNumber value.
std::uint32_t m_serial; ///< CGDisplaySerialNumber value.
std::uint32_t m_unit; ///< CGDisplayUnitNumber value (depends on connection order).
};

/**
* @brief Check whether a CGDisplaySerialNumber value identifies a display.
* @param serial CGDisplaySerialNumber value.
* @returns False for 0 (no serial) and 0xFFFFFFFF (documented by Apple as an exception value).
*/
[[nodiscard]] bool isUsableCgSerial(std::uint32_t serial);

/**
* @brief Build the identity text hashed into a "macos-cg-*" device id.
*
* Used when a display has neither an EDID nor IOKit metadata, which on Apple Silicon is most
* displays (there are no IODisplayConnect services) and every virtual display. The display id
* and unit number change when a display reconnects or a virtual display is recreated, so they are
* left out when vendor, model and serial identify the display on their own: the serial is usable
* and no other online display reports the same vendor, model and serial. Otherwise they are kept,
* so displays that can't be told apart by serial still get distinct ids.
* @param display Display to build the identity for.
* @param online_displays Every online display (may include `display` itself).
* @returns Text to hash.
*/
[[nodiscard]] std::string makeCgDeviceIdentity(const CgDisplayInfo &display, const std::vector<CgDisplayInfo> &online_displays);

/**
* @brief Build the other identity text a display's "macos-cg-*" device id may have been saved with.
*
* Whether makeCgDeviceIdentity() includes the display id and unit number depends on whether
* another online display reports the same vendor, model and serial, so a display that stays
* connected while such a display is plugged in or unplugged switches between the two forms. This
* returns the form makeCgDeviceIdentity() does not currently give, so a saved id can still be
* matched. Displays without a usable serial only ever have one form.
* @param display Display to build the identity for.
* @param online_displays Every online display (may include `display` itself).
* @returns The other identity text, or nothing if the display has only one.
*/
[[nodiscard]] std::optional<std::string> makeCgDeviceIdentityAlias(const CgDisplayInfo &display, const std::vector<CgDisplayInfo> &online_displays);
} // namespace display_device::mac_utils
3 changes: 3 additions & 0 deletions src/macos/include/display_device/macos/mac_display_device.h
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,9 @@ namespace display_device {
private:
/**
* @brief Resolve a library device id to a CoreGraphics display id.
*
* Matches the display's current device id first, then its alias (see
* MacApiLayerInterface::getDeviceIdAlias) if exactly one online display has it.
* @param device_id Device id to resolve.
* @param query_type Display list type to search.
* @return Display id, or empty optional if not found.
Expand Down
44 changes: 37 additions & 7 deletions src/macos/mac_api_layer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#include <numeric>
#include <sstream>
#include <string>
#include <vector>

// local includes
#include "display_device/logging.h"
Expand Down Expand Up @@ -460,6 +461,28 @@ namespace display_device {
[[nodiscard]] std::string makeDeviceId(const std::string_view prefix, const std::uint64_t hash) {
return std::format("macos-{}-{:016x}", prefix, hash);
}

/**
* @brief Read the CoreGraphics identity values of a display.
* @param display_id Display id.
* @return Identity values.
*/
[[nodiscard]] mac_utils::CgDisplayInfo makeCgDisplayInfo(const MacDisplayId display_id) {
return {display_id, CGDisplayVendorNumber(display_id), CGDisplayModelNumber(display_id), CGDisplaySerialNumber(display_id), CGDisplayUnitNumber(display_id)};
}

/**
* @brief Read the CoreGraphics identity values of every online display.
* @param layer API layer to list the displays with.
* @return Identity values.
*/
[[nodiscard]] std::vector<mac_utils::CgDisplayInfo> makeOnlineCgDisplayInfos(const MacApiLayer &layer) {
std::vector<mac_utils::CgDisplayInfo> online_displays;
for (const auto online_id : layer.getDisplayIds(MacQueryType::Online)) {
online_displays.push_back(makeCgDisplayInfo(online_id));
}
return online_displays;
}
} // namespace

bool MacApiLayer::isApiAccessAvailable() const {
Expand Down Expand Up @@ -588,13 +611,20 @@ namespace display_device {
}
}

std::ostringstream fallback;
fallback << "vendor=" << CGDisplayVendorNumber(display_id) << ';'
<< "model=" << CGDisplayModelNumber(display_id) << ';'
<< "serial=" << CGDisplaySerialNumber(display_id) << ';'
<< "unit=" << CGDisplayUnitNumber(display_id) << ';'
<< "display=" << display_id;
return makeDeviceId("cg", hashText(fallback.str()));
return makeDeviceId("cg", hashText(mac_utils::makeCgDeviceIdentity(makeCgDisplayInfo(display_id), makeOnlineCgDisplayInfos(*this))));
}

std::string MacApiLayer::getDeviceIdAlias(const MacDisplayId display_id) const {
// Only "macos-cg-*" ids have an alias; keep in step with getDeviceId().
if (!getEdid(display_id).empty()) {
return {};
}
if (const auto dictionary {copyDisplayInfo(display_id)}; dictionary && !makeIokitMetadata(dictionary.get()).empty()) {
return {};
}

const auto alias {mac_utils::makeCgDeviceIdentityAlias(makeCgDisplayInfo(display_id), makeOnlineCgDisplayInfos(*this))};
return alias ? makeDeviceId("cg", hashText(*alias)) : std::string {};
}

std::optional<MacDisplayMode> MacApiLayer::getCurrentDisplayMode(const MacDisplayId display_id) const {
Expand Down
60 changes: 60 additions & 0 deletions src/macos/mac_api_utils.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@
#include "display_device/macos/mac_api_utils.h"

// system includes
#include <algorithm>
#include <cmath>
#include <sstream>

namespace display_device::mac_utils {
bool isSuccess(const MacApiError error_code) {
Expand All @@ -27,4 +29,62 @@ namespace display_device::mac_utils {
return lhs.m_resolution == rhs.m_resolution &&
fuzzyCompareRefreshRates(lhs.m_refresh_rate, rhs.m_refresh_rate);
}

bool isUsableCgSerial(const std::uint32_t serial) {
return serial != 0 && serial != 0xFFFFFFFF;
}

namespace {
/**
* @brief Build the identity text from vendor, model and serial only.
* @param display Display to build the identity for.
* @returns Identity text.
*/
[[nodiscard]] std::string makeSerialIdentity(const CgDisplayInfo &display) {
std::ostringstream identity;
identity << "vendor=" << display.m_vendor << ';'
<< "model=" << display.m_model << ';'
<< "serial=" << display.m_serial;
return identity.str();
}

/**
* @brief Build the identity text that also includes the unit number and display id.
* @param display Display to build the identity for.
* @returns Identity text.
*/
[[nodiscard]] std::string makeQualifiedIdentity(const CgDisplayInfo &display) {
std::ostringstream identity;
identity << makeSerialIdentity(display) << ';'
<< "unit=" << display.m_unit << ';'
<< "display=" << display.m_display_id;
return identity.str();
}

/**
* @brief Check whether another online display reports the same vendor, model and serial.
* @param display Display to check.
* @param online_displays Every online display (may include `display` itself).
* @returns True if such a display is online.
*/
[[nodiscard]] bool hasTwinOnline(const CgDisplayInfo &display, const std::vector<CgDisplayInfo> &online_displays) {
return std::ranges::any_of(online_displays, [&display](const CgDisplayInfo &other) {
return other.m_display_id != display.m_display_id && other.m_vendor == display.m_vendor && other.m_model == display.m_model && other.m_serial == display.m_serial;
});
}
} // namespace

std::string makeCgDeviceIdentity(const CgDisplayInfo &display, const std::vector<CgDisplayInfo> &online_displays) {
if (!isUsableCgSerial(display.m_serial) || hasTwinOnline(display, online_displays)) {
return makeQualifiedIdentity(display);
}
return makeSerialIdentity(display);
}

std::optional<std::string> makeCgDeviceIdentityAlias(const CgDisplayInfo &display, const std::vector<CgDisplayInfo> &online_displays) {
if (!isUsableCgSerial(display.m_serial)) {
return std::nullopt;
}
return hasTwinOnline(display, online_displays) ? makeSerialIdentity(display) : makeQualifiedIdentity(display);
}
} // namespace display_device::mac_utils
24 changes: 22 additions & 2 deletions src/macos/mac_display_device_general.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
#include "display_device/macos/mac_display_device.h"

// system includes
#include <algorithm>
#include <stdexcept>

// local includes
Expand Down Expand Up @@ -78,12 +79,31 @@
return std::nullopt;
}

for (const auto display_id : m_m_api->getDisplayIds(query_type)) {
const auto display_ids {m_m_api->getDisplayIds(query_type)};
for (const auto display_id : display_ids) {
if (m_m_api->getDeviceId(display_id) == device_id) {
return display_id;
}
}

return std::nullopt;
// The id may have been saved while a display with the same vendor, model and serial was (or
// wasn't) online, in which case it is now the display's alias. Twins can't be told apart, so
// accept the alias only if exactly one online display has it.
std::optional<MacDisplayId> alias_match;
for (const auto display_id : query_type == MacQueryType::Online ? display_ids : m_m_api->getDisplayIds(MacQueryType::Online)) {
if (m_m_api->getDeviceIdAlias(display_id) != device_id) {
continue;
}
if (alias_match) {

Check failure on line 97 in src/macos/mac_display_device_general.cpp

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use has_value() or another member function to clarify that the code tests the presence of a value in the "optional", not the contained "unsigned int" value itself.

See more on https://sonarcloud.io/project/issues?id=LizardByte_libdisplaydevice&issues=AaID5sS_pW6TBiJYoucl&open=AaID5sS_pW6TBiJYoucl&pullRequest=332
DD_LOG(warning) << "Device id " << device_id << " matches more than one display with the same vendor, model and serial; not resolving it.";
return std::nullopt;
}
alias_match = display_id;
}

if (alias_match && std::ranges::find(display_ids, *alias_match) == std::ranges::end(display_ids)) {
return std::nullopt;
}
return alias_match;
}
} // namespace display_device
65 changes: 65 additions & 0 deletions tests/unit/macos/test_mac_api_utils.cpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
// system includes
#include <format>

// local includes
#include "display_device/macos/mac_api_utils.h"
#include "fixtures/fixtures.h"
Expand Down Expand Up @@ -25,3 +28,65 @@ TEST_S(FuzzyCompareModes) {
EXPECT_FALSE(display_device::mac_utils::fuzzyCompareModes({{1920, 720}, {60, 1}}, {{1920, 1080}, {60, 1}}));
EXPECT_FALSE(display_device::mac_utils::fuzzyCompareModes({{1920, 1080}, {60, 1}}, {{1920, 1080}, {50, 1}}));
}

TEST_S(IsUsableCgSerial) {
EXPECT_TRUE(display_device::mac_utils::isUsableCgSerial(1398099505));
EXPECT_FALSE(display_device::mac_utils::isUsableCgSerial(0));
EXPECT_FALSE(display_device::mac_utils::isUsableCgSerial(0xFFFFFFFF));
}

TEST_S(MakeCgDeviceIdentity) {
using display_device::mac_utils::CgDisplayInfo;
using display_device::mac_utils::makeCgDeviceIdentity;

// A unique serial: the identity survives the display id and unit number changing (reconnects,
// virtual displays being recreated).
const CgDisplayInfo virtual_display {9, 22084, 1, 1398099505, 2};
const CgDisplayInfo recreated {30, 22084, 1, 1398099505, 3};
const CgDisplayInfo other_panel {1, 1552, 41007, 7, 0};
EXPECT_EQ(makeCgDeviceIdentity(virtual_display, {virtual_display, other_panel}), "vendor=22084;model=1;serial=1398099505");
EXPECT_EQ(makeCgDeviceIdentity(virtual_display, {virtual_display}), makeCgDeviceIdentity(recreated, {recreated}));

// No usable serial (0, or Apple's 0xFFFFFFFF exception value): the display id and unit number
// are all that tell identical displays apart.
for (const auto serial : {0U, 0xFFFFFFFFU}) {
const CgDisplayInfo first {1, 1552, 41007, serial, 0};
const CgDisplayInfo second {2, 1552, 41007, serial, 1};
EXPECT_EQ(makeCgDeviceIdentity(first, {first}), std::format("vendor=1552;model=41007;serial={};unit=0;display=1", serial));
EXPECT_NE(makeCgDeviceIdentity(first, {first, second}), makeCgDeviceIdentity(second, {first, second}));
}

// Two online displays reporting the same vendor, model and serial keep distinct identities.
const CgDisplayInfo twin_a {4, 1552, 41007, 16843009, 0};
const CgDisplayInfo twin_b {5, 1552, 41007, 16843009, 1};
EXPECT_EQ(makeCgDeviceIdentity(twin_a, {twin_a, twin_b}), "vendor=1552;model=41007;serial=16843009;unit=0;display=4");
EXPECT_NE(makeCgDeviceIdentity(twin_a, {twin_a, twin_b}), makeCgDeviceIdentity(twin_b, {twin_a, twin_b}));
// Once the twin is gone, the remaining display gets the stable identity again.
EXPECT_EQ(makeCgDeviceIdentity(twin_a, {twin_a}), "vendor=1552;model=41007;serial=16843009");
}

TEST_S(MakeCgDeviceIdentityAlias) {
using display_device::mac_utils::CgDisplayInfo;
using display_device::mac_utils::makeCgDeviceIdentity;
using display_device::mac_utils::makeCgDeviceIdentityAlias;

const CgDisplayInfo twin_a {4, 1552, 41007, 16843009, 0};
const CgDisplayInfo twin_b {5, 1552, 41007, 16843009, 1};

// A saved alone, then B plugged in: A's saved id becomes its alias, and B has the same alias.
const auto saved_alone {makeCgDeviceIdentity(twin_a, {twin_a})};
EXPECT_EQ(makeCgDeviceIdentityAlias(twin_a, {twin_a, twin_b}), saved_alone);
EXPECT_EQ(makeCgDeviceIdentityAlias(twin_b, {twin_a, twin_b}), saved_alone);

// A saved with B online, then B unplugged (A keeps its display id and unit): A's saved id becomes
// its alias, which only A has.
const auto saved_with_twin {makeCgDeviceIdentity(twin_a, {twin_a, twin_b})};
EXPECT_EQ(makeCgDeviceIdentityAlias(twin_a, {twin_a}), saved_with_twin);
EXPECT_NE(makeCgDeviceIdentityAlias(twin_b, {twin_b}), saved_with_twin);

// No usable serial: only one form.
for (const auto serial : {0U, 0xFFFFFFFFU}) {
const CgDisplayInfo display {1, 1552, 41007, serial, 0};
EXPECT_EQ(makeCgDeviceIdentityAlias(display, {display}), std::nullopt);
}
}
Loading