Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/features/brightness/BrightnessPanel.qml

Raw
pragma ComponentBehavior: Bound
import QtQuick
import "../.."
import "../../Util.js" as Util

Flickable {
    id: root

    required property Theme theme
    required property Brightness brightnessService
    // Presets need one controllable display; the all-displays slider needs two,
    // since for one it would repeat that display's own slider.
    readonly property bool hasGlobal: brightnessService.globalMode !== "none"
    readonly property bool showGlobal: hasGlobal && brightnessService.globalLevels.length >= 2
    readonly property bool adaptiveMode: brightnessService.adaptiveEnabled && brightnessService.adaptiveAvailable
    // The only controllable display's slider while no all-displays slider shows.
    property Item soleSlider: null
    // Opening focuses the all-displays slider, else the only display's slider, or
    // setup while no display is controllable (FeatureEntry.qml).
    readonly property Item initialFocus: showGlobal ? globalSlider : soleSlider || setupButton
    signal configureRequested
    property int expandedBucket: -1
    property string lowerDraft: ""
    property string upperDraft: ""
    property string thresholdError: ""
    // Threshold fields take digits only, up to the sensor's largest count
    // (4294967295), and are wide enough for all of them.
    readonly property real thresholdFieldWidth: Math.ceil(thresholdMetrics.advanceWidth) + 2 * theme.spaceMd + 4
    TextMetrics {
        id: thresholdMetrics

        font.family: root.theme.fontSans
        font.pixelSize: root.theme.textBody
        text: "0000000000"
    }
    RegularExpressionValidator {
        id: thresholdDigits

        regularExpression: /\d{0,10}/
    }
    onThresholdErrorChanged: if (thresholdError.length > 0)
        Qt.callLater(() => Util.revealIn(thresholdWarning, root))
    onAdaptiveModeChanged: if (!adaptiveMode)
        closeThresholds()

    function bucketName(index) {
        return ["dark", "dim", "bright", "sunlight"][index] || "";
    }

    function bucketRange(index) {
        const edges = brightnessService.adaptiveThresholds;
        return index === 0 ? `below ${edges[0]}` : index === 3 ? `${edges[2]} and above` : `${edges[index - 1]}–${edges[index] - 1}`;
    }

    function openThresholds(index) {
        if (expandedBucket === index) {
            closeThresholds();
            return;
        }
        expandedBucket = index;
        lowerDraft = index > 0 ? String(brightnessService.adaptiveThresholds[index - 1]) : "0";
        upperDraft = index < 3 ? String(brightnessService.adaptiveThresholds[index]) : "";
        thresholdError = "";
    }

    function closeThresholds() {
        const previous = expandedBucket;
        expandedBucket = -1;
        thresholdError = "";
        if (previous >= 0) {
            const button = presets.itemAt(previous);
            if (button)
                button.forceActiveFocus(Qt.OtherFocusReason);
        }
    }

    function commitThreshold(index, draft) {
        if (!/^\d+$/.test(draft)) {
            thresholdError = "enter a whole number";
            return;
        }
        const value = Number(draft);
        const edges = brightnessService.adaptiveThresholds;
        if (!Number.isSafeInteger(value) || value <= 0 || (index > 0 && value <= edges[index - 1]) || (index < 2 && value >= edges[index + 1])) {
            thresholdError = "thresholds must stay ordered";
            return;
        }
        thresholdError = brightnessService.setAdaptiveThreshold(index, value) ? "" : "thresholds must stay ordered";
    }

    function setAllAt(level) {
        if (brightnessService && hasGlobal)
            brightnessService.setAll(Math.max(0, Math.min(1, level)));
    }

    function setDisplayAt(id, level) {
        if (brightnessService)
            brightnessService.setDisplay(id, Math.max(0, Math.min(1, level)));
    }

    width: parent ? parent.width : 0
    contentWidth: width
    contentHeight: brightnessCol.height
    // The card fits the content; the entry height caps it (FeatureEntry.qml).
    readonly property real naturalHeight: contentHeight
    // Positioners update after visibility changes; reveal feedback after their
    // final content size, not against the previous collapsed geometry.
    onContentHeightChanged: if (thresholdError.length > 0)
        Qt.callLater(() => Util.revealIn(thresholdWarning, root))
    clip: true
    interactive: contentHeight > height
    boundsBehavior: Flickable.StopAtBounds
    flickableDirection: Flickable.VerticalFlick

    StableListModel {
        id: displayModel
        rows: root.brightnessService.displays
    }

    Column {
        id: brightnessCol

        width: root.width
        spacing: 12

        // The chip already names brightness; the first row is adaptive's state
        // beside its toggle, and absent without a light sensor route.
        Row {
            id: headingRow

            // Adaptive needs monitor control; until setup is done its button is the next step.
            visible: root.brightnessService.adaptiveRoute && root.brightnessService.setupReady
            width: parent.width
            spacing: 12

            NuguText {
                objectName: "adaptiveStatus"
                width: parent.width - adaptiveToggle.width - headingRow.spacing
                anchors.verticalCenter: parent.verticalCenter
                theme: root.theme
                variant: "meta"
                wrapMode: Text.Wrap
                color: root.brightnessService.adaptiveError || root.brightnessService.persistenceError ? root.theme.warning : root.theme.content.minor
                text: root.brightnessService.adaptiveError || root.brightnessService.persistenceError || (!root.brightnessService.adaptiveAvailable ? "light sensor unavailable" : !root.brightnessService.adaptiveEnabled ? "manual" : root.brightnessService.currentBucket >= 0 ? root.bucketName(root.brightnessService.currentBucket) : "reading light")
            }

            PopupButton {
                id: adaptiveToggle

                anchors.verticalCenter: parent.verticalCenter
                theme: root.theme
                text: "adaptive"
                checked: root.brightnessService.adaptiveEnabled
                enabled: root.brightnessService.adaptiveAvailable
                tooltip: !root.brightnessService.adaptiveAvailable ? "light sensor unavailable" : "follow room light"
                onControlFocusedChanged: if (controlFocused)
                    Util.revealIn(this, root)
                onClicked: root.brightnessService.toggleAdaptive()
            }
        }

        // Nothing to adjust and nothing to set up: say why and what to check.
        NuguText {
            visible: displayModel.count === 0 || (!root.hasGlobal && !root.brightnessService.setupNeeded && !root.brightnessService.setupReady && !root.brightnessService.setupExpanded)
            width: parent.width
            theme: root.theme
            wrapMode: Text.Wrap
            text: displayModel.count === 0 ? "no displays found" : displayModel.count === 1 ? "this display does not accept brightness changes; check its cable and the monitor menu" : "no display accepts brightness changes; check the cables and monitor menus"
        }

        PopupCard {
            width: parent.width
            height: 48
            visible: root.showGlobal
            theme: root.theme

            NuguText {
                id: globalIcon

                anchors.left: parent.left
                anchors.verticalCenter: parent.verticalCenter
                theme: root.theme
                font.family: root.theme.fontIcon
                font.pixelSize: 18
                text: "󰃟"
                Accessible.ignored: true
            }

            PopupSlider {
                id: globalSlider

                anchors.left: globalIcon.right
                anchors.leftMargin: 14
                anchors.right: parent.right
                anchors.verticalCenter: parent.verticalCenter
                theme: root.theme
                enabled: !root.brightnessService.setupRunning
                smoothChanges: root.brightnessService.adaptiveActive
                Accessible.name: "all displays brightness"
                onActiveFocusChanged: if (activeFocus)
                    Util.revealIn(this, root)
                levels: root.brightnessService.globalMode === "mixed" ? root.brightnessService.globalLevels : []
                value: root.brightnessService.globalLevel
                onMoved: value => root.setAllAt(value)
            }
        }

        Grid {
            id: presetGrid

            width: parent.width
            visible: root.hasGlobal
            columns: 4
            columnSpacing: 8

            Repeater {
                id: presets

                model: [0.25, 0.5, 0.75, 1]

                delegate: PopupButton {
                    id: preset

                    required property real modelData
                    readonly property int bucketIndex: Math.round(modelData * 4) - 1
                    readonly property string levelIcon: ["󰃝", "󰃞", "󰃟", "󰃠"][bucketIndex]

                    theme: root.theme
                    width: Math.floor((presetGrid.width - presetGrid.columnSpacing * (presetGrid.columns - 1)) / presetGrid.columns)
                    implicitHeight: 48
                    text: root.adaptiveMode ? root.bucketName(bucketIndex) : `${Math.round(preset.modelData * 100)}%`
                    showText: false
                    enabled: !root.brightnessService.setupRunning
                    checked: root.adaptiveMode && root.brightnessService.currentBucket === bucketIndex
                    accessibleName: root.adaptiveMode ? `${text} ambient bucket` : `${root.showGlobal ? "all displays " : ""}brightness ${text}`
                    tooltip: root.adaptiveMode ? `${text} · light ${root.bucketRange(bucketIndex)}${checked ? " · now" : ""}; edit thresholds` : accessibleName

                    Column {
                        anchors.centerIn: parent
                        spacing: 2

                        NuguText {
                            anchors.horizontalCenter: parent.horizontalCenter
                            theme: root.theme
                            font.family: root.theme.fontIcon
                            font.pixelSize: 18
                            text: preset.levelIcon
                            Accessible.ignored: true
                        }

                        NuguText {
                            anchors.horizontalCenter: parent.horizontalCenter
                            theme: root.theme
                            font.pixelSize: root.theme.textMeta
                            text: preset.text
                            Accessible.ignored: true
                        }
                    }
                    onControlFocusedChanged: if (controlFocused)
                        Util.revealIn(this, root)
                    onClicked: {
                        if (root.adaptiveMode)
                            root.openThresholds(bucketIndex);
                        else
                            root.setAllAt(preset.modelData);
                    }
                }
            }
        }

        Column {
            visible: root.adaptiveMode && root.expandedBucket >= 0
            width: parent.width
            spacing: 8

            Row {
                spacing: 8

                // Reads as a sentence: "dim: light from [10] below [50] · now 32".
                NuguText {
                    anchors.verticalCenter: parent.verticalCenter
                    theme: root.theme
                    text: `${root.bucketName(root.expandedBucket)}:`
                }

                NuguText {
                    anchors.verticalCenter: parent.verticalCenter
                    theme: root.theme
                    variant: "meta"
                    text: root.expandedBucket > 0 ? "light from" : "light below"
                }

                PopupTextField {
                    id: lowerThreshold

                    localEscape: true
                    visible: root.expandedBucket > 0
                    width: root.thresholdFieldWidth
                    input.validator: thresholdDigits
                    theme: root.theme
                    accessibleName: `${root.bucketName(root.expandedBucket)} lower threshold`
                    inputMethodHints: Qt.ImhDigitsOnly
                    text: root.lowerDraft
                    onEdited: value => root.lowerDraft = value
                    onAccepted: root.commitThreshold(root.expandedBucket - 1, root.lowerDraft)
                    onCancelled: root.closeThresholds()
                    Connections {
                        target: lowerThreshold.input
                        function onActiveFocusChanged() {
                            if (lowerThreshold.input.activeFocus)
                                Util.revealIn(lowerThreshold, root);
                        }
                    }
                }

                NuguText {
                    visible: root.expandedBucket > 0 && root.expandedBucket < 3
                    anchors.verticalCenter: parent.verticalCenter
                    theme: root.theme
                    variant: "meta"
                    text: "below"
                }

                PopupTextField {
                    id: upperThreshold

                    localEscape: true
                    visible: root.expandedBucket < 3
                    width: root.thresholdFieldWidth
                    input.validator: thresholdDigits
                    theme: root.theme
                    accessibleName: `${root.bucketName(root.expandedBucket)} upper threshold`
                    inputMethodHints: Qt.ImhDigitsOnly
                    text: root.upperDraft
                    onEdited: value => root.upperDraft = value
                    onAccepted: root.commitThreshold(root.expandedBucket, root.upperDraft)
                    onCancelled: root.closeThresholds()
                    Connections {
                        target: upperThreshold.input
                        function onActiveFocusChanged() {
                            if (upperThreshold.input.activeFocus)
                                Util.revealIn(upperThreshold, root);
                        }
                    }
                }

                // The current reading puts the raw light levels in context.
                NuguText {
                    visible: typeof root.brightnessService.adaptiveRaw === "number"
                    anchors.verticalCenter: parent.verticalCenter
                    theme: root.theme
                    variant: "meta"
                    text: `· now ${Math.round(root.brightnessService.adaptiveRaw)}`
                }
            }

            NuguText {
                id: thresholdWarning
                objectName: "thresholdWarning"

                visible: root.thresholdError.length > 0
                width: parent.width
                theme: root.theme
                color: root.theme.warning
                variant: "meta"
                wrapMode: Text.Wrap
                text: root.thresholdError
            }
        }

        Repeater {
            model: displayModel

            delegate: PopupCard {
                id: displayRow

                required property var rowData
                readonly property bool controllable: !!rowData.controllable
                readonly property string issue: String(rowData.issue || "")
                readonly property real level: Math.max(0, Math.min(1, Number(rowData.level || 0)))

                theme: root.theme
                padding: 0
                width: root.width
                height: 44
                Accessible.name: String(rowData.name || "display")
                Accessible.description: issue

                NuguText {
                    id: displayIcon

                    anchors.left: parent.left
                    anchors.leftMargin: 10
                    anchors.verticalCenter: parent.verticalCenter
                    theme: root.theme
                    font.family: root.theme.fontIcon
                    font.pixelSize: 18
                    text: "󰍹"
                    Accessible.ignored: true
                }

                NuguText {
                    id: displayName

                    anchors.left: displayIcon.right
                    anchors.leftMargin: 10
                    anchors.verticalCenter: parent.verticalCenter
                    // Without a slider the name takes the row up to its status.
                    width: displayRow.controllable ? root.width * 0.34 : Math.max(0, displayRow.width - x - 10 - (issueBadge.visible ? issueBadge.width + 10 : 0))
                    theme: root.theme
                    text: String(displayRow.rowData.name || "display").toLowerCase()
                    elide: Text.ElideRight
                }

                PopupSlider {
                    id: displaySlider

                    anchors.left: displayName.right
                    anchors.leftMargin: 10
                    anchors.right: displayPercent.left
                    anchors.rightMargin: 10
                    anchors.verticalCenter: parent.verticalCenter
                    theme: root.theme
                    visible: displayRow.controllable
                    smoothChanges: root.brightnessService.adaptiveActive
                    enabled: displayRow.controllable && !root.brightnessService.setupRunning
                    Accessible.name: `${displayName.text} brightness`
                    onActiveFocusChanged: if (activeFocus)
                        Util.revealIn(this, root)
                    Accessible.description: displayRow.issue
                    value: displayRow.level
                    onMoved: value => root.setDisplayAt(String(displayRow.rowData.id), value)
                }

                Binding {
                    when: displayRow.controllable && !root.showGlobal
                    target: root
                    property: "soleSlider"
                    value: displaySlider
                }

                NuguText {
                    id: displayPercent

                    anchors.right: issueBadge.visible ? issueBadge.left : parent.right
                    anchors.rightMargin: 10
                    anchors.verticalCenter: parent.verticalCenter
                    width: 44
                    theme: root.theme
                    variant: "meta"
                    visible: displayRow.controllable
                    text: displayRow.controllable ? `${Math.round((root.brightnessService.adaptiveActive ? displaySlider.displayedValue : displayRow.level) * 100)}%` : ""
                    horizontalAlignment: Text.AlignRight
                }

                NuguText {
                    id: issueBadge

                    visible: displayRow.issue.length > 0
                    anchors.right: parent.right
                    anchors.rightMargin: 10
                    anchors.verticalCenter: parent.verticalCenter
                    width: Math.min(Math.ceil(issueMetrics.advanceWidth), displayRow.controllable ? 90 : displayRow.width * 0.5)
                    theme: root.theme
                    variant: "meta"
                    text: displayRow.issue.toLowerCase()
                    color: root.theme.warning
                    elide: Text.ElideRight
                    horizontalAlignment: Text.AlignRight
                }

                // The status's natural width, independent of the badge's own size.
                TextMetrics {
                    id: issueMetrics

                    font: issueBadge.font
                    text: issueBadge.text
                }
            }
        }

        PopupButton {
            id: setupButton
            visible: root.brightnessService.setupNeeded || root.brightnessService.setupReady || root.brightnessService.setupExpanded
            theme: root.theme
            text: "configure light"
            onControlFocusedChanged: if (controlFocused)
                Util.revealIn(this, root)
            onClicked: root.configureRequested()
        }
    }
}