Skip to content

fix: support ambient light automatic brightness - #122

Merged
fly602 merged 1 commit into
linuxdeepin:release/2500from
fly602:release/2500
Aug 4, 2026
Merged

fix: support ambient light automatic brightness#122
fly602 merged 1 commit into
linuxdeepin:release/2500from
fly602:release/2500

Conversation

@fly602

@fly602 fly602 commented Aug 3, 2026

Copy link
Copy Markdown
Contributor
  1. Add an ambient brightness service backed by iio-sensor-proxy
  2. Convert lux samples into stable brightness recommendations with filtering, hysteresis, and debounce
  3. Coordinate sensor lifecycle with lid, sleep, session, service, and configuration state

Influence:

  1. Publish automatic brightness state and recommendations through org.deepin.dde.AmbientBrightness1
  2. Prevent power-saving and manual brightness paths from conflicting with ambient brightness
  3. Verify sensor lifecycle and brightness policy with unit tests

fix: 支持环境光自动亮度调节

  1. 新增基于iio-sensor-proxy的环境光亮度服务
  2. 通过滤波、滞回和防抖将lux样本转换为稳定的亮度推荐值
  3. 根据合盖、休眠、会话、传感器服务及配置状态管理光感生命周期

Influence:

  1. 通过org.deepin.dde.AmbientBrightness1发布自动亮度状态及推荐值
  2. 避免省电及手动亮度调节路径与环境光自动亮度冲突
  3. 通过单元测试验证光感生命周期及亮度策略

PMS: BUG-372191

Summary by Sourcery

Introduce a DDE ambient brightness plugin that provides automatic brightness recommendations based on ambient light while decoupling it from power settings and integrating tests and build wiring.

New Features:

  • Add a session D-Bus service that reads ambient light from iio-sensor-proxy and publishes automatic brightness recommendations via org.deepin.dde.AmbientBrightness1.
  • Implement a configurable continuous ambient light policy with smoothing, hysteresis, debounce, and lux-to-brightness mapping.
  • Expose a Qt-based model and lifecycle management for ambient brightness tied to lid, sleep, and session state.

Bug Fixes:

  • Stop forcing ambient light auto-brightness off when changing brightness via the shortcut tool, avoiding conflicts with manual adjustments.

Enhancements:

  • Remove legacy ambientLightAdjustBrightness wiring from the power manager in favor of the new dedicated ambient brightness service.
  • Document the ambient brightness module and its continuous policy, including configuration and algorithm behavior.

Build:

  • Wire the new ambient-brightness plugin and its tests into the CMake build and enable CTest support.

Tests:

  • Add unit tests for the ambient brightness policy, model behavior after reset, and service wake/lid debounce timing.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry @fly602, you have reached your weekly rate limit of 500000 diff characters.

Please try again later or upgrade to continue using Sourcery

@sourcery-ai

sourcery-ai Bot commented Aug 3, 2026

Copy link
Copy Markdown

Reviewer's Guide

Introduce a new ambient-brightness plugin that exposes org.deepin.dde.AmbientBrightness1 on D-Bus, implements a configurable continuous ambient light policy backed by iio-sensor-proxy with lifecycle management (lid/sleep/session), adds unit tests and CMake wiring, and removes legacy power config toggles for ambient-light from shortcut and power manager paths so manual brightness changes no longer forcibly disable auto brightness.

File-Level Changes

Change Details Files
Remove legacy ambient-light config usage from shortcut brightness tool and power manager to avoid fighting with the new ambient-brightness service.
  • Stop creating and using DConfig in DisplayController::changeBrightness() to disable ambientLightAdjustBrightness before manual brightness changes.
  • Remove AmbientLightAdjustBrightness Q_PROPERTY, members, setters, and DConfig wiring from PowerManager and powerconstants.
  • Drop the KEY_AMBIENT_LIGHT_ADJUST_BRIGHTNESS constant from shortcut constants.
src/plugin-qt/shortcut/tools/dde-shortcut-tool/displaycontroller.cpp
src/plugin-qt/power/session/powermanager.h
src/plugin-qt/power/session/powermanager.cpp
src/plugin-qt/power/powerconstants.h
src/plugin-qt/shortcut/tools/dde-shortcut-tool/constant.h
Wire up build and testing infrastructure for the new ambient-brightness plugin.
  • Enable CTest at top-level and add ambient-brightness subdirectory to plugin-qt CMake.
  • Define a MODULE library target plugin-ambient-brightness with sources, Qt/DTK dependencies, and install rules for the plugin, DSM metadata, D-Bus service file, and DConfig JSON.
  • Add a tests subdirectory that builds a QtTest executable exercising policy, model, and service behavior and registers it with CTest.
CMakeLists.txt
src/plugin-qt/CMakeLists.txt
src/plugin-qt/ambient-brightness/CMakeLists.txt
src/plugin-qt/ambient-brightness/tests/CMakeLists.txt
Add a new ambient-brightness service plugin that talks to iio-sensor-proxy, manages lifecycle, and exposes automatic brightness state and recommendation over D-Bus.
  • Implement AmbientBrightnessService as a deepin-service-manager plugin exposing org.deepin.dde.AmbientBrightness1 with Supported, State, Enabled, and RecommendedBrightness, and an Enable(bool) method.
  • Connect to net.hadess.SensorProxy on the system bus, handle ClaimLight/ReleaseLight, subscribe to PropertiesChanged for LightLevel, and robustly obtain an initial sample with timeout and fallback property read.
  • Coordinate sensor lifecycle with AmbientLightLifecycleState based on DConfig flag, lid open/close (org.deepin.dde.Power1), system sleep/wake and session Active state (login1), with delayed reconnect via timers to debounce lid-open and recovery events.
  • Drive an AmbientBrightnessModel with monotonic-timestamped lux samples and policy evaluation timers, and publish property changes via org.freedesktop.DBus.Properties.PropertiesChanged on the session bus.
  • Provide plugin entrypoints (DSMRegister/DSMUnRegister) that create, initialize, and destroy a singleton AmbientBrightnessService per D-Bus connection.
src/plugin-qt/ambient-brightness/ambientbrightnessservice.h
src/plugin-qt/ambient-brightness/ambientbrightnessservice.cpp
src/plugin-qt/ambient-brightness/ambientlightlifecyclestate.h
src/plugin-qt/ambient-brightness/plugin.cpp
src/plugin-qt/ambient-brightness/misc/plugin-ambient-brightness.json
src/plugin-qt/ambient-brightness/misc/ambient-brightness.service
src/plugin-qt/ambient-brightness/configs/org.deepin.dde.daemon.ambient-brightness.json
Introduce an algorithm/policy layer to convert lux samples into stable brightness recommendations with filtering, hysteresis, debounce, and configurable mapping modes.
  • Define AmbientBrightnessPolicy, SensorSample, and Recommendation abstractions plus a BrightnessAlgorithm enum and factory functions to create policies with or without DConfig.
  • Implement BrightnessCurve to map lux to [0,1] brightness using log1p-based piecewise-linear interpolation with validation.
  • Implement ContinuousPolicyConfig and ContinuousAmbientLightPolicy that maintain a ring buffer of lux samples, compute fast/slow weighted or raw ambient lux, apply hysteresis and per-direction debounce, support both continuous curve and discrete step modes, and schedule reevaluation via nextEvaluationDelayMs().
  • Implement AmbientBrightnessModel as a QObject wrapper around a policy, tracking Supported/State and emitting recommendedBrightnessChanged only on meaningful changes using fuzzy comparison.
  • Implement policy factory logic that reads DConfig keys (continuousMappingMode, continuousLuxCurve, useWeightedWindows, horizon/debounce/hysteresis parameters), parses JSON curves from QString or QVariantList, validates values, and falls back to safe defaults on invalid config.
  • Add QLoggingCategory for the module and update code to log state transitions and recommendations.
src/plugin-qt/ambient-brightness/ambientbrightnesspolicy.h
src/plugin-qt/ambient-brightness/ambientbrightnesspolicyfactory.h
src/plugin-qt/ambient-brightness/ambientbrightnesspolicyfactory.cpp
src/plugin-qt/ambient-brightness/brightnesscurve.h
src/plugin-qt/ambient-brightness/brightnesscurve.cpp
src/plugin-qt/ambient-brightness/continuous/continuousambientlightpolicy.h
src/plugin-qt/ambient-brightness/continuous/continuousambientlightpolicy.cpp
src/plugin-qt/ambient-brightness/ambientbrightnessmodel.h
src/plugin-qt/ambient-brightness/ambientbrightnessmodel.cpp
src/plugin-qt/ambient-brightness/ambientbrightnesslogging.h
src/plugin-qt/ambient-brightness/ambientbrightnesslogging.cpp
Document the ambient-brightness module and its continuous policy in detail for maintainers and reviewers.
  • Add top-level ambient-brightness README describing module responsibilities, D-Bus interfaces, lifecycle semantics, configuration, and class responsibilities.
  • Add detailed README for ContinuousAmbientLightPolicy explaining sample handling, ring buffer, weighted windows, hysteresis, debounce, mapping modes, and configuration parameters.
src/plugin-qt/ambient-brightness/README.md
src/plugin-qt/ambient-brightness/continuous/README.md
Add unit tests to verify ambient-brightness policy behavior, model republish semantics, and service lifecycle timing.
  • Create a QtTest-based suite exercising ContinuousAmbientLightPolicy default recommendation, config validation/fallback, step classification consistency, debounce at exact thresholds, terminal step scheduling, lux saturation, and high-frequency weighted-window behavior.
  • Test AmbientBrightnessModel to ensure it republishes recommendations after reset/disable->enable cycles.
  • Test that AmbientBrightnessService schedules lid-open wake refresh timers using the darkenDebounceMs delay and that later recovery events do not shorten the lid delay.
  • Link the test target against Qt Core/DBus/Test and Dtk Core and register it with CTest as 'ambient-brightness-policy'.
src/plugin-qt/ambient-brightness/tests/tst_ambientbrightnesspolicy.cpp
src/plugin-qt/ambient-brightness/tests/CMakeLists.txt

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@fly602

fly602 commented Aug 3, 2026

Copy link
Copy Markdown
Contributor Author

/test all

@deepin-ci-robot

Copy link
Copy Markdown

deepin pr auto review

★ 总体评分:90分

■ 【总体评价】

代码实现了环境光自动亮度功能的独立插件模块,架构分层清晰且逻辑正确
逻辑正确且设计良好,因存在部分代码重复扣10分

■ 【详细分析】

  • 1.语法逻辑(完全正确)✓

代码分层合理,插件入口、服务层、模型层和算法层职责分明。AmbientBrightnessService 正确处理了 D-Bus 注册、传感器生命周期和定时器管理。ContinuousAmbientLightPolicy 实现了防抖、滞回和加权窗口算法,逻辑严密。
潜在问题:plugin.cppDSMRegister 函数在重复注册时直接 delete g_service,如果旧实例正在执行异步操作可能存在风险,但在当前单线程插件模型下可接受。
建议:无需重大修改,保持现有逻辑结构。

  • 2.代码质量(良好)✓

命名规范统一,注释详尽,特别是 README.md 和代码内注释极大地提升了可读性。环形缓冲区的实现按需扩容,设计合理。
潜在问题:ambientbrightnessservice.cpp 中的 onAutomaticBrightnessEnabledChangedEnable 方法存在大量重复的停止逻辑代码,违反了 DRY 原则。
建议:提取公共的停止逻辑到一个私有方法如 stopSensorAndDisableModel() 中,供两者调用。

  • 3.代码性能(高效)✓

算法层使用环形缓冲区缓存样本,按需扩容且裁剪窗口外数据,避免了不必要的内存分配。加权窗口计算使用积分函数,复杂度可控。定时器采用单次触发模式,避免了不必要的轮询。
建议:无需修改,性能表现优秀。

  • 4.代码安全(存在0个安全漏洞)✓

漏洞对比统计:新增漏洞 0 个,减少漏洞 0 个,持平 0 个
代码主要处理传感器数值和 D-Bus 通信,输入校验严格。variantToValidLuxBrightnessCurve::isValid 对数值范围和有限性进行了检查。JSON 解析使用 Qt 标准库,无注入风险。除法运算前有严格前置条件保证除数非零。
建议:继续保持严格的输入校验机制。

■ 【改进建议代码示例】

// ambientbrightnessservice.cpp
void AmbientBrightnessService::stopSensorAndDisableModel()
{
    stopInitialSampleWait();
    if (m_evaluationTimer)
        m_evaluationTimer->stop();
    if (m_sensor && m_claimed)
        m_sensor->call(QStringLiteral("ReleaseLight"));
    m_claimed = false;
    m_haveSample = false;
    m_model.setDisabled();
}

void AmbientBrightnessService::onAutomaticBrightnessEnabledChanged(bool enabled)
{
    if (m_lifecycle.enabled == enabled)
        return;
    qCDebug(logAmbientBrightness) << "configured enabled=" << enabled;
    m_lifecycle.enabled = enabled;
    Q_EMIT enabledChanged(enabled);
    publishPropertyChange(QStringLiteral("Enabled"), enabled);
    if (!enabled) {
        stopSensorAndDisableModel();
    } else {
        refreshSensorConnection();
    }
}

void AmbientBrightnessService::Enable(bool active)
{
    qCDebug(logAmbientBrightness) << "enable requested=" << active;
    m_lifecycle.enabled = active;
    Q_EMIT enabledChanged(active);
    publishPropertyChange(QStringLiteral("Enabled"), active);
    if (m_config && m_config->isValid())
        m_config->setValue(QString::fromLatin1(kAmbientLightAdjustBrightnessKey), active);

    if (!active) {
        stopSensorAndDisableModel();
    } else {
        refreshSensorConnection();
    }
}

@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: fly602, robertkill

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

1. Add an ambient brightness service backed by iio-sensor-proxy
2. Convert lux samples into stable brightness recommendations with filtering, hysteresis, and debounce
3. Coordinate sensor lifecycle with lid, sleep, session, service, and configuration state

Influence:
1. Publish automatic brightness state and recommendations through org.deepin.dde.AmbientBrightness1
2. Prevent power-saving and manual brightness paths from conflicting with ambient brightness
3. Verify sensor lifecycle and brightness policy with unit tests

fix: 支持环境光自动亮度调节

1. 新增基于iio-sensor-proxy的环境光亮度服务
2. 通过滤波、滞回和防抖将lux样本转换为稳定的亮度推荐值
3. 根据合盖、休眠、会话、传感器服务及配置状态管理光感生命周期

Influence:
1. 通过org.deepin.dde.AmbientBrightness1发布自动亮度状态及推荐值
2. 避免省电及手动亮度调节路径与环境光自动亮度冲突
3. 通过单元测试验证光感生命周期及亮度策略

PMS: BUG-372191
@fly602
fly602 merged commit e12a5f4 into linuxdeepin:release/2500 Aug 4, 2026
7 of 8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants