From d35a72b6ba5d88c68080183b3cd116c537f728a2 Mon Sep 17 00:00:00 2001 From: DrogaBox Date: Wed, 25 Nov 2026 22:28:29 -0300 Subject: [PATCH 1/3] GPU control: profiles for the card's settings The page can now keep a setup under a name and put it back in one click: a power limit, or the whole fan, clock and voltage state. A profile saves what the kext confirmed, together with the card it was made on (its PCI device id and the limits the kext reported), in the app's defaults under one versioned key. Names are trimmed and unique; a file from a newer build is left alone. Loading goes through the same call the controls make, so every limit is checked again: a profile made on another card still loads, and a value this card does not take now is left out with a sentence under the list while the rest of the state goes as usual. A raised GFX maximum, and a power limit above the start-up one, need "Allow overclocking", as they do by hand. With Remember on, a loaded profile becomes the remembered state once the kext confirms it. Profiles live in Settings > GPU control > Profiles: one row each with Load, Rename and Delete, a checkmark on the one that matches what the card holds now, "Save current settings..." asking for a name in a sheet, and a confirmation before deleting. All strings in every language, a section in docs/GPU_CONTROL.md and a changelog line. ./build.sh --test: 35195 checks OK. --- CHANGELOG.md | 2 + .../RyzenStatus/Core/DefaultsKey+App.swift | 3 + .../Core/GPUControlProfileStrings.swift | 628 ++++++++++++++++++ .../Services/Metrics/GPUControlProfiles.swift | 539 +++++++++++++++ .../Services/Metrics/GPUControlService.swift | 87 +++ .../Settings/GPUControlProfilesSection.swift | 243 +++++++ .../UI/Settings/GPUControlSettingsView.swift | 31 +- Tests/MetricsTests.swift | 1 + Tests/Suites/GPUControlProfileTests.swift | 319 +++++++++ docs/GPU_CONTROL.md | 17 + 10 files changed, 1867 insertions(+), 3 deletions(-) create mode 100644 Sources/RyzenStatus/Core/GPUControlProfileStrings.swift create mode 100644 Sources/RyzenStatus/Services/Metrics/GPUControlProfiles.swift create mode 100644 Sources/RyzenStatus/UI/Settings/GPUControlProfilesSection.swift create mode 100644 Tests/Suites/GPUControlProfileTests.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index 91788dd8..87c4379b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,7 @@ # Changelog +**GPU profiles**: Settings › GPU control has a Profiles section that saves the setup the card holds under a name — a power limit, or the fan curve with zero RPM, the GFX clocks and the voltage — and loads it again in one click. Loading goes through the same path as changing a value by hand, so every limit is checked against the card in front of you: a profile made on another card, or one whose value this card no longer takes, is still listed and still loads, and the section names the part that was left out (a raised clock or power limit needs Allow overclocking). With Remember on, a loaded profile comes back at launch and after a wake like any other change. Names are trimmed and unique, the row that matches what the card holds now is marked, and deleting asks first. Tested with unit tests only. + **GPU power limit, from the optional GPUSensors.kext**: when the kext is loaded and an administrator has allowed GPU changes, Settings › GPU control and the panel can lower the RX 6800 XT's power limit in 10 W steps down to the card's own minimum (225 W on a card that starts at 240 W). The kext checks every request and goes back to the start-up limit on its own when RyzenStatus quits, stops answering or the Mac sleeps; a switch on the page asks for the same limit again after launch and wake, only while changes are allowed and never with a password. Another switch, Allow changes after restart too, asks for an administrator password once and then allows GPU changes again at every startup, so the remembered limit comes back after a restart too; turning it off asks again and removes that step. With GPUSensors.kext 0.8.0, Close Changes closes them again without a password, and on an RX 6900 XT the page shows the readings only. GPUSensors.kext is not public yet; without it, nothing changes. **GPU minimum clock, from GPUSensors.kext 0.9.0**: Settings › GPU control has a GFX minimum clock under the maximum. It only raises the minimum, from the card's stock value up to the GFX maximum in force, and keeps the clock up at idle, so the card draws more power and runs warmer; the kext checks every request, watches the temperature while it is held, and goes back to stock in the same cases as the other GPU changes. The section shows only with GPUSensors.kext 0.9.0. The memory clock, fan minimum speed and fan target temperature stay out: on the RX 6800 XT the driver offers no lower memory clock and no fan minimum or target while it offers the fan curve. Tested with unit tests only. diff --git a/Sources/RyzenStatus/Core/DefaultsKey+App.swift b/Sources/RyzenStatus/Core/DefaultsKey+App.swift index fff038cf..6ccbb921 100644 --- a/Sources/RyzenStatus/Core/DefaultsKey+App.swift +++ b/Sources/RyzenStatus/Core/DefaultsKey+App.swift @@ -1114,4 +1114,7 @@ extension DefaultsKey { /// The "Allow overclocking" switch of Settings > GPU control (off by /// default). static let gpuControlOverclock = "gpuControlOverclock" + /// The owner's GPU profiles, one JSON blob with a version number + /// (`GPUControlProfileStore`). + static let gpuControlProfiles = "gpuControlProfiles" } diff --git a/Sources/RyzenStatus/Core/GPUControlProfileStrings.swift b/Sources/RyzenStatus/Core/GPUControlProfileStrings.swift new file mode 100644 index 00000000..87cfddff --- /dev/null +++ b/Sources/RyzenStatus/Core/GPUControlProfileStrings.swift @@ -0,0 +1,628 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 RyzenStatus + +import Foundation + +/// Settings > GPU control > Profiles: the saved GPU setups. A profile is a +/// name for what the page holds (a power limit, or a fan curve with zero RPM, +/// the GFX clocks and the voltage), and this section loads one with the +/// checks the controls above make. +struct GPUControlProfileStrings { + let section: String + let empty: String + let footer: String + let saveCurrent: String + let saveTitle: String + let renameTitle: String + let nameLabel: String + let saveAction: String + let cancel: String + /// %@ = the name already taken. + let duplicateName: String + let load: String + let rename: String + let delete: String + let deleteTitle: String + /// %@ = the profile's name. + let deleteMessage: String + let matches: String + /// %@ = the profile's name. + let loadedFormat: String + /// %1$@ = the profile's name, %2$@ = what was left out. + let leftOutFormat: String + let raiseNeedsOverclock: String + let otherCard: String + let nothingToSave: String + let listSeparator: String + let listLastSeparator: String + let fieldPower: String + let fieldFanCurve: String + let fieldZeroRpm: String + let fieldGfxMax: String + let fieldGfxMin: String + let fieldVolt: String + let fieldRaise: String + let blockedWriting: String + let blockedDriver: String + let blockedOther: String + let blockedOD8: String + let blockedFan: String + let blockedOutOfRange: String + + /// One part of a profile, in words: the sentence about what was left out. + func field(_ field: GPUControlProfileField) -> String { + switch field { + case .power: return fieldPower + case .fanCurve: return fieldFanCurve + case .zeroRpm: return fieldZeroRpm + case .gfxMax: return fieldGfxMax + case .gfxMin: return fieldGfxMin + case .volt: return fieldVolt + case .raise: return fieldRaise + } + } + + /// Every text, for the tests. + var all: [String] { + [section, empty, footer, saveCurrent, saveTitle, renameTitle, nameLabel, saveAction, cancel, + duplicateName, load, rename, delete, deleteTitle, deleteMessage, matches, loadedFormat, + leftOutFormat, raiseNeedsOverclock, otherCard, nothingToSave, listSeparator, listLastSeparator, + fieldPower, fieldFanCurve, fieldZeroRpm, fieldGfxMax, fieldGfxMin, fieldVolt, fieldRaise, + blockedWriting, blockedDriver, blockedOther, blockedOD8, blockedFan, blockedOutOfRange] + } +} + +extension FeatureStrings { + static func gpuControlProfile(_ language: AppLanguage) -> GPUControlProfileStrings { + switch language { + case .enUS: return .enUS + case .ptBR: return .ptBR + case .tr: return .tr + case .ru: return .ru + case .es: return .es + case .sk: return .sk + case .de: return .de + case .fr: return .fr + case .it: return .it + case .ja: return .ja + case .ko: return .ko + case .zhHans: return .zhHans + case .zhTW, .zhHK: return .zhTW + case .uk: return .uk + } + } +} + +extension GPUControlProfileStrings { + static let enUS = GPUControlProfileStrings( + section: "Profiles", + empty: "No profiles yet.", + footer: "A profile keeps a power limit, or a fan curve with zero RPM, the GFX clocks and the voltage. Loading one sends it the way the controls above do, so every limit is checked again; with Remember on, the card keeps it like any other change.", + saveCurrent: "Save current settings…", + saveTitle: "Save the GPU settings as a profile", + renameTitle: "Rename the profile", + nameLabel: "Name", + saveAction: "Save", + cancel: "Cancel", + duplicateName: "There is already a profile called “%@”.", + load: "Load", + rename: "Rename", + delete: "Delete", + deleteTitle: "Delete this profile?", + deleteMessage: "“%@” is removed from this Mac. What the GPU holds now does not change.", + matches: "This is what the GPU holds now", + loadedFormat: "“%@” is in force.", + leftOutFormat: "“%1$@” went out without %2$@: this card does not take it now.", + raiseNeedsOverclock: "A raised clock or power limit needs Allow overclocking on.", + otherCard: "This profile was made on another card: its values were checked against this one.", + nothingToSave: "Hold a power limit, or a fan, clock or voltage, to save it as a profile.", + listSeparator: ", ", + listLastSeparator: " and ", + fieldPower: "the power limit", + fieldFanCurve: "the fan curve", + fieldZeroRpm: "zero RPM off", + fieldGfxMax: "the GFX maximum", + fieldGfxMin: "the GFX minimum", + fieldVolt: "the voltage", + fieldRaise: "the overclock flag", + blockedWriting: "GPU changes are closed: open them, then load the profile.", + blockedDriver: "The driver has not answered yet: try again in a moment.", + blockedOther: "Another program holds a change: close it before loading a profile.", + blockedOD8: "The fan and clock table could not be read after the restart: restart the Mac to load this profile.", + blockedFan: "This kext build was not checked with fan curves: update the kext, or save the profile without the fan part.", + blockedOutOfRange: "Nothing in this profile is inside this card’s limits now.") + + static let es = GPUControlProfileStrings( + section: "Perfiles", + empty: "Todavía no hay perfiles.", + footer: "Un perfil guarda un límite de potencia, o una curva de ventilador con cero RPM, los relojes de GFX y el voltaje. Al cargarlo se envía como los controles de arriba, así que cada límite se vuelve a comprobar; con Recordar activado, la tarjeta lo mantiene como cualquier otro cambio.", + saveCurrent: "Guardar los ajustes actuales…", + saveTitle: "Guardar los ajustes de la GPU como perfil", + renameTitle: "Cambiar el nombre del perfil", + nameLabel: "Nombre", + saveAction: "Guardar", + cancel: "Cancelar", + duplicateName: "Ya hay un perfil llamado «%@».", + load: "Cargar", + rename: "Renombrar", + delete: "Eliminar", + deleteTitle: "¿Eliminar este perfil?", + deleteMessage: "«%@» se elimina de este Mac. Lo que la GPU mantiene ahora no cambia.", + matches: "Esto es lo que la GPU mantiene ahora", + loadedFormat: "«%@» está en vigor.", + leftOutFormat: "«%1$@» se envió sin %2$@: esta tarjeta no lo acepta ahora.", + raiseNeedsOverclock: "Un reloj o un límite de potencia subido necesita Permitir overclock activado.", + otherCard: "Este perfil se creó en otra tarjeta: sus valores se comprobaron con esta.", + nothingToSave: "Mantén un límite de potencia, o un ventilador, reloj o voltaje, para guardarlo como perfil.", + listSeparator: ", ", + listLastSeparator: " y ", + fieldPower: "el límite de potencia", + fieldFanCurve: "la curva del ventilador", + fieldZeroRpm: "cero RPM desactivado", + fieldGfxMax: "el máximo de GFX", + fieldGfxMin: "el mínimo de GFX", + fieldVolt: "el voltaje", + fieldRaise: "la marca de overclock", + blockedWriting: "Los cambios en la GPU están cerrados: ábrelos y luego carga el perfil.", + blockedDriver: "El driver todavía no responde: inténtalo en un momento.", + blockedOther: "Otro programa mantiene un cambio: ciérralo antes de cargar un perfil.", + blockedOD8: "No se pudo leer la tabla de ventilador y relojes tras el reinicio: reinicia el Mac para cargar este perfil.", + blockedFan: "Esta versión del kext no se comprobó con curvas: actualiza el kext o guarda el perfil sin la parte del ventilador.", + blockedOutOfRange: "Nada de este perfil está dentro de los límites de esta tarjeta ahora.") + + static let ptBR = GPUControlProfileStrings( + section: "Perfis", + empty: "Ainda não há perfis.", + footer: "Um perfil guarda um limite de potência, ou uma curva de ventoinha com zero RPM, os clocks da GFX e a tensão. Ao carregá-lo ele é enviado como os controles acima, então cada limite é conferido de novo; com Lembrar ativado, a placa o mantém como qualquer outra mudança.", + saveCurrent: "Salvar ajustes atuais…", + saveTitle: "Salvar os ajustes da GPU como perfil", + renameTitle: "Renomear o perfil", + nameLabel: "Nome", + saveAction: "Salvar", + cancel: "Cancelar", + duplicateName: "Já existe um perfil chamado “%@”.", + load: "Carregar", + rename: "Renomear", + delete: "Apagar", + deleteTitle: "Apagar este perfil?", + deleteMessage: "“%@” é removido deste Mac. O que a GPU mantém agora não muda.", + matches: "É isto que a GPU mantém agora", + loadedFormat: "“%@” está em vigor.", + leftOutFormat: "“%1$@” foi enviado sem %2$@: esta placa não aceita isso agora.", + raiseNeedsOverclock: "Um clock ou limite de potência elevado precisa de Permitir overclock ativado.", + otherCard: "Este perfil foi criado em outra placa: os valores foram conferidos com esta.", + nothingToSave: "Mantenha um limite de potência, ou uma ventoinha, clock ou tensão, para salvar como perfil.", + listSeparator: ", ", + listLastSeparator: " e ", + fieldPower: "o limite de potência", + fieldFanCurve: "a curva da ventoinha", + fieldZeroRpm: "zero RPM desligado", + fieldGfxMax: "o máximo da GFX", + fieldGfxMin: "o mínimo da GFX", + fieldVolt: "a tensão", + fieldRaise: "a marca de overclock", + blockedWriting: "As mudanças na GPU estão fechadas: abra-as e depois carregue o perfil.", + blockedDriver: "O driver ainda não respondeu: tente em instantes.", + blockedOther: "Outro programa mantém uma mudança: feche-a antes de carregar um perfil.", + blockedOD8: "A tabela de ventoinha e clocks não pôde ser lida após o reinício: reinicie o Mac para carregar este perfil.", + blockedFan: "Esta versão do kext não foi conferida com curvas: atualize o kext ou salve o perfil sem a parte da ventoinha.", + blockedOutOfRange: "Nada neste perfil está dentro dos limites desta placa agora.") + + static let tr = GPUControlProfileStrings( + section: "Profiller", + empty: "Henüz profil yok.", + footer: "Bir profil bir güç sınırını, ya da sıfır RPM'li fan eğrisini, GFX saat hızlarını ve gerilimi saklar. Yüklerken yukarıdaki denetimler gibi gönderilir, böylece her sınır yeniden denetlenir; Hatırla açıksa kart onu diğer değişiklikler gibi korur.", + saveCurrent: "Geçerli ayarları kaydet…", + saveTitle: "GPU ayarlarını profil olarak kaydet", + renameTitle: "Profilin adını değiştir", + nameLabel: "Ad", + saveAction: "Kaydet", + cancel: "Vazgeç", + duplicateName: "“%@” adlı bir profil zaten var.", + load: "Yükle", + rename: "Yeniden adlandır", + delete: "Sil", + deleteTitle: "Bu profil silinsin mi?", + deleteMessage: "“%@” bu Mac'ten kaldırılır. GPU'nun şu an tuttukları değişmez.", + matches: "GPU'nun şu an tuttukları bunlar", + loadedFormat: "“%@” yürürlükte.", + leftOutFormat: "“%1$@” %2$@ olmadan gönderildi: bu kart artık onu kabul etmiyor.", + raiseNeedsOverclock: "Yükseltilmiş bir saat hızı veya güç sınırı için Hız aşırtmaya izin ver açık olmalı.", + otherCard: "Bu profil başka bir kartta oluşturuldu: değerleri bu kartla denetlendi.", + nothingToSave: "Profil olarak kaydetmek için bir güç sınırı, ya da fan, saat hızı veya gerilim tutun.", + listSeparator: ", ", + listLastSeparator: " ve ", + fieldPower: "güç sınırı", + fieldFanCurve: "fan eğrisi", + fieldZeroRpm: "sıfır RPM kapalı", + fieldGfxMax: "GFX üst sınırı", + fieldGfxMin: "GFX alt sınırı", + fieldVolt: "gerilim", + fieldRaise: "hız aşırtma bayrağı", + blockedWriting: "GPU değişiklikleri kapalı: önce açın, sonra profili yükleyin.", + blockedDriver: "Sürücü henüz yanıt vermedi: birazdan tekrar deneyin.", + blockedOther: "Başka bir program bir değişiklik tutuyor: profil yüklemeden önce onu kapatın.", + blockedOD8: "Yeniden başlatmadan sonra fan ve saat tablosu okunamadı: bu profili yüklemek için Mac'i yeniden başlatın.", + blockedFan: "Bu kext sürümü fan eğrileriyle denenmedi: kext'i güncelleyin ya da profili fan bölümü olmadan kaydedin.", + blockedOutOfRange: "Bu profildeki hiçbir değer artık bu kartın sınırları içinde değil.") + + static let ru = GPUControlProfileStrings( + section: "Профили", + empty: "Профилей пока нет.", + footer: "Профиль хранит лимит мощности либо кривую вентилятора с нулевыми оборотами, частоты GFX и напряжение. При загрузке он отправляется так же, как элементы управления выше, поэтому каждый предел проверяется заново; если включено «Запоминать», карта удерживает его как любое другое изменение.", + saveCurrent: "Сохранить текущие настройки…", + saveTitle: "Сохранить настройки GPU как профиль", + renameTitle: "Переименовать профиль", + nameLabel: "Имя", + saveAction: "Сохранить", + cancel: "Отменить", + duplicateName: "Профиль с именем «%@» уже есть.", + load: "Загрузить", + rename: "Переименовать", + delete: "Удалить", + deleteTitle: "Удалить этот профиль?", + deleteMessage: "«%@» будет удалён с этого Mac. То, что сейчас удерживает GPU, не изменится.", + matches: "Это то, что GPU удерживает сейчас", + loadedFormat: "«%@» действует.", + leftOutFormat: "«%1$@» отправлен без %2$@: эта карта сейчас это не принимает.", + raiseNeedsOverclock: "Для повышенной частоты или лимита мощности нужно включить «Разрешить разгон».", + otherCard: "Профиль создан на другой карте: его значения проверены по этой.", + nothingToSave: "Удерживайте лимит мощности либо вентилятор, частоту или напряжение, чтобы сохранить профиль.", + listSeparator: ", ", + listLastSeparator: " и ", + fieldPower: "лимит мощности", + fieldFanCurve: "кривая вентилятора", + fieldZeroRpm: "нулевые обороты выключены", + fieldGfxMax: "максимум GFX", + fieldGfxMin: "минимум GFX", + fieldVolt: "напряжение", + fieldRaise: "флаг разгона", + blockedWriting: "Изменения GPU закрыты: откройте их, затем загрузите профиль.", + blockedDriver: "Драйвер ещё не ответил: попробуйте через минуту.", + blockedOther: "Другая программа удерживает изменение: закройте его перед загрузкой профиля.", + blockedOD8: "После перезагрузки не удалось прочитать таблицу вентилятора и частот: перезагрузите Mac, чтобы загрузить этот профиль.", + blockedFan: "Эта сборка kext не проверялась с кривыми вентилятора: обновите kext или сохраните профиль без вентилятора.", + blockedOutOfRange: "Ничего из этого профиля сейчас не в пределах этой карты.") + + static let sk = GPUControlProfileStrings( + section: "Profily", + empty: "Zatiaľ žiadne profily.", + footer: "Profil uchováva limit výkonu alebo krivku ventilátora s nulovými otáčkami, takty GFX a napätie. Pri načítaní sa odošle ako ovládacie prvky vyššie, takže každý limit sa znova skontroluje; keď je zapnuté Pamätať, karta ho drží ako každú inú zmenu.", + saveCurrent: "Uložiť aktuálne nastavenia…", + saveTitle: "Uložiť nastavenia GPU ako profil", + renameTitle: "Premenovať profil", + nameLabel: "Názov", + saveAction: "Uložiť", + cancel: "Zrušiť", + duplicateName: "Profil s názvom „%@“ už existuje.", + load: "Načítať", + rename: "Premenovať", + delete: "Odstrániť", + deleteTitle: "Odstrániť tento profil?", + deleteMessage: "„%@“ sa odstráni z tohto Macu. To, čo GPU práve drží, sa nemení.", + matches: "Toto GPU práve drží", + loadedFormat: "„%@“ platí.", + leftOutFormat: "„%1$@“ sa odoslal bez %2$@: táto karta to teraz neprijíma.", + raiseNeedsOverclock: "Zvýšený takt alebo limit výkonu potrebuje zapnuté Povoliť pretaktovanie.", + otherCard: "Profil vznikol na inej karte: jeho hodnoty sa skontrolovali s touto.", + nothingToSave: "Držte limit výkonu alebo ventilátor, takt či napätie, aby sa dal uložiť profil.", + listSeparator: ", ", + listLastSeparator: " a ", + fieldPower: "limit výkonu", + fieldFanCurve: "krivka ventilátora", + fieldZeroRpm: "nulové otáčky vypnuté", + fieldGfxMax: "maximum GFX", + fieldGfxMin: "minimum GFX", + fieldVolt: "napätie", + fieldRaise: "príznak pretaktovania", + blockedWriting: "Zmeny GPU sú zatvorené: otvorte ich a potom načítajte profil.", + blockedDriver: "Ovládač ešte neodpovedal: skúste o chvíľu.", + blockedOther: "Iný program drží zmenu: pred načítaním profilu ju zatvorte.", + blockedOD8: "Po reštarte sa tabuľka ventilátora a taktov neprečítala: na načítanie profilu reštartujte Mac.", + blockedFan: "Táto verzia kextu nebola overená s krivkami: aktualizujte kext alebo uložte profil bez ventilátora.", + blockedOutOfRange: "Nič z tohto profilu teraz nie je v limitoch tejto karty.") + + static let de = GPUControlProfileStrings( + section: "Profile", + empty: "Noch keine Profile.", + footer: "Ein Profil hält ein Leistungslimit oder eine Lüfterkurve mit null U/min, die GFX-Takte und die Spannung. Beim Laden geht es denselben Weg wie die Regler oben, also wird jede Grenze erneut geprüft; mit Merken an behält die Karte es wie jede andere Änderung.", + saveCurrent: "Aktuelle Einstellungen sichern…", + saveTitle: "Die GPU-Einstellungen als Profil sichern", + renameTitle: "Profil umbenennen", + nameLabel: "Name", + saveAction: "Sichern", + cancel: "Abbrechen", + duplicateName: "Ein Profil namens „%@“ gibt es schon.", + load: "Laden", + rename: "Umbenennen", + delete: "Löschen", + deleteTitle: "Dieses Profil löschen?", + deleteMessage: "„%@“ wird von diesem Mac entfernt. Was die GPU gerade hält, bleibt.", + matches: "Das hält die GPU gerade", + loadedFormat: "„%@“ ist aktiv.", + leftOutFormat: "„%1$@“ ging ohne %2$@ raus: diese Karte nimmt das gerade nicht.", + raiseNeedsOverclock: "Ein erhöhter Takt oder ein höheres Leistungslimit braucht eingeschaltetes Übertakten erlauben.", + otherCard: "Dieses Profil entstand auf einer anderen Karte: seine Werte wurden an dieser geprüft.", + nothingToSave: "Halte ein Leistungslimit oder Lüfter, Takt bzw. Spannung, um ein Profil zu sichern.", + listSeparator: ", ", + listLastSeparator: " und ", + fieldPower: "das Leistungslimit", + fieldFanCurve: "die Lüfterkurve", + fieldZeroRpm: "Null-U/min aus", + fieldGfxMax: "der GFX-Höchsttakt", + fieldGfxMin: "der GFX-Mindesttakt", + fieldVolt: "die Spannung", + fieldRaise: "die Übertaktungsmarke", + blockedWriting: "GPU-Änderungen sind geschlossen: erst öffnen, dann das Profil laden.", + blockedDriver: "Der Treiber hat noch nicht geantwortet: gleich noch einmal versuchen.", + blockedOther: "Ein anderes Programm hält eine Änderung: vor dem Laden schließen.", + blockedOD8: "Lüfter- und Takt-Tabelle war nach dem Neustart nicht lesbar: zum Laden den Mac neu starten.", + blockedFan: "Diese kext-Version wurde nicht mit Kurven geprüft: Kext aktualisieren oder das Profil ohne Lüfter sichern.", + blockedOutOfRange: "Nichts aus diesem Profil liegt gerade in den Grenzen dieser Karte.") + + static let fr = GPUControlProfileStrings( + section: "Profils", + empty: "Aucun profil pour l’instant.", + footer: "Un profil garde une limite de puissance, ou une courbe de ventilateur avec zéro tr/min, les fréquences GFX et la tension. Au chargement, il part comme les réglages ci-dessus, donc chaque limite est revérifiée ; avec Mémoriser activé, la carte le garde comme tout autre changement.", + saveCurrent: "Enregistrer les réglages actuels…", + saveTitle: "Enregistrer les réglages du GPU comme profil", + renameTitle: "Renommer le profil", + nameLabel: "Nom", + saveAction: "Enregistrer", + cancel: "Annuler", + duplicateName: "Un profil nommé « %@ » existe déjà.", + load: "Charger", + rename: "Renommer", + delete: "Supprimer", + deleteTitle: "Supprimer ce profil ?", + deleteMessage: "« %@ » est retiré de ce Mac. Ce que le GPU tient maintenant ne change pas.", + matches: "C’est ce que le GPU tient maintenant", + loadedFormat: "« %@ » est en vigueur.", + leftOutFormat: "« %1$@ » est parti sans %2$@ : cette carte ne l’accepte pas maintenant.", + raiseNeedsOverclock: "Une fréquence ou une limite de puissance relevée demande Autoriser l’overclocking.", + otherCard: "Ce profil a été créé sur une autre carte : ses valeurs ont été vérifiées sur celle-ci.", + nothingToSave: "Tenez une limite de puissance, ou un ventilateur, une fréquence ou une tension, pour l’enregistrer en profil.", + listSeparator: ", ", + listLastSeparator: " et ", + fieldPower: "la limite de puissance", + fieldFanCurve: "la courbe du ventilateur", + fieldZeroRpm: "zéro tr/min désactivé", + fieldGfxMax: "la fréquence GFX maximale", + fieldGfxMin: "la fréquence GFX minimale", + fieldVolt: "la tension", + fieldRaise: "l’indicateur d’overclocking", + blockedWriting: "Les modifications du GPU sont fermées : ouvrez-les, puis chargez le profil.", + blockedDriver: "Le pilote n’a pas encore répondu : réessayez dans un instant.", + blockedOther: "Un autre programme tient un changement : fermez-le avant de charger un profil.", + blockedOD8: "La table ventilateur et fréquences n’a pas pu être lue après le redémarrage : redémarrez le Mac pour charger ce profil.", + blockedFan: "Cette version du kext n’a pas été vérifiée avec des courbes : mettez le kext à jour ou enregistrez le profil sans le ventilateur.", + blockedOutOfRange: "Rien dans ce profil n’est dans les limites de cette carte maintenant.") + + static let it = GPUControlProfileStrings( + section: "Profili", + empty: "Ancora nessun profilo.", + footer: "Un profilo tiene un limite di potenza, oppure una curva della ventola con zero giri, i clock GFX e la tensione. Al caricamento viene inviato come i controlli qui sopra, quindi ogni limite è ricontrollato; con Ricorda attivo la scheda lo mantiene come ogni altra modifica.", + saveCurrent: "Salva le impostazioni attuali…", + saveTitle: "Salva le impostazioni GPU come profilo", + renameTitle: "Rinomina il profilo", + nameLabel: "Nome", + saveAction: "Salva", + cancel: "Annulla", + duplicateName: "Esiste già un profilo chiamato «%@».", + load: "Carica", + rename: "Rinomina", + delete: "Elimina", + deleteTitle: "Eliminare questo profilo?", + deleteMessage: "«%@» viene rimosso da questo Mac. Ciò che la GPU tiene ora non cambia.", + matches: "Questo è ciò che la GPU tiene ora", + loadedFormat: "«%@» è in vigore.", + leftOutFormat: "«%1$@» è stato inviato senza %2$@: questa scheda ora non lo accetta.", + raiseNeedsOverclock: "Un clock o un limite di potenza alzato richiede Consenti l’overclock attivo.", + otherCard: "Questo profilo è stato creato su un’altra scheda: i suoi valori sono stati controllati su questa.", + nothingToSave: "Tieni un limite di potenza, oppure ventola, clock o tensione, per salvarlo come profilo.", + listSeparator: ", ", + listLastSeparator: " e ", + fieldPower: "il limite di potenza", + fieldFanCurve: "la curva della ventola", + fieldZeroRpm: "zero giri disattivato", + fieldGfxMax: "il massimo GFX", + fieldGfxMin: "il minimo GFX", + fieldVolt: "la tensione", + fieldRaise: "il flag di overclock", + blockedWriting: "Le modifiche GPU sono chiuse: aprile, poi carica il profilo.", + blockedDriver: "Il driver non ha ancora risposto: riprova tra un momento.", + blockedOther: "Un altro programma tiene una modifica: chiudila prima di caricare un profilo.", + blockedOD8: "Dopo il riavvio la tabella di ventola e clock non è leggibile: riavvia il Mac per caricare questo profilo.", + blockedFan: "Questa versione del kext non è stata provata con le curve: aggiorna il kext o salva il profilo senza la ventola.", + blockedOutOfRange: "Niente in questo profilo rientra ora nei limiti di questa scheda.") + + static let ja = GPUControlProfileStrings( + section: "プロファイル", + empty: "プロファイルはまだありません。", + footer: "プロファイルは、電力制限、またはゼロ回転を含むファンカーブ、GFX クロック、電圧を保存します。読み込むと上のコントロールと同じ経路で送られるため、すべての上限が再確認されます。「覚える」がオンなら、他の変更と同じようにカードが保持します。", + saveCurrent: "現在の設定を保存…", + saveTitle: "GPU の設定をプロファイルとして保存", + renameTitle: "プロファイルの名前を変更", + nameLabel: "名前", + saveAction: "保存", + cancel: "キャンセル", + duplicateName: "「%@」という名前のプロファイルはすでにあります。", + load: "読み込む", + rename: "名前を変更", + delete: "削除", + deleteTitle: "このプロファイルを削除しますか?", + deleteMessage: "「%@」をこの Mac から削除します。GPU が現在保持している内容は変わりません。", + matches: "GPU が現在保持している内容", + loadedFormat: "「%@」が適用されています。", + leftOutFormat: "「%1$@」は %2$@ なしで送信されました。このカードは現在それを受け付けません。", + raiseNeedsOverclock: "クロックや電力制限を上げるには「オーバークロックを許可」が必要です。", + otherCard: "このプロファイルは別のカードで作成されました。値はこのカードで確認されました。", + nothingToSave: "プロファイルとして保存するには、電力制限、またはファン・クロック・電圧を保持してください。", + listSeparator: "、", + listLastSeparator: "と", + fieldPower: "電力制限", + fieldFanCurve: "ファンカーブ", + fieldZeroRpm: "ゼロ回転オフ", + fieldGfxMax: "GFX 最大クロック", + fieldGfxMin: "GFX 最小クロック", + fieldVolt: "電圧", + fieldRaise: "オーバークロックの指定", + blockedWriting: "GPU の変更が閉じています。開いてからプロファイルを読み込んでください。", + blockedDriver: "ドライバがまだ応答していません。少し待ってから試してください。", + blockedOther: "別のプログラムが変更を保持しています。閉じてから読み込んでください。", + blockedOD8: "再起動後にファンとクロックの表を読めませんでした。このプロファイルを読み込むには Mac を再起動してください。", + blockedFan: "この kext ではカーブを確認していません。kext を更新するか、ファンを含めずに保存してください。", + blockedOutOfRange: "このプロファイルのどの値も、現在このカードの上限内にありません。") + + static let ko = GPUControlProfileStrings( + section: "프로필", + empty: "아직 프로필이 없습니다.", + footer: "프로필은 전력 제한, 또는 제로 RPM을 포함한 팬 곡선, GFX 클록, 전압을 저장합니다. 불러오면 위의 컨트롤과 같은 경로로 전송되므로 모든 한도를 다시 확인합니다. 기억이 켜져 있으면 다른 변경과 마찬가지로 카드가 유지합니다.", + saveCurrent: "현재 설정 저장…", + saveTitle: "GPU 설정을 프로필로 저장", + renameTitle: "프로필 이름 변경", + nameLabel: "이름", + saveAction: "저장", + cancel: "취소", + duplicateName: "‘%@’ 이름의 프로필이 이미 있습니다.", + load: "불러오기", + rename: "이름 변경", + delete: "삭제", + deleteTitle: "이 프로필을 삭제할까요?", + deleteMessage: "‘%@’을(를) 이 Mac에서 제거합니다. GPU가 지금 유지하는 값은 바뀌지 않습니다.", + matches: "GPU가 지금 유지하는 값", + loadedFormat: "‘%@’이(가) 적용되었습니다.", + leftOutFormat: "‘%1$@’은(는) %2$@ 없이 전송되었습니다. 이 카드는 지금 그것을 받지 않습니다.", + raiseNeedsOverclock: "클록이나 전력 제한을 올리려면 오버클럭 허용이 켜져 있어야 합니다.", + otherCard: "이 프로필은 다른 카드에서 만들어졌습니다. 값은 이 카드로 확인했습니다.", + nothingToSave: "프로필로 저장하려면 전력 제한, 또는 팬·클록·전압을 유지하세요.", + listSeparator: ", ", + listLastSeparator: " 및 ", + fieldPower: "전력 제한", + fieldFanCurve: "팬 곡선", + fieldZeroRpm: "제로 RPM 끔", + fieldGfxMax: "GFX 최대 클록", + fieldGfxMin: "GFX 최소 클록", + fieldVolt: "전압", + fieldRaise: "오버클럭 표시", + blockedWriting: "GPU 변경이 닫혀 있습니다. 먼저 열고 프로필을 불러오세요.", + blockedDriver: "드라이버가 아직 응답하지 않았습니다. 잠시 후 다시 시도하세요.", + blockedOther: "다른 프로그램이 변경을 유지하고 있습니다. 닫은 뒤 불러오세요.", + blockedOD8: "재시동 후 팬과 클록 표를 읽지 못했습니다. 이 프로필을 불러오려면 Mac을 재시동하세요.", + blockedFan: "이 kext에서는 곡선을 확인하지 않았습니다. kext를 업데이트하거나 팬 없이 저장하세요.", + blockedOutOfRange: "이 프로필의 어떤 값도 지금 이 카드의 한도 안에 없습니다.") + + static let zhHans = GPUControlProfileStrings( + section: "配置文件", + empty: "还没有配置文件。", + footer: "配置文件保存功率限制,或包含零转速的风扇曲线、GFX 时钟和电压。载入时按上方控件相同的路径发送,因此每个上限都会重新检查;开启“记住”后,显卡会像其他更改一样保持它。", + saveCurrent: "存储当前设置…", + saveTitle: "将 GPU 设置存为配置文件", + renameTitle: "重命名配置文件", + nameLabel: "名称", + saveAction: "存储", + cancel: "取消", + duplicateName: "已存在名为“%@”的配置文件。", + load: "载入", + rename: "重命名", + delete: "删除", + deleteTitle: "删除此配置文件?", + deleteMessage: "“%@”将从此 Mac 移除。GPU 当前保持的内容不会改变。", + matches: "这是 GPU 当前保持的内容", + loadedFormat: "“%@”已生效。", + leftOutFormat: "“%1$@”在发送时去掉了 %2$@:这张显卡现在不接受它。", + raiseNeedsOverclock: "提高时钟或功率限制需要开启“允许超频”。", + otherCard: "此配置文件是在另一张显卡上创建的:其中的数值已按这张显卡重新检查。", + nothingToSave: "请先保持一项功率限制,或风扇、时钟、电压,才能存为配置文件。", + listSeparator: "、", + listLastSeparator: "和", + fieldPower: "功率限制", + fieldFanCurve: "风扇曲线", + fieldZeroRpm: "关闭零转速", + fieldGfxMax: "GFX 最大时钟", + fieldGfxMin: "GFX 最小时钟", + fieldVolt: "电压", + fieldRaise: "超频标志", + blockedWriting: "GPU 更改已关闭:请先打开,再载入配置文件。", + blockedDriver: "驱动尚未响应:请稍后再试。", + blockedOther: "另一个程序正保持更改:请先关闭,再载入配置文件。", + blockedOD8: "重新启动后无法读取风扇和时钟表:要载入此配置文件,请重新启动 Mac。", + blockedFan: "此 kext 未用曲线验证过:请更新 kext,或去掉风扇部分再存储。", + blockedOutOfRange: "此配置文件中的任何值现在都不在这张显卡的范围内。") + + static let zhTW = GPUControlProfileStrings( + section: "設定檔", + empty: "還沒有設定檔。", + footer: "設定檔會保存功率限制,或包含零轉速的風扇曲線、GFX 時脈與電壓。載入時以上方控制項相同的路徑送出,因此每個上限都會重新檢查;開啟「記住」後,顯示卡會像其他變更一樣保持它。", + saveCurrent: "儲存目前設定…", + saveTitle: "將 GPU 設定存為設定檔", + renameTitle: "重新命名設定檔", + nameLabel: "名稱", + saveAction: "儲存", + cancel: "取消", + duplicateName: "已有名為「%@」的設定檔。", + load: "載入", + rename: "重新命名", + delete: "刪除", + deleteTitle: "刪除此設定檔?", + deleteMessage: "「%@」將從此 Mac 移除。GPU 目前保持的內容不會改變。", + matches: "這是 GPU 目前保持的內容", + loadedFormat: "「%@」已生效。", + leftOutFormat: "「%1$@」送出時去掉了 %2$@:這張顯示卡現在不接受它。", + raiseNeedsOverclock: "提高時脈或功率限制需要開啟「允許超頻」。", + otherCard: "此設定檔是在另一張顯示卡上建立的:其中的數值已依這張顯示卡重新檢查。", + nothingToSave: "請先保持一項功率限制,或風扇、時脈、電壓,才能存為設定檔。", + listSeparator: "、", + listLastSeparator: "和", + fieldPower: "功率限制", + fieldFanCurve: "風扇曲線", + fieldZeroRpm: "關閉零轉速", + fieldGfxMax: "GFX 最大時脈", + fieldGfxMin: "GFX 最小時脈", + fieldVolt: "電壓", + fieldRaise: "超頻旗標", + blockedWriting: "GPU 變更已關閉:請先開啟,再載入設定檔。", + blockedDriver: "驅動程式尚未回應:請稍後再試。", + blockedOther: "另一個程式正保持變更:請先關閉,再載入設定檔。", + blockedOD8: "重新啟動後無法讀取風扇與時脈表:要載入此設定檔,請重新啟動 Mac。", + blockedFan: "此 kext 未以曲線驗證過:請更新 kext,或去掉風扇部分再儲存。", + blockedOutOfRange: "此設定檔中的任何值現在都不在這張顯示卡的範圍內。") + + static let uk = GPUControlProfileStrings( + section: "Профілі", + empty: "Профілів ще немає.", + footer: "Профіль зберігає ліміт потужності або криву вентилятора з нульовими обертами, частоти GFX і напругу. Під час завантаження він надсилається так само, як елементи керування вище, тож кожну межу перевірено заново; якщо ввімкнено «Пам’ятати», карта тримає його як будь-яку іншу зміну.", + saveCurrent: "Зберегти поточні налаштування…", + saveTitle: "Зберегти налаштування GPU як профіль", + renameTitle: "Перейменувати профіль", + nameLabel: "Назва", + saveAction: "Зберегти", + cancel: "Скасувати", + duplicateName: "Профіль із назвою «%@» уже є.", + load: "Завантажити", + rename: "Перейменувати", + delete: "Видалити", + deleteTitle: "Видалити цей профіль?", + deleteMessage: "«%@» буде видалено з цього Mac. Те, що GPU тримає зараз, не зміниться.", + matches: "Це те, що GPU тримає зараз", + loadedFormat: "«%@» діє.", + leftOutFormat: "«%1$@» надіслано без %2$@: ця карта зараз цього не приймає.", + raiseNeedsOverclock: "Для підвищеної частоти чи ліміту потужності потрібно ввімкнути «Дозволити розгін».", + otherCard: "Профіль створено на іншій карті: його значення перевірено на цій.", + nothingToSave: "Утримуйте ліміт потужності або вентилятор, частоту чи напругу, щоб зберегти профіль.", + listSeparator: ", ", + listLastSeparator: " і ", + fieldPower: "ліміт потужності", + fieldFanCurve: "крива вентилятора", + fieldZeroRpm: "нульові оберти вимкнено", + fieldGfxMax: "максимум GFX", + fieldGfxMin: "мінімум GFX", + fieldVolt: "напруга", + fieldRaise: "прапорець розгону", + blockedWriting: "Зміни GPU закрито: відкрийте їх, потім завантажте профіль.", + blockedDriver: "Драйвер ще не відповів: спробуйте за мить.", + blockedOther: "Інша програма тримає зміну: закрийте її перед завантаженням профілю.", + blockedOD8: "Після перезавантаження не вдалося прочитати таблицю вентилятора й частот: перезавантажте Mac, щоб завантажити цей профіль.", + blockedFan: "Цю збірку kext не перевірено з кривими: оновіть kext або збережіть профіль без вентилятора.", + blockedOutOfRange: "Нічого з цього профілю зараз не в межах цієї карти.") +} diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlProfiles.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlProfiles.swift new file mode 100644 index 00000000..59bd78f8 --- /dev/null +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlProfiles.swift @@ -0,0 +1,539 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 RyzenStatus + +import Foundation +import IOKit + +/// The card a profile was made on: its PCI device id and the limits the kext +/// reported when it was saved. A profile from another card is never refused +/// for that alone: the numbers are here so the page can say that what was +/// left out was left out because this card is a different one. +struct GPUControlProfileCard: Codable, Equatable, Sendable { + var deviceID: UInt32? + /// The start-up power limit, in watts. + var bootW: Int? + var floorW: Int? + var ceilW: Int? + var stockGfxMaxMHz: Int? + var gfxMaxTopMHz: Int? + var gfxMinStockMHz: Int? + var voltStockMV: Int? + var voltMinMV: Int? + + static let unknown = GPUControlProfileCard() + + init(deviceID: UInt32? = nil, bootW: Int? = nil, floorW: Int? = nil, ceilW: Int? = nil, + stockGfxMaxMHz: Int? = nil, gfxMaxTopMHz: Int? = nil, gfxMinStockMHz: Int? = nil, + voltStockMV: Int? = nil, voltMinMV: Int? = nil) { + self.deviceID = deviceID + self.bootW = bootW + self.floorW = floorW + self.ceilW = ceilW + self.stockGfxMaxMHz = stockGfxMaxMHz + self.gfxMaxTopMHz = gfxMaxTopMHz + self.gfxMinStockMHz = gfxMinStockMHz + self.voltStockMV = voltStockMV + self.voltMinMV = voltMinMV + } + + /// The card as the kext and the registry describe it now. + static func current(facts: GPUControlFacts?, writing: GPUControlStatus.Writing?, + deviceID: UInt32?) -> Self { + let od8 = writing?.od8 + return Self(deviceID: deviceID, + bootW: facts?.bootW, + floorW: facts?.powerRange?.floorW, + ceilW: facts?.powerRange?.ceilW, + stockGfxMaxMHz: od8?.stockGfxMaxMHz, + gfxMaxTopMHz: od8?.gfxMaxTopMHz, + gfxMinStockMHz: od8?.gfxMin?.stock, + voltStockMV: od8?.gfxVolt?.stock, + voltMinMV: od8?.gfxVolt?.min) + } + + /// Two cards are the same when every value both of them know agrees: the + /// device id when both have it, and the limits the kext reports (the GFX + /// maximum moves a little across wakes, so a card saved before a wake is + /// still the same card; the start-up limit and the stock maximum are the + /// ones that do not move on their own). + func isSameCard(as other: Self) -> Bool { + if let mine = deviceID, let theirs = other.deviceID, mine != theirs { return false } + if let mine = bootW, let theirs = other.bootW, mine != theirs { return false } + if let mine = floorW, let theirs = other.floorW, mine != theirs { return false } + return true + } +} + +/// One of the saved GPU profiles: a name, what the page held when it was +/// saved, and the card it was saved on. Its values are the page's own types, +/// never a second set of fields: a power limit, or the whole OD8 state. +struct GPUControlProfile: Equatable, Identifiable, Sendable { + var name: String + var request: GPUControlRequest + var card: GPUControlProfileCard + + var id: String { name } + + /// Only a power limit and a fan/clock/voltage state are worth a name; + /// the way back to stock is not a profile. + var isSaveable: Bool { + switch request { + case .power(let watts): return watts > 0 + case .od8(let want): return !want.isStock + case .startUp: return false + } + } +} + +extension GPUControlProfile: Codable { + /// The stored shape: flat, every part optional, so a file from an older + /// or a newer build still reads (an entry this build cannot use is + /// dropped, never a reason to lose the others). + private struct Stored: Codable { + var name: String? + var kind: String? + var watts: Int? + /// `[C, %]` × 5, flat, as the remembered curve is kept. + var curve: [Int]? + var zeroRpmOff: Bool? + var gfxMaxMHz: Int? + var gfxMinMHz: Int? + var voltMV: Int? + var overclock: Bool? + var card: GPUControlProfileCard? + } + + private enum Keys: String, CodingKey { + case name, kind, watts, curve, zeroRpmOff, gfxMaxMHz, gfxMinMHz, voltMV, overclock, card + } + + init(from decoder: Decoder) throws { + let stored = try Stored(from: decoder) + let card = stored.card ?? .unknown + let name = (stored.name ?? "").trimmingCharacters(in: .whitespacesAndNewlines) + switch stored.kind { + case "power": + let watts = stored.watts ?? 0 + guard !name.isEmpty, watts > 0 else { throw GPUControlProfileDecodeError.unusable } + self.init(name: name, request: .power(watts: UInt32(clamping: watts)), card: card) + case "od8": + var want = GPUControlOD8Want(zeroRpmOff: stored.zeroRpmOff ?? false) + if let flat = stored.curve { + guard flat.count == 2 * GPUControlWire.fanCurvePoints else { + throw GPUControlProfileDecodeError.unusable + } + want.curve = stride(from: 0, to: flat.count, by: 2).map { + GPUControlFanPoint(temperatureC: flat[$0], speedPercent: flat[$0 + 1]) + } + } + if let mhz = stored.gfxMaxMHz, mhz > 0 { want.gfxMaxMHz = mhz } + if let mhz = stored.gfxMinMHz, mhz > 0 { want.gfxMinMHz = mhz } + if let mv = stored.voltMV, mv > 0 { want.voltMV = mv } + want.overclock = stored.overclock ?? false + guard !name.isEmpty, !want.isStock else { throw GPUControlProfileDecodeError.unusable } + self.init(name: name, request: .od8(want), card: card) + default: + // A kind this build does not know: the entry is left out. + throw GPUControlProfileDecodeError.unusable + } + } + + func encode(to encoder: Encoder) throws { + var stored = Stored() + stored.name = name + stored.card = card + switch request { + case .power(let watts): + stored.kind = "power" + stored.watts = Int(watts) + case .od8(let want): + stored.kind = "od8" + if let curve = want.curve { + stored.curve = curve.flatMap { [$0.temperatureC, $0.speedPercent] } + } + stored.zeroRpmOff = want.zeroRpmOff + stored.gfxMaxMHz = want.gfxMaxMHz + stored.gfxMinMHz = want.gfxMinMHz + stored.voltMV = want.voltMV + if want.overclock { stored.overclock = true } + case .startUp: + stored.kind = "power" + stored.watts = 0 + } + try stored.encode(to: encoder) + } +} + +enum GPUControlProfileDecodeError: Error { + /// An entry this build cannot use: dropped, the others are kept. + case unusable +} + +/// The saved profiles, in the app's defaults under one key, with a version +/// number. A file written by a newer build is left alone: this build shows +/// no profiles and saves none over it. +struct GPUControlProfileStore: Equatable, Sendable { + static let currentVersion = 1 + + private(set) var profiles: [GPUControlProfile] = [] + /// The stored file came from a newer build and was not read: nothing is + /// written over it. + private(set) var isNewerVersion = false + + init() {} + + init(profiles: [GPUControlProfile], isNewerVersion: Bool = false) { + self.profiles = profiles + self.isNewerVersion = isNewerVersion + } + + /// One entry of the written file. + private struct File: Encodable { + var version: Int + var profiles: [GPUControlProfile] + } + + /// One entry of a file being read: an entry this build cannot use is + /// dropped on its own, never together with the others. + private struct Entry: Decodable { + var profile: GPUControlProfile? + + init(from decoder: Decoder) throws { + profile = try? GPUControlProfile(from: decoder) + } + } + + private struct ReadFile: Decodable { + var version: Int + var profiles: [Entry] + } + + /// The raw text of a file this build could not read because of its + /// version, so a save does not throw it away. + private struct VersionProbe: Decodable { + var version: Int + } + + static func decode(_ data: Data) -> GPUControlProfileStore? { + let decoder = JSONDecoder() + if let probe = try? decoder.decode(VersionProbe.self, from: data), probe.version > currentVersion { + return GPUControlProfileStore(profiles: [], isNewerVersion: true) + } + guard let file = try? decoder.decode(ReadFile.self, from: data) else { return nil } + guard file.version >= 1 else { return nil } + return GPUControlProfileStore(profiles: file.profiles.compactMap(\.profile)) + } + + static func load(_ defaults: UserDefaults) -> GPUControlProfileStore { + guard let data = defaults.data(forKey: DefaultsKey.gpuControlProfiles) else { return GPUControlProfileStore() } + return decode(data) ?? GPUControlProfileStore() + } + + /// Written as one JSON blob, with the version this build writes. + func save(_ defaults: UserDefaults) { + guard !isNewerVersion else { return } + guard let data = encoded() else { return } + defaults.set(data, forKey: DefaultsKey.gpuControlProfiles) + } + + func encoded() -> Data? { + guard !isNewerVersion else { return nil } + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + return try? encoder.encode(File(version: Self.currentVersion, profiles: profiles)) + } + + // MARK: Names + + /// A name with its ends trimmed; nil when nothing is left. + static func clean(_ raw: String) -> String? { + let name = raw.trimmingCharacters(in: .whitespacesAndNewlines) + return name.isEmpty ? nil : name + } + + /// Names are unique without regard to case, so "Game" and "game" cannot + /// sit next to each other. + func isTaken(_ name: String, excluding: String? = nil) -> Bool { + let name = name.trimmingCharacters(in: .whitespacesAndNewlines) + return profiles.contains { profile in + if let excluding, profile.name.caseInsensitiveCompare(excluding) == .orderedSame { return false } + return profile.name.caseInsensitiveCompare(name) == .orderedSame + } + } + + /// The first entry with that name (exact, then without regard to case). + func profile(named name: String) -> GPUControlProfile? { + profiles.first { $0.name == name } ?? profiles.first { $0.name.caseInsensitiveCompare(name) == .orderedSame } + } + + // MARK: Changing them + + mutating func add(_ profile: GPUControlProfile) { + if let index = profiles.firstIndex(where: { $0.name.caseInsensitiveCompare(profile.name) == .orderedSame }) { + profiles[index] = profile + } else { + profiles.append(profile) + } + } + + @discardableResult + mutating func rename(_ name: String, to newName: String) -> Bool { + guard let index = profiles.firstIndex(where: { $0.name == name }) else { return false } + profiles[index].name = newName + return true + } + + @discardableResult + mutating func remove(named name: String) -> Bool { + let count = profiles.count + profiles.removeAll { $0.name == name } + return profiles.count != count + } +} + +/// One part of a profile's state, for the sentence about what was left out. +enum GPUControlProfileField: String, CaseIterable, Equatable, Sendable { + case power + case fanCurve + case zeroRpm + case gfxMax + case gfxMin + case volt + case raise +} + +/// Why a profile went out as nothing at all. +enum GPUControlProfileBlock: Equatable, Sendable { + /// Writing is closed, off, or was never opened since the restart. + case writingClosed + case waitingForDriver + case otherProgram + /// OD8 was not read cleanly after the restart. + case od8NotRead + /// A fan state, and this kext build was not checked with fan curves. + case fanNotChecked + /// Every value in it is outside this card's limits now. + case outOfRange + /// All it held was a raise, and "Allow overclocking" is off. + case raiseNeedsOverclock +} + +/// What loading one profile came to. +struct GPUControlProfileLoad: Equatable, Sendable { + var name: String + /// What goes out, nil when nothing does. + var request: GPUControlRequest? + /// The parts this card does not take now; the rest of the state still + /// goes, as with a value set by hand. + var leftOut: [GPUControlProfileField] = [] + /// The profile was made on another card (or the limits moved). + var cardChanged = false + /// A raise (a GFX maximum above stock, a power limit above the start-up + /// one) was left out because "Allow overclocking" is off. + var raiseNeedsOverclock = false + var blocked: GPUControlProfileBlock? + + var wentOut: Bool { request != nil } +} + +/// What saving one profile came to. +enum GPUControlProfileSave: Equatable, Sendable { + case saved(name: String) + case emptyName + case duplicateName(String) + case nothingToSave + /// The stored file comes from a newer build: nothing is written over it. + case newerVersion +} + +/// The profiles' rules, without threads or defaults: what a name may be, and +/// what of a profile this card takes now. +enum GPUControlProfiles { + /// A profile for what is held: the card is recorded with it. + static func profile(named name: String, held: GPUControlRequest, card: GPUControlProfileCard) -> GPUControlProfile? { + let profile = GPUControlProfile(name: name, request: held.normalized, card: card) + return profile.isSaveable ? profile : nil + } + + /// The request a profile becomes on this card now, through the same + /// checks the page applies to a value set by hand: the power limit from + /// the pop-up's values (or, above the start-up limit, the overclock + /// section's, only while "Allow overclocking" is on), and an OD8 state + /// through `checkedAgain`, which leaves out a clock, a minimum, a voltage + /// or a raise the card does not take now. A fan state needs a kext build + /// the curve rules were checked with, as "Apply curve" does. + static func load(_ profile: GPUControlProfile, card: GPUControlProfileCard, + facts: GPUControlFacts?, stockGfxMaxMHz: Int?, + od8Ready: Bool, kextVersion: String?, + gfxMin: GPUControlClockMinLogic.Limits?, + volt: GPUControlVoltLogic.Limits?, + overclock: GPUControlOverclockLogic.GfxLimits?, + overclockAllowed: Bool) -> GPUControlProfileLoad { + var load = GPUControlProfileLoad(name: profile.name, request: nil) + load.cardChanged = !profile.card.isSameCard(as: card) + guard let facts else { + load.blocked = .waitingForDriver + return load + } + if facts.isReadOnlyCard || facts.off || facts.writeOffCode != 0 || !facts.armed { + load.blocked = .writingClosed + return load + } + if facts.owned && !facts.mine { + load.blocked = .otherProgram + return load + } + if !facts.ready { + load.blocked = .waitingForDriver + return load + } + switch profile.request { + case .startUp: + load.blocked = .outOfRange + return load + case .power(let watts): + loadPower(&load, watts: Int(watts), facts: facts, overclockAllowed: overclockAllowed) + return load + case .od8(let want): + return loadOD8(load, want: want, facts: facts, od8Ready: od8Ready, kextVersion: kextVersion, + stockGfxMaxMHz: stockGfxMaxMHz, gfxMin: gfxMin, volt: volt, + overclock: overclock, overclockAllowed: overclockAllowed) + } + } + + private static func loadPower(_ load: inout GPUControlProfileLoad, watts: Int, + facts: GPUControlFacts, overclockAllowed: Bool) { + guard let boot = facts.bootW else { + load.blocked = .waitingForDriver + return + } + let choices = GPUControlPageLogic.powerChoices(bootW: boot, range: facts.powerRange) + // The start-up limit is the way back, as choosing it on the page is. + if watts == boot, choices.contains(watts) { + load.request = .startUp + return + } + if choices.contains(watts) { + load.request = .power(watts: UInt32(clamping: watts)) + return + } + // Above the start-up limit: the overclock section's own values, and + // only while "Allow overclocking" is on. + if watts > boot, let ceiling = GPUControlOverclockLogic.ceilingW(facts: facts), + GPUControlOverclockLogic.powerChoices(bootW: boot, ceilW: ceiling, + stepW: facts.powerRange?.stepW ?? GPUControlWire.powerStepW) + .contains(watts) { + if overclockAllowed { + load.request = .power(watts: UInt32(clamping: watts)) + } else { + load.blocked = .raiseNeedsOverclock + load.raiseNeedsOverclock = true + } + return + } + load.blocked = .outOfRange + } + + private static func loadOD8(_ load: GPUControlProfileLoad, want: GPUControlOD8Want, + facts: GPUControlFacts, od8Ready: Bool, kextVersion: String?, + stockGfxMaxMHz: Int?, gfxMin: GPUControlClockMinLogic.Limits?, + volt: GPUControlVoltLogic.Limits?, + overclock: GPUControlOverclockLogic.GfxLimits?, + overclockAllowed: Bool) -> GPUControlProfileLoad { + var load = load + // OD8 not read cleanly: the kext could not take it. + guard od8Ready else { + load.blocked = .od8NotRead + return load + } + // A fan state and another kext build: the rules were not checked with + // it, and "Apply curve" is off too. + if want.curve != nil || want.zeroRpmOff, !GPUControlCurveRules.isChecked(kextVersion) { + load.blocked = .fanNotChecked + return load + } + guard let checked = GPUControlRememberPolicy.checkedAgain( + .od8(want), stockGfxMaxMHz: stockGfxMaxMHz, gfxMin: gfxMin, volt: volt, + overclock: overclock, overclockAllowed: overclockAllowed), + case .od8(let kept) = checked else { + let fields = leftOut(want, keptIn: .stock) + // A raise alone, with the switch off: that is the reason, not + // the card's limits. + if !overclockAllowed, want.overclock, fields.allSatisfy({ $0 == .gfxMax || $0 == .raise }) { + load.blocked = .raiseNeedsOverclock + load.raiseNeedsOverclock = true + return load + } + load.leftOut = fields + load.blocked = .outOfRange + return load + } + load.leftOut = leftOut(want, keptIn: kept) + load.request = .od8(kept) + // A raise left out only because the switch is off says why. + if want.overclock || (want.gfxMaxMHz.map { $0 > (stockGfxMaxMHz ?? $0) } ?? false) { + if !overclockAllowed, kept.overclock == false, + kept.gfxMaxMHz != want.gfxMaxMHz { + load.raiseNeedsOverclock = true + } + } + return load + } + + /// Which parts of `want` the state `kept` no longer carries. + static func leftOut(_ want: GPUControlOD8Want, keptIn kept: GPUControlOD8Want) -> [GPUControlProfileField] { + var fields: [GPUControlProfileField] = [] + if want.curve != nil, kept.curve == nil { fields.append(.fanCurve) } + if want.zeroRpmOff, !kept.zeroRpmOff { fields.append(.zeroRpm) } + if want.gfxMaxMHz != nil, kept.gfxMaxMHz == nil { + fields.append(.gfxMax) + if want.overclock { fields.append(.raise) } + } + if want.gfxMinMHz != nil, kept.gfxMinMHz == nil { fields.append(.gfxMin) } + if want.voltMV != nil, kept.voltMV == nil { fields.append(.volt) } + return fields + } + + /// The saved profile that is exactly what the card holds now, if any: a + /// name, not a second copy of the values. + static func match(_ profiles: [GPUControlProfile], held: GPUControlRequest?) -> String? { + guard let held, held != .startUp else { return nil } + return profiles.first { $0.request == held }?.name + } +} + +/// The display card's PCI device id, read from the I/O Registry: the +/// accelerator's own node or the one above it (the PCI device). Read only; +/// nil when it cannot be read, and then a profile is only compared by the +/// limits the kext reports. +enum GPUControlCardDevice { + static func displayDeviceID() -> UInt32? { + var iterator: io_iterator_t = 0 + guard IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOAccelerator"), + &iterator) == kIOReturnSuccess else { return nil } + defer { IOObjectRelease(iterator) } + while case let entry = IOIteratorNext(iterator), entry != 0 { + defer { IOObjectRelease(entry) } + if let id = deviceID(from: entry, depth: 4) { return id } + } + return nil + } + + private static func deviceID(from entry: io_registry_entry_t, depth: Int) -> UInt32? { + if let value = IORegistryEntryCreateCFProperty(entry, "device-id" as CFString, + kCFAllocatorDefault, 0)?.takeRetainedValue() { + // The registry keeps it as four bytes, little endian (bf 73 00 00). + if let data = value as? Data, data.count >= 4 { + return UInt32(data[0]) | UInt32(data[1]) << 8 | UInt32(data[2]) << 16 | UInt32(data[3]) << 24 + } + if let number = value as? NSNumber { return number.uint32Value } + } + guard depth > 0 else { return nil } + var parent: io_registry_entry_t = 0 + guard IORegistryEntryGetParentEntry(entry, kIOServicePlane, &parent) == KERN_SUCCESS, parent != 0 else { + return nil + } + defer { IOObjectRelease(parent) } + return deviceID(from: parent, depth: depth - 1) + } +} diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift index 53e0e93f..2e0589ff 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift @@ -79,6 +79,16 @@ final class GPUControlService: ObservableObject { } } + /// The owner's GPU profiles, as saved in the app's defaults. + @Published private(set) var profiles: [GPUControlProfile] = [] + /// What the last profile loaded came to: the section under the list says + /// what went out and what this card did not take. + @Published private(set) var profileLoad: GPUControlProfileLoad? + /// The display card's PCI device id, read once: a profile records the + /// card it was made on with it. + private let cardDeviceID: UInt32? = GPUControlCardDevice.displayDeviceID() + private var profileStore = GPUControlProfileStore() + private let defaults: UserDefaults /// The switch for the controller's queue: a remembered raise is checked /// against it right before it goes out. @@ -102,6 +112,8 @@ final class GPUControlService: ObservableObject { let on = defaults.bool(forKey: DefaultsKey.gpuControlOverclock) overclock = on overclockNow.withLock { $0 = on } + profileStore = GPUControlProfileStore.load(defaults) + profiles = profileStore.profiles } var facts: GPUControlFacts? { GPUControlPageLogic.facts(snapshot: snapshot, control: control) } @@ -366,6 +378,81 @@ final class GPUControlService: ObservableObject { } } if next.stopped != nil { pendingRemembered = false } + // The sentence about the last profile loaded is about the state it + // put on the card: another change makes it old news. + if let load = profileLoad, next.outcome == nil, next.activity == .none, + next.held != load.request { + profileLoad = nil + } + } + + // MARK: Profiles + + /// The card as the kext and the registry describe it now. + private var cardNow: GPUControlProfileCard { + GPUControlProfileCard.current(facts: facts, writing: control?.writing, deviceID: cardDeviceID) + } + + /// The saved profile that is exactly what the card holds now, if any. + var matchingProfile: String? { + GPUControlProfiles.match(profiles, held: snapshot?.held) + } + + /// What the card holds now goes into a profile under `raw`. Only what + /// the kext confirmed is saved, as Remembering does; a name is trimmed, + /// may not be empty and may not repeat another profile's. + @discardableResult + func saveProfile(named raw: String) -> GPUControlProfileSave { + guard !profileStore.isNewerVersion else { return .newerVersion } + guard let held = snapshot?.held, held != .startUp else { return .nothingToSave } + guard let name = GPUControlProfileStore.clean(raw) else { return .emptyName } + guard !profileStore.isTaken(name) else { return .duplicateName(name) } + guard let profile = GPUControlProfiles.profile(named: name, held: held, card: cardNow) else { + return .nothingToSave + } + profileStore.add(profile) + profileStore.save(defaults) + profiles = profileStore.profiles + return .saved(name: name) + } + + @discardableResult + func renameProfile(named name: String, to raw: String) -> GPUControlProfileSave { + guard !profileStore.isNewerVersion else { return .newerVersion } + guard let clean = GPUControlProfileStore.clean(raw) else { return .emptyName } + guard profileStore.profile(named: name) != nil else { return .nothingToSave } + guard !profileStore.isTaken(clean, excluding: name) else { return .duplicateName(clean) } + profileStore.rename(name, to: clean) + profileStore.save(defaults) + profiles = profileStore.profiles + return .saved(name: clean) + } + + func deleteProfile(named name: String) { + guard !profileStore.isNewerVersion else { return } + profileStore.remove(named: name) + profileStore.save(defaults) + profiles = profileStore.profiles + } + + /// A profile goes out through the controller's own path, exactly as a + /// value the owner changes by hand does: the same checks, the same + /// waiting, the same refusal on screen. What this card does not take now + /// is left out, and the section says which part. With Remember on, a + /// profile the kext confirms becomes the remembered state like any other + /// change (`received`). + func loadProfile(_ profile: GPUControlProfile) { + let writing = control?.writing + let od8Ready = facts?.od8Ready ?? false + let load = GPUControlProfiles.load( + profile, card: cardNow, facts: facts, stockGfxMaxMHz: writing?.od8?.stockGfxMaxMHz, + od8Ready: od8Ready, kextVersion: writing?.kextVersion, + gfxMin: GPUControlClockMinLogic.limits(writing: writing, od8Ready: od8Ready), + volt: GPUControlVoltLogic.limits(writing: writing, od8Ready: od8Ready), + overclock: GPUControlOverclockLogic.gfxLimits(writing: writing, od8Ready: od8Ready), + overclockAllowed: overclock) + profileLoad = load + if let request = load.request { controller?.choose(request) } } // MARK: Another program (security review S-5, S-9) diff --git a/Sources/RyzenStatus/UI/Settings/GPUControlProfilesSection.swift b/Sources/RyzenStatus/UI/Settings/GPUControlProfilesSection.swift new file mode 100644 index 00000000..757b83fc --- /dev/null +++ b/Sources/RyzenStatus/UI/Settings/GPUControlProfilesSection.swift @@ -0,0 +1,243 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 RyzenStatus + +import AppKit +import SwiftUI + +/// What the profiles section asks of the app: saving what the card holds now +/// under a name, and loading, renaming or deleting one of them. Saving and +/// renaming answer with what came of the name, so the sheet can say why it +/// stayed open. +struct GPUControlProfileActions { + var save: (String) -> GPUControlProfileSave = { _ in .nothingToSave } + var load: (GPUControlProfile) -> Void = { _ in } + var rename: (String, String) -> GPUControlProfileSave = { _, _ in .nothingToSave } + var delete: (String) -> Void = { _ in } +} + +/// Settings > GPU control > Profiles: the owner's GPU setups, one row each, +/// in the plain style of Settings > AMD Ryzen Power > Custom profiles (a +/// name, its buttons, and what it holds under it). Saving asks for a name in +/// a sheet; deleting asks first. +struct GPUControlProfilesSection: View { + let input: GPUControlPageInput + let strings: GPUControlProfileStrings + let page: GPUControlPageStrings + let actions: GPUControlProfileActions + + @State private var sheet: NameSheet? + @State private var pendingDelete: GPUControlProfile? + @State private var sheetProblem: String? + + /// The name sheet: a new profile (`original` nil) or a rename. + private struct NameSheet: Identifiable { + var id: String + var original: String? + var name: String + var title: String + } + + var body: some View { + Section { + ForEach(input.profiles) { profile in + row(profile) + } + if input.profiles.isEmpty { + Text(strings.empty) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + HStack(spacing: 10) { + Button(strings.saveCurrent) { + sheetProblem = nil + sheet = NameSheet(id: "new", original: nil, name: "", title: strings.saveTitle) + } + .disabled(held == nil) + Spacer() + } + .buttonStyle(.bordered) + if let message { + GPUControlProblemLabel(text: message.text, isProblem: message.isProblem) + } + } header: { + Text(strings.section) + } footer: { + Text(strings.footer) + .font(.caption) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + .sheet(item: $sheet) { draft in + sheetView(draft) + } + .alert(strings.deleteTitle, isPresented: Binding( + get: { pendingDelete != nil }, + set: { if !$0 { pendingDelete = nil } } + ), presenting: pendingDelete) { profile in + Button(strings.delete, role: .destructive) { + actions.delete(profile.name) + pendingDelete = nil + } + Button(strings.cancel, role: .cancel) { pendingDelete = nil } + } message: { profile in + Text(String(format: strings.deleteMessage, profile.name)) + } + } + + // MARK: Rows + + private func row(_ profile: GPUControlProfile) -> some View { + let matches = input.matchingProfile.map { $0 == profile.name } ?? false + return VStack(alignment: .leading, spacing: 4) { + HStack { + Text(profile.name) + .fontWeight(matches ? .semibold : .regular) + if matches { + // Never colour alone: the row's weight and the help say it. + Image(systemName: "checkmark.circle.fill") + .foregroundColor(.green) + .help(strings.matches) + .accessibilityLabel(strings.matches) + } + Spacer() + Button(strings.load) { actions.load(profile) } + .disabled(!canLoad) + Button(strings.rename) { + sheetProblem = nil + sheet = NameSheet(id: profile.name, original: profile.name, name: profile.name, + title: strings.renameTitle) + } + Button(role: .destructive) { + pendingDelete = profile + } label: { + Image(systemName: "trash") + } + .help(strings.delete) + } + .buttonStyle(.borderless) + Text(summary(profile.request)) + .font(.caption2) + .foregroundStyle(.secondary) + } + } + + /// What a profile holds, in the page's own words. + private func summary(_ request: GPUControlRequest) -> String { + switch request { + case .power(let watts): return String(format: page.wattsFormat, Int(watts)) + case .od8(let want): return page.od8Held(want) + case .startUp: return "" + } + } + + /// What the card holds now, when that is something a profile could keep. + private var held: GPUControlRequest? { + guard case .heldByApp(let request)? = input.state, request != .startUp else { return nil } + return request + } + + /// Loading goes through the page's own path, so it waits where the + /// controls wait: writing open, nothing else on its way. + private var canLoad: Bool { + input.canChoose && (input.state?.acceptsChoices ?? false) && !input.isPending + } + + // MARK: The last load + + /// One line about the last profile loaded, or why Save is dimmed. + private var message: (text: String, isProblem: Bool)? { + if let load = input.profileLoad { + if let blocked = load.blocked { + return (blockedText(blocked), true) + } + var lines: [String] = [] + if load.leftOut.isEmpty { + lines.append(String(format: strings.loadedFormat, load.name)) + } else { + lines.append(String(format: strings.leftOutFormat, load.name, fieldList(load.leftOut))) + } + if load.raiseNeedsOverclock { lines.append(strings.raiseNeedsOverclock) } + if load.cardChanged { lines.append(strings.otherCard) } + return (lines.joined(separator: " "), !load.leftOut.isEmpty || load.raiseNeedsOverclock) + } + return held == nil ? (strings.nothingToSave, false) : nil + } + + private func blockedText(_ block: GPUControlProfileBlock) -> String { + switch block { + case .writingClosed: return strings.blockedWriting + case .waitingForDriver: return strings.blockedDriver + case .otherProgram: return strings.blockedOther + case .od8NotRead: return strings.blockedOD8 + case .fanNotChecked: return strings.blockedFan + case .outOfRange: return strings.blockedOutOfRange + case .raiseNeedsOverclock: return strings.raiseNeedsOverclock + } + } + + private func fieldList(_ fields: [GPUControlProfileField]) -> String { + let names = fields.map(fieldName) + guard let last = names.last else { return "" } + guard names.count > 1 else { return last } + return names.dropLast().joined(separator: strings.listSeparator) + strings.listLastSeparator + last + } + + private func fieldName(_ field: GPUControlProfileField) -> String { + switch field { + case .power: return strings.fieldPower + case .fanCurve: return strings.fieldFanCurve + case .zeroRpm: return strings.fieldZeroRpm + case .gfxMax: return strings.fieldGfxMax + case .gfxMin: return strings.fieldGfxMin + case .volt: return strings.fieldVolt + case .raise: return strings.fieldRaise + } + } + + // MARK: The name sheet + + private func sheetView(_ draft: NameSheet) -> some View { + VStack(alignment: .leading, spacing: 12) { + Text(draft.title) + .font(.headline) + TextField(strings.nameLabel, text: Binding( + get: { sheet?.name ?? "" }, + set: { sheet?.name = $0; sheetProblem = nil } + )) + .textFieldStyle(.roundedBorder) + .frame(width: 340) + if let sheetProblem { + Text(sheetProblem) + .font(.caption) + .foregroundStyle(.orange) + .fixedSize(horizontal: false, vertical: true) + } + HStack { + Spacer() + Button(strings.cancel) { sheet = nil } + .keyboardShortcut(.cancelAction) + Button(strings.saveAction) { commit(draft) } + .keyboardShortcut(.defaultAction) + .disabled((draft.name).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + } + } + .padding() + .frame(width: 400) + } + + private func commit(_ draft: NameSheet) { + let outcome = draft.original.map { actions.rename($0, draft.name) } ?? actions.save(draft.name) + switch outcome { + case .saved: + sheet = nil + sheetProblem = nil + case .duplicateName(let name): + sheetProblem = String(format: strings.duplicateName, name) + case .emptyName, .nothingToSave, .newerVersion: + // Nothing to say that the field or the section does not: the + // sheet stays open for a name that can be used. + sheet = nil + } + } +} diff --git a/Sources/RyzenStatus/UI/Settings/GPUControlSettingsView.swift b/Sources/RyzenStatus/UI/Settings/GPUControlSettingsView.swift index 684c4ee5..4f0112ad 100644 --- a/Sources/RyzenStatus/UI/Settings/GPUControlSettingsView.swift +++ b/Sources/RyzenStatus/UI/Settings/GPUControlSettingsView.swift @@ -21,6 +21,7 @@ struct GPUControlSettingsView: View { clock: FeatureStrings.gpuControlClock(l10n.language), boot: FeatureStrings.gpuControlBoot(l10n.language), overclock: FeatureStrings.gpuControlOverclock(l10n.language), + profile: FeatureStrings.gpuControlProfile(l10n.language), title: FeatureStrings.gpuControl(l10n.language).title, actions: GPUControlPageActions( choosePower: { service.choosePower($0) }, @@ -37,7 +38,12 @@ struct GPUControlSettingsView: View { chooseVolt: { service.chooseVolt($0) }, chooseGfxMaxRaised: { service.chooseGfxMaxRaised($0) }, setOverclock: { service.overclock = $0 }, - closeChanges: { service.closeChanges() })) + closeChanges: { service.closeChanges() }), + profileActions: GPUControlProfileActions( + save: { service.saveProfile(named: $0) }, + load: { service.loadProfile($0) }, + rename: { service.renameProfile(named: $0, to: $1) }, + delete: { service.deleteProfile(named: $0) })) // Reads once a second only while the page is on screen. .settingsPageActivity(.gpuControl, activate: { service.viewerAppeared() }, @@ -72,6 +78,12 @@ struct GPUControlPageInput: Equatable { var fanDraft: GPUControlFanDraft? /// "Allow overclocking" (GPUSensors 0.9.0), off by default. var overclock = false + /// The owner's saved GPU profiles, and the name of the one that is + /// exactly what the card holds now (nil when none is). + var profiles: [GPUControlProfile] = [] + var matchingProfile: String? + /// The last profile loaded: what went out and what was left out. + var profileLoad: GPUControlProfileLoad? init(facts: GPUControlFacts?, state: GPUControlPageState?, snapshot: GPUControlSnapshot?) { self.facts = facts @@ -95,6 +107,9 @@ struct GPUControlPageInput: Equatable { canChoose = service.mode != .none writing = service.control?.writing overclock = service.overclock + profiles = service.profiles + matchingProfile = service.matchingProfile + profileLoad = service.profileLoad } } @@ -213,8 +228,10 @@ struct GPUControlPageContent: View { let clock: GPUControlClockStrings let boot: GPUControlBootStrings let overclock: GPUControlOverclockStrings + let profile: GPUControlProfileStrings let title: String let actions: GPUControlPageActions + let profileActions: GPUControlProfileActions @State private var copied = false /// The editor's draft; its `edited` flag says whether the owner touched /// it since it was last seeded or applied. @@ -223,16 +240,19 @@ struct GPUControlPageContent: View { init(input: GPUControlPageInput, strings: GPUControlPageStrings, fan: GPUControlFanStrings, clock: GPUControlClockStrings, boot: GPUControlBootStrings = .enUS, - overclock: GPUControlOverclockStrings = .enUS, title: String, - actions: GPUControlPageActions) { + overclock: GPUControlOverclockStrings = .enUS, profile: GPUControlProfileStrings = .enUS, + title: String, actions: GPUControlPageActions, + profileActions: GPUControlProfileActions = GPUControlProfileActions()) { self.input = input self.strings = strings self.fan = fan self.clock = clock self.boot = boot self.overclock = overclock + self.profile = profile self.title = title self.actions = actions + self.profileActions = profileActions var held: GPUControlOD8Want? if case .heldByApp(.od8(let want))? = input.state { held = want } _draft = State(initialValue: input.fanDraft ?? GPUControlFanDraft(held: held)) @@ -278,6 +298,11 @@ struct GPUControlPageContent: View { if case .closed? = input.state { armSection } if Self.showsBootArm(input) { bootArmSection } rememberSection + // Its own section, like "remember": the list is worth seeing even + // on a card the control only reads. + if showsPower || !input.profiles.isEmpty { + GPUControlProfilesSection(input: input, strings: profile, page: s, actions: profileActions) + } detailsSection } .formStyle(.grouped) diff --git a/Tests/MetricsTests.swift b/Tests/MetricsTests.swift index f9d99ab8..8bc3ee00 100644 --- a/Tests/MetricsTests.swift +++ b/Tests/MetricsTests.swift @@ -14478,6 +14478,7 @@ struct MetricsTests { ("GPUControlFanTests", GPUControlFanTests.run), ("GPUControlClockTests", GPUControlClockTests.run), ("GPUControlOverclockTests", GPUControlOverclockTests.run), + ("GPUControlProfileTests", GPUControlProfileTests.run), ("GPUControlA11yTests", GPUControlA11yTests.run), ("GPUFolderTests", GPUFolderTests.run), ("GPUInstallerDMGTests", GPUInstallerDMGTests.run), diff --git a/Tests/Suites/GPUControlProfileTests.swift b/Tests/Suites/GPUControlProfileTests.swift new file mode 100644 index 00000000..a955d9c9 --- /dev/null +++ b/Tests/Suites/GPUControlProfileTests.swift @@ -0,0 +1,319 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 RyzenStatus + +import Foundation + +/// Settings > GPU control > Profiles: the stored shape with its version, +/// the names, the request a profile becomes on a card, the profile that +/// matches what is held, and the words. +enum GPUControlProfileTests { + static func run(_ suite: TestSuite) { + encoding(suite) + names(suite) + store(suite) + loading(suite) + matching(suite) + strings(suite) + } + + private typealias Want = GPUControlOD8Want + private typealias Policy = GPUControlRememberPolicy + + private static let card = GPUControlProfileCard(deviceID: 0x73BF, bootW: 240, floorW: 225, ceilW: 261, + stockGfxMaxMHz: 2_359, gfxMaxTopMHz: 2_800, + gfxMinStockMHz: 500, voltStockMV: 1_075, voltMinMV: 881) + + private static let curve = [ + GPUControlFanPoint(temperatureC: 30, speedPercent: 25), + GPUControlFanPoint(temperatureC: 50, speedPercent: 35), + GPUControlFanPoint(temperatureC: 65, speedPercent: 50), + GPUControlFanPoint(temperatureC: 80, speedPercent: 75), + GPUControlFanPoint(temperatureC: 90, speedPercent: 100), + ] + + /// The test card's limits as the kext reports them. + private static func facts(armed: Bool = true, ready: Bool = true, od8Ready: Bool = true, + owned: Bool = false, mine: Bool = false) -> GPUControlFacts { + var f = GPUControlFacts(source: .properties) + f.ready = ready + f.armed = armed + f.od8Ready = od8Ready + f.takesRaise = true + f.owned = owned + f.mine = mine + f.bootW = 240 + f.powerRange = GPUControlPowerRange(source: .kext, floorW: 225, maxW: 240, ceilW: 261, stepW: 10, + percentMin: -6, percentMax: 9) + return f + } + + private static func load(_ profile: GPUControlProfile, facts: GPUControlFacts? = facts(), + card: GPUControlProfileCard = card, stockGfxMaxMHz: Int? = 2_359, + od8Ready: Bool = true, kextVersion: String? = "REL-090-2026-11-25", + gfxMin: GPUControlClockMinLogic.Limits? = nil, + volt: GPUControlVoltLogic.Limits? = GPUControlVoltLogic.Limits(min: 881, stock: 1_075), + overclock: GPUControlOverclockLogic.GfxLimits? = GPUControlOverclockLogic.GfxLimits(stock: 2_359, max: 2_800), + overclockAllowed: Bool = false) -> GPUControlProfileLoad { + GPUControlProfiles.load(profile, card: card, facts: facts, stockGfxMaxMHz: stockGfxMaxMHz, + od8Ready: od8Ready, kextVersion: kextVersion, gfxMin: gfxMin, volt: volt, + overclock: overclock, overclockAllowed: overclockAllowed) + } + + private static func profile(_ name: String, _ request: GPUControlRequest) -> GPUControlProfile { + GPUControlProfile(name: name, request: request, card: card) + } + + // MARK: The stored shape + + private static func encoding(_ suite: TestSuite) { + let power = profile("Quiet", .power(watts: 220)) + let od8 = profile("Game", .od8(Want(curve: curve, zeroRpmOff: true, gfxMaxMHz: 2_500, + gfxMinMHz: 1_600, voltMV: 1_050, overclock: true))) + for original in [power, od8] { + let data = GPUControlProfileStore(profiles: [original]).encoded() + let back = data.flatMap(GPUControlProfileStore.decode) + suite.expect(back?.profiles == [original], "\(original.name): written and read back unchanged") + suite.expect(back?.isNewerVersion == false, "\(original.name): the version is this build's") + } + let json = """ + {"version":1,"profiles":[{"name":" Quiet ","kind":"power","watts":220,"card":{"deviceID":29631,"bootW":240},"future":1}]} + """ + let read = GPUControlProfileStore.decode(Data(json.utf8)) + suite.expect(read?.profiles.map(\.name) == ["Quiet"], "a stored name is trimmed, an unknown key is ignored") + suite.expect(read?.profiles.first?.request == .power(watts: 220), "the power limit reads back") + suite.expect(read?.profiles.first?.card.deviceID == 0x73BF, "the card's device id is kept") + + // A file from a newer build: no profiles, and no save over it. + let future = Data(""" + {"version":9,"profiles":[{"name":"Future","kind":"power","watts":200}]} + """.utf8) + let newer = GPUControlProfileStore.decode(future) + suite.expect(newer?.profiles.isEmpty == true && newer?.isNewerVersion == true, + "a file from a newer build is ignored, not a crash") + suite.expect(newer?.encoded() == nil, "and nothing is written over it") + let defaults = UserDefaults(suiteName: "gpucontrol.profile.newer")! + defaults.removePersistentDomain(forName: "gpucontrol.profile.newer") + defaults.set(future, forKey: DefaultsKey.gpuControlProfiles) + var kept = GPUControlProfileStore.load(defaults) + kept.add(power) + kept.save(defaults) + suite.expect(defaults.data(forKey: DefaultsKey.gpuControlProfiles) == future, + "saving with a newer file in place leaves that file alone") + + suite.expect(GPUControlProfileStore.decode(Data("not json".utf8)) == nil, "garbage is no store") + suite.expect(GPUControlProfileStore.decode(Data("{}".utf8)) == nil, "no version, no store") + suite.expect(GPUControlProfileStore.decode(Data(#"{"version":0,"profiles":[]}"#.utf8)) == nil, + "version 0 is no store") + + // One entry this build cannot use does not take the others with it. + let mixed = Data(""" + {"version":1,"profiles":[ + {"name":"Newer","kind":"curve-thing"}, + {"name":"Game","kind":"od8","curve":[30,25,50,35,65,50,80,75],"zeroRpmOff":true}, + {"name":"Stock","kind":"od8"}, + {"name":"Quiet","kind":"power","watts":220} + ]} + """.utf8) + let read2 = GPUControlProfileStore.decode(mixed) + suite.expect(read2?.profiles.map(\.name) == ["Quiet"], + "an unknown kind, a short curve and a stock state are dropped; the rest stays") + let empty = Data(#"{"version":1,"profiles":[{"name":" ","kind":"power","watts":220}]}"#.utf8) + suite.expect(GPUControlProfileStore.decode(empty)?.profiles.isEmpty == true, "a blank name is no profile") + let noWatts = Data(#"{"version":1,"profiles":[{"name":"A","kind":"power"}]}"#.utf8) + suite.expect(GPUControlProfileStore.decode(noWatts)?.profiles.isEmpty == true, "a power limit of 0 is no profile") + + // Only what is worth a name. + suite.expect(GPUControlProfiles.profile(named: "Stock", held: .startUp, card: card) == nil, + "the way back to stock is not a profile") + suite.expect(GPUControlProfiles.profile(named: "Stock", held: .od8(.stock), card: card) == nil, + "nor a stock OD8 state") + suite.expect(GPUControlProfiles.profile(named: "Quiet", held: .power(watts: 220), card: card)?.request + == .power(watts: 220), + "a power limit is one") + } + + // MARK: Names + + private static func names(_ suite: TestSuite) { + suite.expect(GPUControlProfileStore.clean(" Quiet ") == "Quiet", "a name is trimmed") + suite.expect(GPUControlProfileStore.clean(" ") == nil && GPUControlProfileStore.clean("") == nil, + "a blank name is not saved") + var store = GPUControlProfileStore(profiles: [profile("Game", .power(watts: 220))]) + suite.expect(store.isTaken("Game") && store.isTaken("game") && store.isTaken(" GAME "), + "names are unique without regard to case, after trimming") + suite.expect(!store.isTaken("Quiet"), "another name is free") + suite.expect(!store.isTaken("game", excluding: "Game"), "renaming to its own name is not a clash") + suite.expect(store.isTaken("Game", excluding: "Other"), "but it clashes with a different entry") + suite.expect(store.profile(named: "game")?.name == "Game", "a name finds its profile in any case") + + store.add(profile("game", .power(watts: 200))) + suite.expect(store.profiles.count == 1 && store.profiles.first?.request == .power(watts: 200), + "adding a name that exists replaces it, never a second row") + suite.expect(store.rename("game", to: "Quiet") && store.profiles.first?.name == "Quiet", + "renaming finds the profile in any case") + suite.expect(store.remove(named: "Quiet") && store.profiles.isEmpty, "deleting takes it out") + suite.expect(!store.remove(named: "Quiet"), "deleting a name that is not there changes nothing") + } + + private static func store(_ suite: TestSuite) { + let defaults = UserDefaults(suiteName: "gpucontrol.profile.store")! + defaults.removePersistentDomain(forName: "gpucontrol.profile.store") + suite.expect(GPUControlProfileStore.load(defaults).profiles.isEmpty, "no key, no profiles") + var store = GPUControlProfileStore() + store.add(profile("Quiet", .power(watts: 220))) + store.add(profile("Game", .od8(Want(gfxMaxMHz: 2_500, voltMV: 1_050, overclock: true)))) + store.save(defaults) + let read = GPUControlProfileStore.load(defaults) + suite.expect(read.profiles == store.profiles, "both profiles come back from the defaults") + suite.expect(defaults.data(forKey: DefaultsKey.gpuControlProfiles) != nil, + "they live under the GPU control's own key") + } + + // MARK: The request a profile becomes + + private static func loading(_ suite: TestSuite) { + // The power limit. + let lower = load(profile("Quiet", .power(watts: 230))) + suite.expect(lower.request == .power(watts: 230) && lower.leftOut.isEmpty && lower.blocked == nil, + "230 W is inside the card's range: it goes out as it is") + suite.expect(lower.cardChanged == false, "and it was made on this card") + suite.expect(load(profile("Boot", .power(watts: 240))).request == .startUp, + "the start-up limit is the way back, as choosing it is") + let tooLow = load(profile("Low", .power(watts: 200))) + suite.expect(tooLow.request == nil && tooLow.blocked == .outOfRange, + "below the card's floor: nothing goes, and the page says why") + let raisedOff = load(profile("Raise", .power(watts: 261)), overclockAllowed: false) + suite.expect(raisedOff.request == nil && raisedOff.blocked == .raiseNeedsOverclock + && raisedOff.raiseNeedsOverclock, + "a raised power limit with Allow overclocking off: left out, and the page says why") + let raisedOn = load(profile("Raise", .power(watts: 261)), overclockAllowed: true) + suite.expect(raisedOn.request == .power(watts: 261), "the same with the switch on: it goes out") + suite.expect(load(profile("Odd", .power(watts: 250)), overclockAllowed: true).request == .power(watts: 250), + "every value the raised pop-up offers is taken") + suite.expect(load(profile("Past", .power(watts: 270)), overclockAllowed: true).blocked == .outOfRange, + "above the card's ceiling: not taken") + suite.expect(load(profile("Quiet", .power(watts: 220)), facts: nil).blocked == .waitingForDriver, + "no facts yet: nothing is sent") + + // The OD8 state. + let lowered = load(profile("Clock", .od8(Want(gfxMaxMHz: 2_000)))) + suite.expect(lowered.request == .od8(Want(gfxMaxMHz: 2_000)) && lowered.leftOut.isEmpty, + "a lowered GFX maximum goes out, nothing left out") + suite.expect(load(profile("Below", .od8(Want(gfxMaxMHz: 1_400)))).leftOut == [.gfxMax] + && load(profile("Below", .od8(Want(gfxMaxMHz: 1_400)))).request == nil, + "below the kext's floor: left out, and nothing is left to send") + let raiseOn = load(profile("Game", .od8(Want(gfxMaxMHz: 2_500, overclock: true))), overclockAllowed: true) + suite.expect(raiseOn.request == .od8(Want(gfxMaxMHz: 2_500, overclock: true)) && raiseOn.leftOut.isEmpty, + "a raised maximum with Allow overclocking on: it goes out with its flag") + let raiseOff = load(profile("Game", .od8(Want(gfxMaxMHz: 2_500, overclock: true))), overclockAllowed: false) + suite.expect(raiseOff.request == nil && raiseOff.blocked == .raiseNeedsOverclock + && raiseOff.raiseNeedsOverclock, + "a raise alone with the switch off: the page says what to turn on") + let mixed = Want(curve: curve, zeroRpmOff: true, gfxMaxMHz: 2_500, voltMV: 1_050, overclock: true) + let mixedOff = load(profile("Mixed", .od8(mixed)), overclockAllowed: false) + suite.expect(mixedOff.request == .od8(Want(curve: curve, zeroRpmOff: true, voltMV: 1_050)), + "with the switch off the raise goes and the rest of the state stays") + suite.expect(mixedOff.leftOut == [.gfxMax, .raise] && mixedOff.raiseNeedsOverclock, + "and the page names what it left out") + + let voltOnly = load(profile("Volt", .od8(Want(voltMV: 950))), + volt: GPUControlVoltLogic.Limits(min: 1_000, stock: 1_075)) + suite.expect(voltOnly.request == nil && voltOnly.leftOut == [.volt] && voltOnly.blocked == .outOfRange, + "a voltage this card's table does not offer: left out") + let minOnly = load(profile("Min", .od8(Want(gfxMinMHz: 1_900))), gfxMin: nil) + suite.expect(minOnly.leftOut == [.gfxMin], "a GFX minimum the kext does not take: left out") + + // The fan state needs a build the curve rules were checked with. + let fanOnOld = load(profile("Fan", .od8(Want(curve: curve))), kextVersion: "REL-073-2026-12-01") + suite.expect(fanOnOld.request == nil && fanOnOld.blocked == .fanNotChecked, + "a fan curve and an unchecked kext build: nothing goes, as Apply curve would not") + suite.expect(load(profile("Fan", .od8(Want(curve: curve)))).request == .od8(Want(curve: curve)), + "the checked build takes the same curve") + + // Where writing stands. + suite.expect(load(profile("Quiet", .power(watts: 220)), facts: facts(armed: false)).blocked == .writingClosed, + "writing closed: the page says to open it") + suite.expect(load(profile("Quiet", .power(watts: 220)), facts: facts(owned: true)).blocked == .otherProgram, + "another program holds a change: close it first") + var off = facts() + off.off = true + suite.expect(load(profile("Quiet", .power(watts: 220)), facts: off).blocked == .writingClosed, + "writing off until restart: no profile goes out") + suite.expect(load(profile("Quiet", .power(watts: 220)), facts: facts(ready: false)).blocked == .waitingForDriver, + "the kext is not ready yet: wait") + suite.expect(load(profile("Game", .od8(Want(gfxMaxMHz: 2_000))), od8Ready: false).blocked == .od8NotRead, + "OD8 not read since the restart: no fan or clock state") + + // Another card: it is still listed, and what it holds is checked again. + let otherCard = GPUControlProfileCard(deviceID: 0x73E0, bootW: 240) + let moved = load(profile("Quiet", .power(watts: 230)), card: otherCard) + suite.expect(moved.cardChanged && moved.request == .power(watts: 230), + "a profile from another card still loads, and the page says the card changed") + let movedRaise = load(profile("Game", .od8(Want(gfxMaxMHz: 2_500, overclock: true))), + card: otherCard, overclockAllowed: false) + suite.expect(movedRaise.cardChanged && movedRaise.blocked == .raiseNeedsOverclock, + "and its checks are this card's") + suite.expect(load(profile("Quiet", .power(watts: 220)), + card: GPUControlProfileCard(deviceID: 0x73BF, bootW: 250)).cardChanged, + "a card that starts at another limit is a different card too") + suite.expect(!load(profile("Quiet", .power(watts: 220)), + card: GPUControlProfileCard(deviceID: 0x73BF, bootW: 240, stockGfxMaxMHz: 2_400)).cardChanged, + "a stock maximum that moved a little is the same card") + + // Which parts are named as left out. + suite.expect(GPUControlProfiles.leftOut(mixed, keptIn: Want(curve: curve, zeroRpmOff: true, voltMV: 1_050)) + == [.gfxMax, .raise], + "the sentence names the clock and the raise, not what stayed") + suite.expect(GPUControlProfiles.leftOut(Want(gfxMinMHz: 1_600, voltMV: 1_050), + keptIn: Want(voltMV: 1_050)) == [.gfxMin], + "one part at a time") + suite.expect(GPUControlProfiles.leftOut(.stock, keptIn: .stock).isEmpty, "a stock state leaves nothing out") + } + + private static func matching(_ suite: TestSuite) { + let profiles = [profile("Quiet", .power(watts: 220)), profile("Game", .od8(Want(gfxMaxMHz: 2_000)))] + suite.expect(GPUControlProfiles.match(profiles, held: .power(watts: 220)) == "Quiet", + "the profile that is exactly what the card holds") + suite.expect(GPUControlProfiles.match(profiles, held: .od8(Want(gfxMaxMHz: 2_000))) == "Game", + "the OD8 one too") + suite.expect(GPUControlProfiles.match(profiles, held: .power(watts: 230)) == nil, + "another limit matches nothing") + suite.expect(GPUControlProfiles.match(profiles, held: nil) == nil, "nothing held, no match") + suite.expect(GPUControlProfiles.match(profiles, held: .startUp) == nil, "the way back is not a profile") + suite.expect(GPUControlProfiles.match([], held: .power(watts: 220)) == nil, "no profiles, no match") + } + + // MARK: The words + + private static func strings(_ suite: TestSuite) { + let en = GPUControlProfileStrings.enUS + for language in AppLanguage.allCases { + let s = FeatureStrings.gpuControlProfile(language) + suite.expect(s.all.allSatisfy { !$0.isEmpty }, "\(language.rawValue): every profile text is filled") + suite.expect(Set(s.all).count >= s.all.count - 1, "\(language.rawValue): the texts are not the same word") + suite.expect(s.leftOutFormat.components(separatedBy: "%1$@").count == 2 + && s.leftOutFormat.components(separatedBy: "%2$@").count == 2 + && !s.leftOutFormat.contains("%@"), + "\(language.rawValue): the left-out text takes the name and the list") + let sentence = String(format: s.leftOutFormat, "Quiet", s.fieldFanCurve + s.listLastSeparator + s.fieldVolt) + suite.expect(!sentence.contains("%") && sentence.contains("Quiet"), + "\(language.rawValue): it formats cleanly") + suite.expect(s.loadedFormat.components(separatedBy: "%@").count == 2, "\(language.rawValue): the loaded text takes the name") + suite.expect(s.duplicateName.components(separatedBy: "%@").count == 2, "\(language.rawValue): the clash text takes the name") + suite.expect(s.deleteMessage.components(separatedBy: "%@").count == 2, "\(language.rawValue): the delete text takes the name") + suite.expect(!s.section.isEmpty && !s.load.isEmpty && !s.delete.isEmpty && !s.blockedWriting.isEmpty, + "\(language.rawValue): the section, its buttons and its reasons are filled") + if language != .enUS { + suite.expect(s.footer != en.footer && s.otherCard != en.otherCard, + "\(language.rawValue): the footer and the card sentence are translated") + } + } + suite.expect(FeatureStrings.gpuControlProfile(.zhHK).section == FeatureStrings.gpuControlProfile(.zhTW).section, + "Hong Kong uses the traditional Chinese texts") + suite.expect(GPUControlProfileField.allCases.map { en.field($0) } == [en.fieldPower, en.fieldFanCurve, + en.fieldZeroRpm, en.fieldGfxMax, + en.fieldGfxMin, en.fieldVolt, + en.fieldRaise], + "every part of a profile has its words, in the order they are listed") + } +} diff --git a/docs/GPU_CONTROL.md b/docs/GPU_CONTROL.md index 9bf06a5c..6e76f96e 100644 --- a/docs/GPU_CONTROL.md +++ b/docs/GPU_CONTROL.md @@ -106,6 +106,23 @@ some cards 2500, for about 5 % more performance and about 15 % more power (KitGu Lab, Guru3D). Igor's Lab advises not to go past about 330 W for the chip. Raise one thing at a time, 25 MHz at a time, and test each step. +## Profiles + +Profiles, at the bottom of the page, keeps the setups you use under names: a quiet desktop, a +gaming one. A profile holds what the page can hold — a power limit, or the whole fan, clock and +voltage state (fan curve, zero RPM, GFX maximum and minimum, voltage) — saved from what the kext +confirmed, exactly what Remember would keep. Names are unique and trimmed; deleting asks first. + +Load sends it the way the controls above do: the same limits, the same watchdog, the same refusal +on the page, and with Remember on the loaded setup comes back at launch and after a wake like any +other change. A profile also records the card it was made on (its PCI device id and the stock +limits the kext reported). On another card, or after those limits moved, it is still listed and +still loads, but every value is checked against the card in front of you: one it does not take is +left out and the section says which — a raised GFX maximum, and a power limit above the start-up +one, go out only while Allow overclocking is on. + +Profiles live in the app's preferences on this Mac; nothing is written to the card. + ## Not offered: memory clock and fast memory timings The cards offer a higher memory clock (2000 to 2150 MHz on the RX 6800 XT) and a "fast From 1c4dc6cbe3637d3460890b16ff2a818829a8416f Mon Sep 17 00:00:00 2001 From: DrogaBox Date: Wed, 25 Nov 2026 23:07:11 -0300 Subject: [PATCH 2/3] GPU control: profile and restore fixes from review - The fresh-readings read before a write now goes to the AMD accelerator only, so an Intel iGPU or another card that enumerates first can't swallow it and leave the kext refusing for want of fresh readings. - A remembered retry that a sleep cut short starts its 30 s window again after the wake instead of running out during the settle delay. - Picking by hand the exact value a remembered retry is asking for makes it the owner's: their refusal shows and the remembered filter no longer rewrites it. - A remembered power limit above the start-up one is dropped while "Allow overclocking" is off, like a raised GFX maximum already was. - The card id a profile records is read from the AMD card only. - The line about the last profile loaded stays until what the card holds changes, instead of going away with the next status reading. - The name sheet saves the name as typed, not the one it opened with. --- .../Metrics/GPUControlController.swift | 35 +++++++++++++++---- .../Services/Metrics/GPUControlPage.swift | 11 ++++-- .../Services/Metrics/GPUControlProfiles.swift | 23 ++++++++---- .../Services/Metrics/GPUControlService.swift | 10 +++--- .../Settings/GPUControlProfilesSection.swift | 8 ++--- Tests/Suites/GPUControlProfileTests.swift | 11 ++++++ 6 files changed, 75 insertions(+), 23 deletions(-) diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlController.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlController.swift index ab6862b2..349ef6e3 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlController.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlController.swift @@ -251,7 +251,14 @@ final class GPUControlEngine { let request = request.normalized let now = clock() if request == wanted { - // Asked for already: it goes out as planned. + // Asked for already: it goes out as planned. When the owner picks + // the very value a remembered retry is asking for, it is the + // owner's from now on (their refusal shows, no remembered filter). + if origin == .owner, wantedOrigin != .owner { + wantedOrigin = .owner + temporarySince = nil + snapshot.ownerReleased = false + } snapshot.outcome = nil return } @@ -410,6 +417,9 @@ final class GPUControlEngine { } } if wanted != nil { + // A retry the sleep cut short gets its whole window again after + // the wake, counted from the next refusal. + temporarySince = nil nextTryAt = Swift.max(nextTryAt, now + Self.wakeSettleMs) if let wanted { snapshot.activity = .afterWake(wanted) } } @@ -1083,19 +1093,32 @@ final class GPUControlController: @unchecked Sendable { /// change makes them fresh, whether or not the app's own GPU readings run /// yet (right after launch, right after a wake). enum GPUControlReadings { - /// Reads `PerformanceStatistics` of the first accelerator that has it. - /// The values are not used here; `IOAcceleratorCache` keeps its own. + /// The AMD accelerator classes, most specific first, so an Intel iGPU or + /// another card that enumerates first is never the one read. + private static let amdClasses = [ + "AMDRadeonX6000_AMDAcceleratedVKDriver", + "AMDRadeonX6000_AmdRadeonGraphicsAccelerator", + "AMDGPUAccelerator" + ] + + /// Reads `PerformanceStatistics` of the AMD accelerator. The values are + /// not used here; `IOAcceleratorCache` keeps its own. static func freshen() { + for cls in amdClasses where read(matching: cls) { return } + } + + private static func read(matching cls: String) -> Bool { var iterator: io_iterator_t = 0 - guard IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching("IOAccelerator"), - &iterator) == kIOReturnSuccess else { return } + guard IOServiceGetMatchingServices(kIOMainPortDefault, IOServiceMatching(cls), + &iterator) == kIOReturnSuccess else { return false } defer { IOObjectRelease(iterator) } while case let entry = IOIteratorNext(iterator), entry != 0 { defer { IOObjectRelease(entry) } if IORegistryEntryCreateCFProperty(entry, "PerformanceStatistics" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue() != nil { - return + return true } } + return false } } diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlPage.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlPage.swift index 0f22ef4a..6187c64a 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlPage.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlPage.swift @@ -706,12 +706,19 @@ extension GPUControlRememberPolicy { /// (`volt`) and a raised GFX maximum (`overclock`, the card's range for /// it): kept only while the kext takes them and inside the card's range, /// and the raise only while "Allow overclocking" is on - /// (`overclockAllowed`). Nil when nothing is left to ask. + /// (`overclockAllowed`). A power limit above the start-up one (`bootW`) + /// is a raise too: it is dropped while the switch is off. Nil when + /// nothing is left to ask. static func checkedAgain(_ request: GPUControlRequest, stockGfxMaxMHz: Int?, gfxMin: GPUControlClockMinLogic.Limits? = nil, volt: GPUControlVoltLogic.Limits? = nil, overclock: GPUControlOverclockLogic.GfxLimits? = nil, - overclockAllowed: Bool = true) -> GPUControlRequest? { + overclockAllowed: Bool = true, + bootW: Int? = nil) -> GPUControlRequest? { + if case .power(let watts) = request, !overclockAllowed, let boot = bootW, boot > 0, + Int(watts) > boot { + return nil + } guard case .od8(var want) = request else { return request } if !overclockAllowed { want = withoutRaise(want) } if let mhz = want.gfxMaxMHz { diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlProfiles.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlProfiles.swift index 59bd78f8..0c59e010 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlProfiles.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlProfiles.swift @@ -519,14 +519,23 @@ enum GPUControlCardDevice { return nil } + /// AMD's PCI vendor id: an Intel iGPU or another card is never the one read. + private static let amdVendor: UInt32 = 0x1002 + + private static func number(_ key: String, of entry: io_registry_entry_t) -> UInt32? { + guard let value = IORegistryEntryCreateCFProperty(entry, key as CFString, + kCFAllocatorDefault, 0)?.takeRetainedValue() else { return nil } + // The registry keeps it as four bytes, little endian (bf 73 00 00). + if let data = value as? Data, data.count >= 4 { + return UInt32(data[0]) | UInt32(data[1]) << 8 | UInt32(data[2]) << 16 | UInt32(data[3]) << 24 + } + return (value as? NSNumber)?.uint32Value + } + private static func deviceID(from entry: io_registry_entry_t, depth: Int) -> UInt32? { - if let value = IORegistryEntryCreateCFProperty(entry, "device-id" as CFString, - kCFAllocatorDefault, 0)?.takeRetainedValue() { - // The registry keeps it as four bytes, little endian (bf 73 00 00). - if let data = value as? Data, data.count >= 4 { - return UInt32(data[0]) | UInt32(data[1]) << 8 | UInt32(data[2]) << 16 | UInt32(data[3]) << 24 - } - if let number = value as? NSNumber { return number.uint32Value } + if let id = number("device-id", of: entry) { + // The node with the PCI ids: only an AMD card counts. + return number("vendor-id", of: entry) == amdVendor ? id : nil } guard depth > 0 else { return nil } var parent: io_registry_entry_t = 0 diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift index 2e0589ff..914a1e65 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlService.swift @@ -163,7 +163,8 @@ final class GPUControlService: ObservableObject { gfxMin: GPUControlClockMinLogic.limits(writing: control?.writing, od8Ready: od8Ready), volt: GPUControlVoltLogic.limits(writing: control?.writing, od8Ready: od8Ready), overclock: GPUControlOverclockLogic.gfxLimits(writing: control?.writing, od8Ready: od8Ready), - overclockAllowed: overclockNow.withLock { $0 }) + overclockAllowed: overclockNow.withLock { $0 }, + bootW: control?.powerWatch?.bootW) } // The kext refuses a curve or a raise while the watchdog's readings // are older than 2 s: one read right before each such change. @@ -379,9 +380,10 @@ final class GPUControlService: ObservableObject { } if next.stopped != nil { pendingRemembered = false } // The sentence about the last profile loaded is about the state it - // put on the card: another change makes it old news. - if let load = profileLoad, next.outcome == nil, next.activity == .none, - next.held != load.request { + // put on the card: another change of what is held makes it old news + // (the readings in the status move every second and do not count). + if let load = profileLoad, next.held != previous?.held, next.outcome == nil, + next.activity == .none, next.held != load.request { profileLoad = nil } } diff --git a/Sources/RyzenStatus/UI/Settings/GPUControlProfilesSection.swift b/Sources/RyzenStatus/UI/Settings/GPUControlProfilesSection.swift index 757b83fc..7d18b951 100644 --- a/Sources/RyzenStatus/UI/Settings/GPUControlProfilesSection.swift +++ b/Sources/RyzenStatus/UI/Settings/GPUControlProfilesSection.swift @@ -217,9 +217,9 @@ struct GPUControlProfilesSection: View { Spacer() Button(strings.cancel) { sheet = nil } .keyboardShortcut(.cancelAction) - Button(strings.saveAction) { commit(draft) } + Button(strings.saveAction) { commit(sheet ?? draft) } .keyboardShortcut(.defaultAction) - .disabled((draft.name).trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) + .disabled((sheet ?? draft).name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) } } .padding() @@ -235,8 +235,8 @@ struct GPUControlProfilesSection: View { case .duplicateName(let name): sheetProblem = String(format: strings.duplicateName, name) case .emptyName, .nothingToSave, .newerVersion: - // Nothing to say that the field or the section does not: the - // sheet stays open for a name that can be used. + // Nothing the sheet can fix: it closes, and the section's line + // says why Save is dimmed. sheet = nil } } diff --git a/Tests/Suites/GPUControlProfileTests.swift b/Tests/Suites/GPUControlProfileTests.swift index a955d9c9..7e41ea06 100644 --- a/Tests/Suites/GPUControlProfileTests.swift +++ b/Tests/Suites/GPUControlProfileTests.swift @@ -281,6 +281,17 @@ enum GPUControlProfileTests { suite.expect(GPUControlProfiles.match(profiles, held: nil) == nil, "nothing held, no match") suite.expect(GPUControlProfiles.match(profiles, held: .startUp) == nil, "the way back is not a profile") suite.expect(GPUControlProfiles.match([], held: .power(watts: 220)) == nil, "no profiles, no match") + + // A remembered power raise is checked against the switch too, not + // only an OD8 raise. + suite.expect(Policy.checkedAgain(.power(watts: 261), stockGfxMaxMHz: 2_359, overclockAllowed: false, + bootW: 240) == nil, "a raised power limit is dropped with the switch off") + suite.expect(Policy.checkedAgain(.power(watts: 261), stockGfxMaxMHz: 2_359, overclockAllowed: true, + bootW: 240) == .power(watts: 261), "and kept with it on") + suite.expect(Policy.checkedAgain(.power(watts: 225), stockGfxMaxMHz: 2_359, overclockAllowed: false, + bootW: 240) == .power(watts: 225), "a lowered limit needs no switch") + suite.expect(Policy.checkedAgain(.power(watts: 261), stockGfxMaxMHz: 2_359, overclockAllowed: false, + bootW: nil) == .power(watts: 261), "no start-up limit known: left as it is") } // MARK: The words From 3ad25ad3880987cb74ad4003689c7a6daa85fa89 Mon Sep 17 00:00:00 2001 From: DrogaBox Date: Wed, 25 Nov 2026 23:29:28 -0300 Subject: [PATCH 3/3] GPU control: profiles load the clocks without an unchecked fan part MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On a kext build the curve rules were not checked with, a profile with a fan state used to load nothing at all. Now the fan part is left out (and named under the list) while the clocks and the voltage still go; only a profile that is nothing but a fan state is refused. A profile's line under its name lists the values ("A fan curve, a GFX maximum of 2300 MHz…") instead of reusing the status sentence that starts with "RyzenStatus is holding". --- .../Core/GPUControlPageStrings.swift | 19 +++++++++++++++---- .../Services/Metrics/GPUControlProfiles.swift | 15 +++++++++++---- .../Settings/GPUControlProfilesSection.swift | 2 +- Tests/Suites/GPUControlProfileTests.swift | 8 ++++++++ 4 files changed, 35 insertions(+), 9 deletions(-) diff --git a/Sources/RyzenStatus/Core/GPUControlPageStrings.swift b/Sources/RyzenStatus/Core/GPUControlPageStrings.swift index 5d81ef1a..3cc9f63c 100644 --- a/Sources/RyzenStatus/Core/GPUControlPageStrings.swift +++ b/Sources/RyzenStatus/Core/GPUControlPageStrings.swift @@ -168,6 +168,18 @@ struct GPUControlPageStrings { /// What an OD8 hold is, in words: "a fan curve and a GFX maximum of 2300 MHz". func od8Held(_ want: GPUControlOD8Want) -> String { + guard let text = od8List(want) else { return heldOD8Short } + return String(format: heldOD8Format, text) + } + + /// What an OD8 state holds, as a list that starts with a capital: a + /// saved profile's line, where "RyzenStatus is holding" would be wrong. + func od8Items(_ want: GPUControlOD8Want) -> String { + guard let text = od8List(want) else { return heldOD8Short } + return text.prefix(1).uppercased() + text.dropFirst() + } + + private func od8List(_ want: GPUControlOD8Want) -> String? { var items: [String] = [] if want.curve != nil { items.append(fanCurveItem) } if want.zeroRpmOff { items.append(zeroRpmItem) } @@ -175,13 +187,12 @@ struct GPUControlPageStrings { if let mhz = want.gfxMinMHz { items.append(String(format: gfxMinItemFormat, mhz)) } if let mv = want.voltMV { items.append(String(format: voltItemFormat, mv)) } // An empty hold would leave "RyzenStatus is holding " with nothing - // after it: say the short form instead. - guard !items.isEmpty else { return heldOD8Short } + // after it: the callers say the short form instead. + guard !items.isEmpty else { return nil } // One sentence in every language: the last item joins with the // language's "and". - let text = items.count < 2 ? items.joined() + return items.count < 2 ? items.joined() : items.dropLast().joined(separator: listSeparator) + listLastSeparator + items[items.count - 1] - return String(format: heldOD8Format, text) } /// The translated sentence of one group. diff --git a/Sources/RyzenStatus/Services/Metrics/GPUControlProfiles.swift b/Sources/RyzenStatus/Services/Metrics/GPUControlProfiles.swift index 0c59e010..b9fc98fd 100644 --- a/Sources/RyzenStatus/Services/Metrics/GPUControlProfiles.swift +++ b/Sources/RyzenStatus/Services/Metrics/GPUControlProfiles.swift @@ -447,13 +447,20 @@ enum GPUControlProfiles { return load } // A fan state and another kext build: the rules were not checked with - // it, and "Apply curve" is off too. + // it, and "Apply curve" is off too. The fan part is left out and the + // clocks and voltage still go; a profile that is only a fan state + // goes out as nothing. + var sendable = want if want.curve != nil || want.zeroRpmOff, !GPUControlCurveRules.isChecked(kextVersion) { - load.blocked = .fanNotChecked - return load + sendable.curve = nil + sendable.zeroRpmOff = false + if sendable.isStock { + load.blocked = .fanNotChecked + return load + } } guard let checked = GPUControlRememberPolicy.checkedAgain( - .od8(want), stockGfxMaxMHz: stockGfxMaxMHz, gfxMin: gfxMin, volt: volt, + .od8(sendable), stockGfxMaxMHz: stockGfxMaxMHz, gfxMin: gfxMin, volt: volt, overclock: overclock, overclockAllowed: overclockAllowed), case .od8(let kept) = checked else { let fields = leftOut(want, keptIn: .stock) diff --git a/Sources/RyzenStatus/UI/Settings/GPUControlProfilesSection.swift b/Sources/RyzenStatus/UI/Settings/GPUControlProfilesSection.swift index 7d18b951..a3d9fc51 100644 --- a/Sources/RyzenStatus/UI/Settings/GPUControlProfilesSection.swift +++ b/Sources/RyzenStatus/UI/Settings/GPUControlProfilesSection.swift @@ -126,7 +126,7 @@ struct GPUControlProfilesSection: View { private func summary(_ request: GPUControlRequest) -> String { switch request { case .power(let watts): return String(format: page.wattsFormat, Int(watts)) - case .od8(let want): return page.od8Held(want) + case .od8(let want): return page.od8Items(want) case .startUp: return "" } } diff --git a/Tests/Suites/GPUControlProfileTests.swift b/Tests/Suites/GPUControlProfileTests.swift index 7e41ea06..1335d818 100644 --- a/Tests/Suites/GPUControlProfileTests.swift +++ b/Tests/Suites/GPUControlProfileTests.swift @@ -229,6 +229,14 @@ enum GPUControlProfileTests { "a fan curve and an unchecked kext build: nothing goes, as Apply curve would not") suite.expect(load(profile("Fan", .od8(Want(curve: curve)))).request == .od8(Want(curve: curve)), "the checked build takes the same curve") + let mixedOnOld = load(profile("Mixed", .od8(Want(curve: curve, zeroRpmOff: true, gfxMaxMHz: 2_000))), + kextVersion: "REL-073-2026-12-01") + suite.expect(mixedOnOld.request == .od8(Want(gfxMaxMHz: 2_000)) && mixedOnOld.blocked == nil, + "an unchecked build: the clock still goes without the fan part") + suite.expect(mixedOnOld.leftOut == [.fanCurve, .zeroRpm], "and the fan part is named as left out") + let words = GPUControlPageStrings.enUS.od8Items(Want(gfxMaxMHz: 2_000)) + suite.expect(words.first?.isUppercase == true && !words.contains("RyzenStatus"), + "a profile's line lists the values, not \"RyzenStatus is holding\"") // Where writing stands. suite.expect(load(profile("Quiet", .power(watts: 220)), facts: facts(armed: false)).blocked == .writingClosed,