diff --git a/AdaptiveBrightness/monitor.hpp b/AdaptiveBrightness/monitor.hpp index 21b9c30..bd6a368 100644 --- a/AdaptiveBrightness/monitor.hpp +++ b/AdaptiveBrightness/monitor.hpp @@ -2,7 +2,9 @@ #ifdef _MSC_VER + #include #include + #include #include #include @@ -46,6 +48,8 @@ class Monitor { const HMONITOR m_hMonitor; const PhysicalMonitor m_physicalMonitor; + + std::optional> m_brightnessRange; }; #endif diff --git a/AdaptiveBrightness/monitor_win.cpp b/AdaptiveBrightness/monitor_win.cpp index d800a6d..d0e469d 100644 --- a/AdaptiveBrightness/monitor_win.cpp +++ b/AdaptiveBrightness/monitor_win.cpp @@ -34,7 +34,35 @@ Monitor::~Monitor() bool Monitor::setBrightness(float percentage) { - return false; + if(!m_brightnessRange) { + qDebug(ltr("No brightness range known for monitor '%1' with handle '0x%2' and physical handle '0x%3'") + .arg(m_physicalMonitor.name) + .arg(reinterpret_cast(m_hMonitor), 0, 16) + .arg(reinterpret_cast(m_physicalMonitor.handle), 0, 16)); + + if(std::isnan(getBrightness())) + return false; + } + + const auto mappedBrightness = map(percentage, 0.f, 1.f, m_brightnessRange->first, m_brightnessRange->second); + const auto newBrightness = std::clamp(std::round(mappedBrightness), m_brightnessRange->first, m_brightnessRange->second); + + if(!SetMonitorBrightness(m_physicalMonitor.handle, newBrightness)) { + qCritical(ltr("Failed to set brightness of monitor '%1' with handle '0x%2' and physical handle '0x%3', error: %4") + .arg(m_physicalMonitor.name) + .arg(reinterpret_cast(m_hMonitor), 0, 16) + .arg(reinterpret_cast(m_physicalMonitor.handle), 0, 16) + .arg(getLastErrorString())); + return false; + } + + qDebug(ltr("Setting brightness of monitor '%1' with handle '0x%2' and physical handle '0x%3' to %4") + .arg(m_physicalMonitor.name) + .arg(reinterpret_cast(m_hMonitor), 0, 16) + .arg(reinterpret_cast(m_physicalMonitor.handle), 0, 16) + .arg(newBrightness)); + + return true; } float Monitor::getBrightness() @@ -57,6 +85,8 @@ float Monitor::getBrightness() return NAN; } + m_brightnessRange = std::pair{minBrightness, maxBrightness}; + return std::clamp(map(brightness, minBrightness, maxBrightness, 0.f, 1.f), 0.f, 1.f); }