commit 2755ff8f82abf286adf6120a4674bb6847a7c311
Author: Jens Kristoffersson <jens.kristoffersson.se@gmail.com>
AuthorDate: Sat Nov 28 23:52:42 2026 +0100
Commit: Jens Kristoffersson <jens.kristoffersson.se@gmail.com>
CommitDate: Sat Nov 28 23:52:42 2026 +0100
TV-launcher: TV-gränssnitt i Qt6/QML för cage
Hemskärm i Netflix/Bigscreen-stil med kategorirader, egna program och
webbappar (inbyggd QtWebEngine, Chromium och appar installerade i
Chromium), styrning med handkontroll via SDL2 och virtuell mus/tangentbord
(uinput), skärmtangentbord, inställningar för ljud, Bluetooth, Wi-Fi,
tema och bakgrund, samt skript för session, uinput och AdGuard Home.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
---
.gitignore | 10 +
CMakeLists.txt | 74 ++++++++
README.md | 165 +++++++++++++++++
qml/AppEditor.qml | 265 ++++++++++++++++++++++++++
qml/AppTile.qml | 122 ++++++++++++
qml/AppearanceDialog.qml | 245 +++++++++++++++++++++++++
qml/AppsPage.qml | 73 ++++++++
qml/AudioPage.qml | 116 ++++++++++++
qml/Backdrop.qml | 43 +++++
qml/BluetoothPage.qml | 170 +++++++++++++++++
qml/CardList.qml | 64 +++++++
qml/HeroView.qml | 126 +++++++++++++
qml/HomeScreen.qml | 399 ++++++++++++++++++++++++++++++++++++++++
qml/Icon.qml | 10 +
qml/ImagePicker.qml | 104 +++++++++++
qml/InstalledPicker.qml | 133 ++++++++++++++
qml/Main.qml | 363 ++++++++++++++++++++++++++++++++++++
qml/OnScreenKeyboard.qml | 235 ++++++++++++++++++++++++
qml/OptionCycler.qml | 70 +++++++
qml/SearchPopup.qml | 149 +++++++++++++++
qml/SectionTitle.qml | 11 ++
qml/SettingsCard.qml | 179 ++++++++++++++++++
qml/SettingsView.qml | 151 +++++++++++++++
qml/SliderCard.qml | 83 +++++++++
qml/Theme.qml | 142 ++++++++++++++
qml/ThemePage.qml | 187 +++++++++++++++++++
qml/Toast.qml | 41 +++++
qml/TvButton.qml | 29 +++
qml/TvMenu.qml | 42 +++++
qml/WallpaperPage.qml | 107 +++++++++++
qml/WebAppView.qml | 99 ++++++++++
qml/WifiPage.qml | 244 ++++++++++++++++++++++++
qml/icons/add.svg | 1 +
qml/icons/apps.svg | 1 +
qml/icons/bluetooth.svg | 1 +
qml/icons/check.svg | 1 +
qml/icons/device.svg | 1 +
qml/icons/edit.svg | 1 +
qml/icons/gamepad.svg | 1 +
qml/icons/globe.svg | 1 +
qml/icons/headphones.svg | 1 +
qml/icons/home.svg | 1 +
qml/icons/image.svg | 1 +
qml/icons/keyboard.svg | 1 +
qml/icons/lock.svg | 1 +
qml/icons/palette.svg | 1 +
qml/icons/power.svg | 1 +
qml/icons/refresh.svg | 1 +
qml/icons/search.svg | 1 +
qml/icons/settings.svg | 1 +
qml/icons/speaker.svg | 1 +
qml/icons/volume-mute.svg | 1 +
qml/icons/volume.svg | 1 +
qml/icons/wifi.svg | 1 +
scripts/setup-adguard.sh | 198 ++++++++++++++++++++
scripts/setup-uinput.sh | 24 +++
scripts/tv-session.sh | 26 +++
src/appstore.cpp | 381 ++++++++++++++++++++++++++++++++++++++
src/appstore.h | 80 ++++++++
src/chromiumapps.cpp | 129 +++++++++++++
src/chromiumapps.h | 28 +++
src/desktopscanner.cpp | 106 +++++++++++
src/desktopscanner.h | 14 ++
src/iconfetcher.cpp | 122 ++++++++++++
src/iconfetcher.h | 39 ++++
src/iconprovider.cpp | 65 +++++++
src/iconprovider.h | 13 ++
src/inputmanager.cpp | 459 ++++++++++++++++++++++++++++++++++++++++++++++
src/inputmanager.h | 129 +++++++++++++
src/main.cpp | 129 +++++++++++++
src/prefs.cpp | 71 +++++++
src/prefs.h | 58 ++++++
src/processlauncher.cpp | 142 ++++++++++++++
src/processlauncher.h | 42 +++++
src/shell.cpp | 51 ++++++
src/shell.h | 18 ++
src/virtualinput.cpp | 163 ++++++++++++++++
src/virtualinput.h | 34 ++++
78 files changed, 6794 insertions(+)
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..c91ca0d
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,10 @@
+# Byggkatalog
+build/
+build-*/
+
+# Editor/IDE
+.vscode/
+.idea/
+*.user
+*~
+.*.swp
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644
index 0000000..0d91a87
--- /dev/null
+++ b/CMakeLists.txt
@@ -0,0 +1,74 @@
+cmake_minimum_required(VERSION 3.21)
+project(tv-launcher VERSION 0.1 LANGUAGES CXX)
+
+set(CMAKE_CXX_STANDARD 17)
+set(CMAKE_CXX_STANDARD_REQUIRED ON)
+
+find_package(Qt6 6.5 REQUIRED COMPONENTS Quick QuickControls2 WebEngineQuick Network)
+find_package(SDL2 REQUIRED)
+
+qt_standard_project_setup(REQUIRES 6.5)
+
+qt_add_executable(tv-launcher
+ src/main.cpp
+ src/appstore.h src/appstore.cpp
+ src/processlauncher.h src/processlauncher.cpp
+ src/inputmanager.h src/inputmanager.cpp
+ src/desktopscanner.h src/desktopscanner.cpp
+ src/iconprovider.h src/iconprovider.cpp
+ src/iconfetcher.h src/iconfetcher.cpp
+ src/shell.h src/shell.cpp
+ src/prefs.h src/prefs.cpp
+ src/chromiumapps.h src/chromiumapps.cpp
+ src/virtualinput.h src/virtualinput.cpp
+)
+
+file(GLOB ICON_FILES RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} qml/icons/*.svg)
+qt_policy(SET QTP0004 NEW)
+
+set_source_files_properties(qml/Theme.qml PROPERTIES QT_QML_SINGLETON_TYPE TRUE)
+
+qt_add_qml_module(tv-launcher
+ URI TvLauncher
+ VERSION 1.0
+ QML_FILES
+ qml/Main.qml
+ qml/Theme.qml
+ qml/HomeScreen.qml
+ qml/AppTile.qml
+ qml/AppEditor.qml
+ qml/OptionCycler.qml
+ qml/InstalledPicker.qml
+ qml/WebAppView.qml
+ qml/Toast.qml
+ qml/TvMenu.qml
+ qml/Icon.qml
+ qml/TvButton.qml
+ qml/Backdrop.qml
+ qml/SettingsCard.qml
+ qml/SliderCard.qml
+ qml/CardList.qml
+ qml/SectionTitle.qml
+ qml/SearchPopup.qml
+ qml/SettingsView.qml
+ qml/AudioPage.qml
+ qml/BluetoothPage.qml
+ qml/WifiPage.qml
+ qml/WallpaperPage.qml
+ qml/AppsPage.qml
+ qml/ThemePage.qml
+ qml/HeroView.qml
+ qml/AppearanceDialog.qml
+ qml/ImagePicker.qml
+ qml/OnScreenKeyboard.qml
+ RESOURCES
+ ${ICON_FILES}
+)
+
+target_link_libraries(tv-launcher PRIVATE
+ Qt6::Quick Qt6::QuickControls2 Qt6::WebEngineQuick Qt6::Network
+ SDL2::SDL2
+)
+
+include(GNUInstallDirs)
+install(TARGETS tv-launcher RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..2079351
--- /dev/null
+++ b/README.md
@@ -0,0 +1,165 @@
+# tv-launcher
+
+TV-gränssnitt i Qt6/QML som körs i [cage](https://github.com/cage-kiosk/cage).
+Designen är inspirerad av Plasma Bigscreen men utan beroenden till Plasma.
+
+- Hemskärm i Netflix-stil: flikar per kategori överst, stor header som visar
+ den markerade appen och en rad med appar under. Fliken "Senaste" visar det du nyss använt.
+- **Egna program**: valfritt kommando, eller välj bland installerade (.desktop-filer)
+- **Webbappar**: valfri adress, antingen i den inbyggda motorn (QtWebEngine) eller i
+ Chromium (behövs för DRM-tjänster som Netflix och Spotify). Varje webbapp får en egen
+ profil så att inloggningar sparas. Ikonen hämtas automatiskt från webbplatsen.
+- Styrs med tangentbord, mus eller handkontroll (8BitDo m.fl. via SDL2)
+
+## Installera beroenden
+
+```sh
+sudo apt install build-essential cmake \
+ qt6-base-dev qt6-declarative-dev qt6-webengine-dev qt6-wayland qt6-svg-plugins \
+ qml6-module-qtquick qml6-module-qtquick-controls qml6-module-qtquick-layouts \
+ qml6-module-qtquick-window qml6-module-qtquick-templates qml6-module-qtqml-workerscript \
+ qml6-module-qtwebengine libsdl2-dev \
+ intel-media-va-driver fonts-noto-core
+# Valfritt: program att starta
+sudo apt install retroarch mpv chromium
+```
+
+## Bygga
+
+```sh
+cmake -B build -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=$HOME/.local
+cmake --build build -j$(nproc)
+cmake --install build # -> ~/.local/bin/tv-launcher
+```
+
+Testa i ett vanligt fönster: `./build/tv-launcher --windowed`
+
+## Starta automatiskt på TV:n
+
+1. Automatisk inloggning på tty1:
+ ```sh
+ sudo systemctl edit getty@tty1
+ ```
+ och lägg in:
+ ```ini
+ [Service]
+ ExecStart=
+ ExecStart=-/sbin/agetty --autologin DITT_ANVÄNDARNAMN --noclear %I $TERM
+ ```
+2. Lägg till sist i `~/.bash_profile`:
+ ```sh
+ if [ -z "$WAYLAND_DISPLAY" ] && [ "$(tty)" = /dev/tty1 ]; then
+ exec ~/tv-launcher/scripts/tv-session.sh
+ fi
+ ```
+
+Terminal: Ctrl+Alt+F2.
+
+## Styrning
+
+| Handkontroll | Tangentbord | Funktion |
+|---------------------|----------------------|-----------------------------------|
+| D-pad / vänster spak| Piltangenter | Flytta (upp = flikraden) |
+| LB / RB | Page Up / Page Down | Byt flik |
+| A | Enter | Starta / välj |
+| B | Esc | Tillbaka / stäng dialog |
+| Y eller Start | Menytangenten / högerklick | Snabbmeny (redigera, flytta, ta bort) |
+| Home (kort) | Ctrl+Esc (i webbapp) | Till hemskärmen |
+| Home (håll 0,8 s) | – | Stäng programmet som körs |
+
+## Filer
+
+- `~/.config/tv-launcher/apps.json`: apparna på hemskärmen (kan redigeras för hand)
+- `~/.local/share/tv-launcher/icons/`: hämtade ikoner för webbappar
+- `~/.local/share/tv-launcher/QtWebEngine/web-<id>/`: inbyggda webbappars profiler
+- `~/.local/share/tv-launcher/chromium/<id>/`: Chromium-webbappars profiler
+
+Exempel på en post i `apps.json`:
+
+```json
+{ "id": "jellyfin", "name": "Jellyfin", "type": "web", "engine": "builtin",
+ "url": "http://192.168.1.10:8096", "category": "Media", "icon": "", "userAgent": "" }
+```
+
+## Tema
+
+Välj färgtema, accentfärg, rutstorlek och hörn under **Inställningar → Tema**.
+Valen sparas i `~/.config/tv-launcher/settings.ini` (avsnittet `[theme]`).
+
+Alla färger och mått finns i `qml/Theme.qml` (motsvarar CSS-variabler).
+Lägg till ett eget färgtema genom att kopiera ett av `presets` där, ge det en ny
+nyckel och lägga till nyckeln i `presetKeys`. Bygg sedan om.
+
+## Webbappar från Chromium
+
+Installera en webbplats som app i Chromium (meny → *Casta, spara och dela* →
+*Installera sidan som app* eller *Skapa genväg*). Den dyker då upp i launchern under
+**Webb** och startas med `--app-id`, med Chromiums vanliga profil och inloggningar.
+Avinstallerar du appen i Chromium försvinner den från launchern. Tar du bort den i
+launchern läggs den inte till igen.
+
+## Handkontroll i program och webbappar
+
+Spel och emulatorer (kategorin **Spel**, RetroArch m.fl.) läser kontrollen själva.
+I webbappar och andra program blir kontrollen en virtuell mus och tangentbord:
+
+| Kontroll | Funktion |
+|---------------|-------------------------------|
+| Vänster spak | Muspekare |
+| Höger spak | Scrolla |
+| D-pad | Piltangenter |
+| A | Klick |
+| B | Tillbaka |
+| X | Enter |
+| Y | Mellanslag (paus/spela) |
+| LB / RB | Föregående / nästa fält (Tab) |
+| LT / RT | Page Up / Page Down |
+| Start | Escape |
+| Select | Skärmtangentbord |
+| L3 | F (helskärm i videospelare) |
+| R3 | Högerklick |
+| Home (håll) | Stäng programmet |
+
+Läget kan ändras per app i **Redigera → Handkontroll**.
+
+Det kräver en engångsbehörighet för `/dev/uinput`:
+
+```sh
+sudo ~/tv-launcher/scripts/setup-uinput.sh
+```
+
+RetroArch behöver kontrollprofiler i `~/.config/retroarch/autoconfig`
+(libretros `retroarch-joypad-autoconfig`, mapparna `udev` och `sdl2`).
+
+## Reklamblockering (AdGuard Home)
+
+```sh
+sudo ~/tv-launcher/scripts/setup-adguard.sh # installera
+sudo ~/tv-launcher/scripts/setup-adguard.sh uninstall # ta bort och återställ DNS
+```
+
+Blockerar reklam- och spårningsadresser via DNS för den här datorn. Webbgränssnittet finns
+på `http://127.0.0.1` (lösenord i `~/.config/tv-launcher/adguard.txt`). Lägg gärna till det
+som webbapp. YouTube-reklam går inte att blockera via DNS.
+
+## Skärmtangentbord
+
+Tryck **Select** på kontrollen (eller **Ctrl+Mellanslag** på ett tangentbord).
+Skriv med D-pad och A, X raderar, RB är mellanslag, Y är Klar, B avbryter.
+
+- I launcherns textfält fylls fältet i direkt.
+- I webbappar och i Chromium och andra program skrivs texten in där markören står
+ när du trycker Klar (*Klar ↵* trycker även Enter, t.ex. för att söka).
+
+Texten till externa program skickas med svensk tangentbordslayout. `tv-session.sh`
+ställer in samma layout som systemet (`/etc/default/keyboard`) för cage.
+
+## Egna ikoner och förhandsbilder
+
+Lägg bilder (png, jpg, webp eller svg) med samma namn som appen i:
+
+- `~/Bilder/TV/Ikoner/`: blir appens ikon, t.ex. `Jellyfin.png`
+- `~/Bilder/TV/Förhandsbilder/`: blir bakgrund i förhandsvisningen överst, t.ex. `7Movies.jpg`
+
+Stora/små bokstäver, mellanslag och bindestreck spelar ingen roll. Ändringar syns direkt.
+En bild som valts under *Utseende och förhandsvisning* går före förhandsbilden i mappen.
diff --git a/qml/AppEditor.qml b/qml/AppEditor.qml
new file mode 100644
index 0000000..9f72b41
--- /dev/null
+++ b/qml/AppEditor.qml
@@ -0,0 +1,265 @@
+import QtQuick
+import QtQuick.Controls
+import QtQuick.Layouts
+import TvLauncher
+
+// Dialog för att lägga till och redigera program och webbappar.
+Popup {
+ id: editor
+
+ property string appId: ""
+ property string error: ""
+
+ parent: Overlay.overlay
+ anchors.centerIn: parent
+ width: Math.min(parent.width - Theme.dp(120), Theme.dp(1300))
+ modal: true
+ focus: true
+ padding: Theme.dp(40)
+ closePolicy: Popup.CloseOnEscape
+
+ background: Rectangle {
+ color: Theme.bg
+ radius: Theme.r(18)
+ border.color: Theme.borderSoft
+ border.width: Theme.dp(1)
+ }
+ Overlay.modal: Rectangle { color: Theme.scrim }
+
+ function openFor(app) {
+ appId = app.id || ""
+ error = ""
+ nameField.text = app.name || ""
+ typeCycler.value = app.type === "web" ? "web" : "app"
+ commandField.text = app.command || ""
+ urlField.text = app.url || ""
+ engineCycler.value = app.engine === "chromium" ? "chromium" : "builtin"
+ const ua = app.userAgent || ""
+ uaCycler.customValue = (ua !== "" && ua !== apps.tvUserAgent) ? ua : ""
+ uaCycler.value = ua
+ const cats = apps.knownCategories.slice()
+ if (app.category && cats.indexOf(app.category) < 0)
+ cats.push(app.category)
+ categoryCycler.options = cats.map(c => ({ value: c, label: c }))
+ categoryCycler.value = app.category || (typeCycler.value === "web" ? "Webb" : "Program")
+ iconField.text = app.icon || ""
+ controllerCycler.value = app.controllerMode || "auto"
+ open()
+ }
+
+ function save() {
+ const isWeb = typeCycler.value === "web"
+ if (nameField.text.trim() === "") { error = "Ange ett namn."; nameField.forceActiveFocus(); return }
+ if (isWeb && urlField.text.trim() === "") { error = "Ange en adress."; urlField.forceActiveFocus(); return }
+ if (!isWeb && commandField.text.trim() === "") { error = "Ange ett kommando."; commandField.forceActiveFocus(); return }
+ apps.save({
+ id: appId,
+ name: nameField.text,
+ type: typeCycler.value,
+ command: isWeb ? "" : commandField.text,
+ url: isWeb ? urlField.text : "",
+ engine: engineCycler.value,
+ userAgent: isWeb ? uaCycler.value : "",
+ category: categoryCycler.value,
+ controllerMode: controllerCycler.value === "auto" ? "" : controllerCycler.value,
+ icon: iconField.text
+ })
+ close()
+ }
+
+ onOpened: nameField.forceActiveFocus()
+
+ component Label2: Text {
+ Layout.preferredWidth: Theme.dp(220)
+ color: Theme.textDim
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(24)
+ }
+
+ component Field: TextField {
+ Layout.fillWidth: true
+ Layout.preferredHeight: Theme.dp(60)
+ color: Theme.text
+ placeholderTextColor: Theme.placeholder
+ selectionColor: Theme.accent
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(24)
+ leftPadding: Theme.dp(16)
+ background: Rectangle {
+ radius: Theme.r(8)
+ color: parent.activeFocus ? Theme.surfaceHi : Theme.surface
+ border.width: parent.activeFocus ? Theme.dp(3) : Theme.dp(1)
+ border.color: parent.activeFocus ? Theme.accent : Theme.border
+ }
+ }
+
+
+ contentItem: RowLayout {
+ spacing: Theme.dp(40)
+
+ ColumnLayout {
+ Layout.fillWidth: true
+ spacing: Theme.dp(16)
+
+ Text {
+ text: editor.appId === "" ? "Lägg till" : "Redigera"
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(36)
+ Layout.bottomMargin: Theme.dp(10)
+ }
+
+ RowLayout {
+ Label2 { text: "Namn" }
+ Field {
+ id: nameField
+ placeholderText: "t.ex. Jellyfin"
+ KeyNavigation.down: typeCycler
+ onAccepted: typeCycler.forceActiveFocus()
+ }
+ }
+ RowLayout {
+ Label2 { text: "Typ" }
+ OptionCycler {
+ id: typeCycler
+ Layout.fillWidth: true
+ options: [{ value: "app", label: "Program" }, { value: "web", label: "Webbapp" }]
+ KeyNavigation.up: nameField
+ KeyNavigation.down: commandField
+ }
+ }
+ RowLayout {
+ visible: typeCycler.value === "app"
+ Label2 { text: "Kommando" }
+ Field {
+ id: commandField
+ placeholderText: "t.ex. retroarch eller mpv --fs ~/Musik"
+ KeyNavigation.up: typeCycler
+ KeyNavigation.down: urlField
+ }
+ }
+ RowLayout {
+ visible: typeCycler.value === "web"
+ Label2 { text: "Adress" }
+ Field {
+ id: urlField
+ placeholderText: "t.ex. http://192.168.1.10:8096"
+ inputMethodHints: Qt.ImhUrlCharactersOnly
+ KeyNavigation.up: commandField
+ KeyNavigation.down: engineCycler
+ }
+ }
+ RowLayout {
+ visible: typeCycler.value === "web"
+ Label2 { text: "Motor" }
+ OptionCycler {
+ id: engineCycler
+ Layout.fillWidth: true
+ options: [
+ { value: "builtin", label: "Inbyggd (snabb, styrs med kontrollen)" },
+ { value: "chromium", label: "Chromium (för DRM: Netflix, Spotify ...)" }
+ ]
+ KeyNavigation.up: urlField
+ KeyNavigation.down: uaCycler
+ }
+ }
+ RowLayout {
+ visible: typeCycler.value === "web"
+ Label2 { text: "Visa som" }
+ OptionCycler {
+ id: uaCycler
+ property string customValue: ""
+ Layout.fillWidth: true
+ options: {
+ const o = [{ value: "", label: "Vanlig webbläsare" },
+ { value: apps.tvUserAgent, label: "Smart-TV (t.ex. youtube.com/tv)" }]
+ if (customValue !== "")
+ o.push({ value: customValue, label: "Egen user agent" })
+ return o
+ }
+ KeyNavigation.up: engineCycler
+ KeyNavigation.down: categoryCycler
+ }
+ }
+ RowLayout {
+ Label2 { text: "Kategori" }
+ OptionCycler {
+ id: categoryCycler
+ Layout.fillWidth: true
+ KeyNavigation.up: uaCycler
+ KeyNavigation.down: controllerCycler
+ }
+ }
+ RowLayout {
+ Label2 { text: "Handkontroll" }
+ OptionCycler {
+ id: controllerCycler
+ Layout.fillWidth: true
+ options: [
+ { value: "auto", label: "Automatiskt" },
+ { value: "keyboard", label: "Mus och tangentbord" },
+ { value: "gamepad", label: "Handkontroll (spel)" }
+ ]
+ KeyNavigation.up: categoryCycler
+ KeyNavigation.down: iconField
+ }
+ }
+ RowLayout {
+ Label2 { text: "Ikon" }
+ Field {
+ id: iconField
+ placeholderText: typeCycler.value === "web" ? "Tomt = hämtas från webbplatsen"
+ : "Ikonnamn (t.ex. retroarch) eller sökväg"
+ KeyNavigation.up: controllerCycler
+ KeyNavigation.down: saveButton
+ }
+ }
+
+ Text {
+ visible: editor.error !== ""
+ text: editor.error
+ color: Theme.danger
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(22)
+ }
+
+ RowLayout {
+ Layout.topMargin: Theme.dp(16)
+ spacing: Theme.dp(20)
+ TvButton {
+ id: saveButton
+ text: "Spara"
+ onClicked: editor.save()
+ KeyNavigation.up: iconField
+ KeyNavigation.right: cancelButton
+ }
+ TvButton {
+ id: cancelButton
+ text: "Avbryt"
+ onClicked: editor.close()
+ KeyNavigation.up: iconField
+ KeyNavigation.right: deleteButton
+ }
+ TvButton {
+ id: deleteButton
+ visible: editor.appId !== ""
+ danger: true
+ text: "Ta bort"
+ onClicked: { apps.remove(editor.appId); editor.close() }
+ KeyNavigation.up: iconField
+ }
+ Item { Layout.fillWidth: true }
+ }
+ }
+
+ // Förhandsvisning av rutan.
+ AppTile {
+ Layout.alignment: Qt.AlignTop
+ Layout.topMargin: Theme.dp(80)
+ enabled: false
+ name: nameField.text || "Namn"
+ icon: iconField.text
+ isWeb: typeCycler.value === "web"
+ }
+ }
+}
diff --git a/qml/AppTile.qml b/qml/AppTile.qml
new file mode 100644
index 0000000..db272c2
--- /dev/null
+++ b/qml/AppTile.qml
@@ -0,0 +1,122 @@
+import QtQuick
+import TvLauncher
+
+// En ruta på hemskärmen i Bigscreen-stil: färgat kort med ikon,
+// namn och undertext under.
+Item {
+ id: tile
+
+ property string name
+ property string subtitle
+ property string icon
+ property string glyph
+ property bool isWeb: false
+ property string customColor // egen färg, tom = enligt temat
+
+ signal activated()
+ signal menuRequested()
+ signal hovered()
+
+ width: Theme.tile(340)
+ height: Theme.tile(300)
+ z: activeFocus ? 10 : 0
+
+ Keys.onReturnPressed: tile.activated()
+ Keys.onEnterPressed: tile.activated()
+ Keys.onMenuPressed: tile.menuRequested()
+
+ Item {
+ id: body
+ anchors.fill: parent
+ scale: tile.activeFocus ? 1.05 : 1.0
+ transformOrigin: Item.Top
+ Behavior on scale { NumberAnimation { duration: 140; easing.type: Easing.OutCubic } }
+
+ Rectangle {
+ id: card
+ anchors { left: parent.left; right: parent.right; top: parent.top }
+ height: Theme.tile(205)
+ radius: Theme.r(12)
+ color: tile.glyph !== "" ? Theme.cardFocus : Theme.tileColor(tile.name, tile.customColor)
+ border.width: tile.activeFocus ? Theme.dp(5) : 0
+ border.color: Theme.accent
+
+ Image {
+ id: img
+ anchors.centerIn: parent
+ width: Theme.tile(112)
+ height: width
+ sourceSize: Qt.size(256, 256)
+ fillMode: Image.PreserveAspectFit
+ asynchronous: true
+ smooth: true
+ source: tile.icon !== "" ? "image://icon/" + encodeURIComponent(tile.icon) : ""
+ visible: status === Image.Ready && implicitWidth > 1
+ }
+
+ Text {
+ anchors.centerIn: parent
+ visible: !img.visible
+ text: tile.glyph !== "" ? tile.glyph : tile.name.charAt(0).toUpperCase()
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: tile.glyph !== "" ? Theme.tile(64) : Theme.tile(88)
+ font.weight: Font.DemiBold
+ }
+
+ Rectangle {
+ visible: tile.isWeb
+ anchors { right: parent.right; top: parent.top; margins: Theme.dp(12) }
+ radius: Theme.r(6)
+ color: "#80000000"
+ width: webLabel.implicitWidth + Theme.dp(14)
+ height: webLabel.implicitHeight + Theme.dp(6)
+ Text {
+ id: webLabel
+ anchors.centerIn: parent
+ text: "WEBB"
+ color: Theme.textDim
+ font.pixelSize: Theme.dp(14)
+ font.weight: Font.Bold
+ }
+ }
+ }
+
+ Column {
+ anchors { left: parent.left; right: parent.right; top: card.bottom; topMargin: Theme.dp(14); leftMargin: Theme.dp(4) }
+ spacing: Theme.dp(2)
+ Text {
+ width: parent.width
+ text: tile.name
+ elide: Text.ElideRight
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(28)
+ }
+ Text {
+ width: parent.width
+ visible: text !== ""
+ text: tile.subtitle
+ elide: Text.ElideRight
+ color: Theme.textDim
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(21)
+ }
+ }
+ }
+
+ MouseArea {
+ anchors.fill: parent
+ hoverEnabled: true
+ acceptedButtons: Qt.LeftButton | Qt.RightButton
+ onEntered: tile.hovered()
+ onClicked: (mouse) => {
+ tile.hovered()
+ if (mouse.button === Qt.RightButton)
+ tile.menuRequested()
+ else
+ tile.activated()
+ }
+ onPressAndHold: tile.menuRequested()
+ }
+}
diff --git a/qml/AppearanceDialog.qml b/qml/AppearanceDialog.qml
new file mode 100644
index 0000000..a11e8da
--- /dev/null
+++ b/qml/AppearanceDialog.qml
@@ -0,0 +1,245 @@
+import QtQuick
+import QtQuick.Controls
+import QtQuick.Layouts
+import TvLauncher
+
+// "Utseende och förhandsvisning" för en app: egen bild och text i
+// förhandsvisningen överst på hemskärmen, om ikonen ska synas och rutans färg.
+// Förhandsvisningen i dialogen uppdateras medan man ändrar.
+Popup {
+ id: dlg
+
+ property string appId: ""
+ property var base: ({})
+ property string image: ""
+ property string heroText: ""
+ property bool showIcon: true
+ property string tileColor: ""
+
+ readonly property var draft: Object.assign({}, base, {
+ heroImage: image, heroText: heroText.trim(), heroShowIcon: showIcon, color: tileColor
+ })
+
+ function openFor(app) {
+ base = apps.get(app.id)
+ appId = app.id
+ image = base.heroImage || ""
+ heroText = base.heroText || ""
+ showIcon = base.heroShowIcon !== false
+ tileColor = base.color || ""
+ imageField.text = image
+ textField.text = heroText
+ open()
+ }
+
+ function save() {
+ apps.patch(appId, {
+ heroImage: image.trim(),
+ heroText: heroText.trim(),
+ heroShowIcon: showIcon ? "" : false, // tomt = standard (visa)
+ color: tileColor
+ })
+ close()
+ }
+
+ parent: Overlay.overlay
+ anchors.centerIn: parent
+ width: Math.min(parent.width - Theme.dp(100), Theme.dp(1600))
+ modal: true
+ focus: true
+ padding: Theme.dp(36)
+ closePolicy: Popup.CloseOnEscape
+
+ background: Rectangle { color: Theme.bg; radius: Theme.r(18); border.color: Theme.borderSoft; border.width: Theme.dp(1) }
+ Overlay.modal: Rectangle { color: Theme.scrim }
+
+ onOpened: imageButton.forceActiveFocus()
+
+ component Label2: Text {
+ Layout.preferredWidth: Theme.dp(200)
+ color: Theme.textDim
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(24)
+ }
+ component Field: TextField {
+ Layout.fillWidth: true
+ Layout.preferredHeight: Theme.dp(60)
+ color: Theme.text
+ placeholderTextColor: Theme.placeholder
+ selectionColor: Theme.accent
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(24)
+ leftPadding: Theme.dp(16)
+ background: Rectangle {
+ radius: Theme.r(8)
+ color: parent.activeFocus ? Theme.surfaceHi : Theme.surface
+ border.width: parent.activeFocus ? Theme.dp(3) : Theme.dp(1)
+ border.color: parent.activeFocus ? Theme.accent : Theme.border
+ }
+ }
+
+ ImagePicker {
+ id: imagePicker
+ onPicked: (path) => { imageField.text = path; dlg.image = path }
+ onClosed: imageButton.forceActiveFocus()
+ }
+
+ contentItem: ColumnLayout {
+ spacing: Theme.dp(16)
+
+ Text {
+ text: "Utseende: " + (dlg.base.name || "")
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(36)
+ }
+
+ // Förhandsvisning: hemskärmens header i liten skala + rutan.
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: Theme.dp(28)
+
+ Item {
+ id: previewBox
+ Layout.fillWidth: true
+ Layout.preferredHeight: Math.min(width * Theme.dp(600) / dlg.parent.width, Theme.dp(280))
+ clip: true
+
+ Backdrop { anchors.fill: parent }
+ Rectangle {
+ anchors.fill: parent
+ gradient: Gradient {
+ orientation: Gradient.Horizontal
+ GradientStop { position: 0.0; color: "#b0000000" }
+ GradientStop { position: 0.45; color: "#60000000" }
+ GradientStop { position: 0.75; color: "#00000000" }
+ }
+ }
+ HeroView {
+ width: dlg.parent.width
+ height: previewBox.height / scale
+ transformOrigin: Item.TopLeft
+ scale: previewBox.width / dlg.parent.width
+ app: dlg.draft
+ }
+ Rectangle {
+ anchors.fill: parent
+ color: "transparent"
+ radius: Theme.r(10)
+ border.color: Theme.border
+ border.width: Theme.dp(1)
+ }
+ }
+
+ Item {
+ Layout.alignment: Qt.AlignVCenter
+ Layout.preferredWidth: Theme.tile(340) * 0.8
+ Layout.preferredHeight: Theme.tile(300) * 0.8
+ AppTile {
+ scale: 0.8
+ transformOrigin: Item.TopLeft
+ enabled: false
+ name: dlg.base.name || ""
+ subtitle: "Rutan"
+ icon: dlg.base.icon || ""
+ customColor: dlg.tileColor
+ isWeb: dlg.base.type === "web"
+ }
+ }
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: Theme.dp(16)
+ Label2 { text: "Bild" }
+ Field {
+ id: imageField
+ placeholderText: "Sökväg (~/Bilder/...) eller webbadress (https://...)"
+ onTextChanged: dlg.image = text
+ KeyNavigation.right: imageButton
+ KeyNavigation.down: textField
+ }
+ TvButton {
+ id: imageButton
+ text: "Välj bild …"
+ onClicked: imagePicker.open()
+ KeyNavigation.left: imageField
+ KeyNavigation.right: clearImageButton
+ KeyNavigation.down: textField
+ }
+ TvButton {
+ id: clearImageButton
+ text: "Ingen bild"
+ onClicked: { imageField.text = ""; dlg.image = "" }
+ KeyNavigation.left: imageButton
+ KeyNavigation.down: textField
+ }
+ }
+
+ RowLayout {
+ Layout.fillWidth: true
+ spacing: Theme.dp(16)
+ Label2 { text: "Text" }
+ Field {
+ id: textField
+ placeholderText: "Egen text under namnet (tomt = adress eller kommando)"
+ onTextChanged: dlg.heroText = text
+ KeyNavigation.up: imageButton
+ KeyNavigation.down: iconCard
+ }
+ }
+
+ SettingsCard {
+ id: iconCard
+ Layout.fillWidth: true
+ icon: "image"
+ title: "Visa ikonen i förhandsvisningen"
+ toggle: dlg.showIcon
+ onActivated: dlg.showIcon = !dlg.showIcon
+ KeyNavigation.up: textField
+ KeyNavigation.down: colorCard
+ }
+
+ SettingsCard {
+ id: colorCard
+ Layout.fillWidth: true
+ icon: "palette"
+ title: "Rutans färg"
+ subtitle: "Automatisk följer inställningen under Tema"
+ options: Theme.tileColorChoices
+ value: dlg.tileColor
+ onChosen: (v) => dlg.tileColor = v
+ KeyNavigation.up: iconCard
+ KeyNavigation.down: saveButton
+ }
+
+ RowLayout {
+ Layout.topMargin: Theme.dp(8)
+ spacing: Theme.dp(20)
+ TvButton {
+ id: saveButton
+ text: "Spara"
+ onClicked: dlg.save()
+ KeyNavigation.up: colorCard
+ KeyNavigation.right: cancelButton
+ }
+ TvButton {
+ id: cancelButton
+ text: "Avbryt"
+ onClicked: dlg.close()
+ KeyNavigation.up: colorCard
+ KeyNavigation.right: resetButton
+ }
+ TvButton {
+ id: resetButton
+ text: "Återställ"
+ onClicked: {
+ imageField.text = ""; textField.text = ""
+ dlg.image = ""; dlg.heroText = ""; dlg.showIcon = true; dlg.tileColor = ""
+ }
+ KeyNavigation.up: colorCard
+ }
+ Item { Layout.fillWidth: true }
+ }
+ }
+}
diff --git a/qml/AppsPage.qml b/qml/AppsPage.qml
new file mode 100644
index 0000000..f8fb931
--- /dev/null
+++ b/qml/AppsPage.qml
@@ -0,0 +1,73 @@
+import QtQuick
+import TvLauncher
+
+// Lista över alla appar och webbappar med möjlighet att lägga till och redigera.
+Item {
+ id: page
+
+ signal editApp(var app)
+ signal addApp(string type)
+ signal pickInstalled()
+
+ readonly property var all: {
+ apps.revision
+ let out = []
+ for (const c of apps.categories) out = out.concat(apps.appsIn(c))
+ return out
+ }
+
+ // Kortet som hade fokus, så att vi hittar tillbaka när listan byggs om.
+ property int lastIndex: -1
+ function focusFirst() {
+ const cs = list.cards()
+ if (lastIndex >= 0 && cs.length > 0) {
+ const c = cs[Math.min(lastIndex, cs.length - 1)]
+ c.forceActiveFocus()
+ list.ensureVisible(c)
+ } else {
+ list.focusFirst()
+ }
+ }
+
+ CardList {
+ id: list
+ anchors.fill: parent
+
+ SettingsCard {
+ icon: "add"
+ title: "Lägg till program"
+ subtitle: "Ett eget kommando, t.ex. ett spel, en emulator eller ett skript"
+ onActivated: page.addApp("app")
+ }
+ SettingsCard {
+ icon: "globe"
+ title: "Lägg till webbapp"
+ subtitle: "Gör en webbplats till en app, t.ex. Jellyfin, SVT Play eller Spotify"
+ onActivated: page.addApp("web")
+ }
+ SettingsCard {
+ icon: "apps"
+ title: "Från installerade program"
+ subtitle: "Välj bland programmen som finns på datorn"
+ onActivated: page.pickInstalled()
+ }
+
+ SectionTitle { text: "Dina appar (" + page.all.length + ")" }
+ Repeater {
+ model: page.all
+ delegate: SettingsCard {
+ required property var modelData
+ required property int index
+ onActiveFocusChanged: if (activeFocus) page.lastIndex = index + 3
+ appIcon: modelData.icon || " "
+ title: modelData.name
+ subtitle: modelData.category + " · " + (modelData.type === "web"
+ ? "Webbapp: " + modelData.url + (modelData.engine === "chromium" ? " (Chromium)" : "")
+ : modelData.command)
+ valueText: "Redigera"
+ onActivated: page.editApp(modelData)
+ onMenuRequested: page.editApp(modelData)
+ }
+ }
+ }
+}
diff --git a/qml/AudioPage.qml b/qml/AudioPage.qml
new file mode 100644
index 0000000..c89d4d5
--- /dev/null
+++ b/qml/AudioPage.qml
@@ -0,0 +1,116 @@
+import QtQuick
+import TvLauncher
+
+// Ljud via PipeWire/WirePlumber (wpctl).
+Item {
+ id: page
+
+ readonly property bool available: shell.has("wpctl")
+ property real volume: 0
+ property bool muted: false
+ property var sinks: []
+ property string error: ""
+
+ function focusFirst() { list.focusFirst() }
+
+ function refresh() {
+ if (!available) return
+ shell.run("wpctl", ["get-volume", "@DEFAULT_AUDIO_SINK@"], (code, out, err) => {
+ if (code !== 0) {
+ error = (err || out).trim() || "Kunde inte läsa volymen."
+ return
+ }
+ error = ""
+ const m = out.match(/Volume:\s*([\d.]+)/)
+ if (m) volume = Math.min(1, parseFloat(m[1]))
+ muted = out.indexOf("MUTED") >= 0
+ })
+ shell.run("wpctl", ["status"], (code, out) => {
+ if (code === 0) sinks = parseSinks(out)
+ })
+ }
+
+ // Plockar ut "Sinks:" under "Audio" ur wpctl status.
+ function parseSinks(text) {
+ const out = []
+ let inAudio = false, inSinks = false
+ for (const raw of text.split("\n")) {
+ const t = raw.trim()
+ if (/^Audio\b/.test(t)) { inAudio = true; continue }
+ if (/^(Video|Settings)\b/.test(t)) { inAudio = false; inSinks = false; continue }
+ if (!inAudio) continue
+ if (t.indexOf("Sinks:") >= 0) { inSinks = true; continue }
+ if (/(Sources|Filters|Streams|Devices|Sink endpoints|Source endpoints):/.test(t)) { inSinks = false; continue }
+ if (!inSinks) continue
+ const s = raw.replace(/^[\s│├└─]+/, "")
+ const m = s.match(/^(\*)?\s*(\d+)\.\s+(.*?)(\s+\[vol:.*\])?\s*$/)
+ if (m) out.push({ id: m[2], name: m[3], isDefault: m[1] === "*" })
+ }
+ return out
+ }
+
+ function setVolume(v) {
+ volume = v
+ shell.run("wpctl", ["set-volume", "-l", "1.0", "@DEFAULT_AUDIO_SINK@", v.toFixed(2)], () => refresh())
+ }
+ function toggleMute() {
+ muted = !muted
+ shell.run("wpctl", ["set-mute", "@DEFAULT_AUDIO_SINK@", "toggle"], () => refresh())
+ }
+ function setDefault(id) {
+ shell.run("wpctl", ["set-default", id], () => refresh())
+ }
+
+ Component.onCompleted: refresh()
+ Timer { interval: 4000; running: page.available && page.visible; repeat: true; onTriggered: page.refresh() }
+
+ CardList {
+ id: list
+ anchors.fill: parent
+
+ SettingsCard {
+ visible: !page.available
+ icon: "volume-mute"
+ title: "Ljudsystemet saknas"
+ subtitle: "Installera PipeWire och logga sedan ut och in igen:\nsudo apt install pipewire-audio wireplumber"
+ }
+ SettingsCard {
+ visible: page.available && page.error !== ""
+ icon: "volume-mute"
+ title: "Kunde inte nå ljudsystemet"
+ subtitle: page.error + "\nKontrollera: systemctl --user status pipewire wireplumber"
+ }
+ SliderCard {
+ visible: page.available && page.error === ""
+ icon: page.muted ? "volume-mute" : "volume"
+ title: "Volym"
+ value: page.volume
+ valueText: page.muted ? "Ljud av" : Math.round(page.volume * 100) + " %"
+ onMoved: (v) => page.setVolume(v)
+ onActivated: page.toggleMute()
+ }
+ SettingsCard {
+ visible: page.available && page.error === ""
+ icon: "volume-mute"
+ title: "Stäng av ljudet"
+ toggle: page.muted
+ onActivated: page.toggleMute()
+ }
+
+ SectionTitle {
+ visible: page.available && page.sinks.length > 0
+ text: "Ljudutgång"
+ }
+ Repeater {
+ model: page.sinks
+ delegate: SettingsCard {
+ required property var modelData
+ icon: /hdmi|displayport/i.test(modelData.name) ? "speaker" : (/head|blue|bt/i.test(modelData.name) ? "headphones" : "volume")
+ title: modelData.name
+ subtitle: modelData.isDefault ? "Används nu" : "Tryck för att använda"
+ checked: modelData.isDefault
+ onActivated: page.setDefault(modelData.id)
+ }
+ }
+ }
+}
diff --git a/qml/Backdrop.qml b/qml/Backdrop.qml
new file mode 100644
index 0000000..bc0a9e5
--- /dev/null
+++ b/qml/Backdrop.qml
@@ -0,0 +1,43 @@
+import QtQuick
+import TvLauncher
+
+// Bakgrund: vald bild, annars en mörk färgtoning i Bigscreen-stil.
+Item {
+ id: backdrop
+
+ Rectangle {
+ anchors.fill: parent
+ gradient: Gradient {
+ GradientStop { position: 0.0; color: Theme.backdropTop }
+ GradientStop { position: 0.55; color: Theme.backdropMid }
+ GradientStop { position: 1.0; color: Theme.backdropBottom }
+ }
+ }
+ Rectangle {
+ anchors.fill: parent
+ gradient: Gradient {
+ orientation: Gradient.Horizontal
+ GradientStop { position: 0.0; color: "#00000000" }
+ GradientStop { position: 1.0; color: Theme.alpha(Theme.backdropGlow, 0.25) }
+ }
+ }
+
+ Image {
+ id: img
+ anchors.fill: parent
+ source: prefs.wallpaper !== "" ? "file://" + prefs.wallpaper : ""
+ fillMode: Image.PreserveAspectCrop
+ sourceSize: Qt.size(backdrop.width, backdrop.height)
+ asynchronous: true
+ cache: false
+ opacity: status === Image.Ready ? 1 : 0
+ Behavior on opacity { NumberAnimation { duration: 400 } }
+ }
+
+ // Dämpning så att text och rutor syns.
+ Rectangle {
+ anchors.fill: parent
+ color: "black"
+ opacity: prefs.dim
+ }
+}
diff --git a/qml/BluetoothPage.qml b/qml/BluetoothPage.qml
new file mode 100644
index 0000000..8e79142
--- /dev/null
+++ b/qml/BluetoothPage.qml
@@ -0,0 +1,170 @@
+import QtQuick
+import TvLauncher
+
+// Bluetooth via BlueZ (bluetoothctl): sätt på, sök, parkoppla och anslut
+// t.ex. handkontroller, tangentbord och hörlurar.
+Item {
+ id: page
+
+ readonly property bool available: shell.has("bluetoothctl")
+ property bool serviceOk: true
+ property bool powered: false
+ property bool scanning: false
+ property var devices: []
+ property string busyMac: ""
+ property string status: ""
+
+ function focusFirst() { list.focusFirst() }
+
+ function parseDevices(text) {
+ const out = []
+ for (const line of text.split("\n")) {
+ const m = line.trim().match(/^Device\s+([0-9A-F:]{17})\s+(.*)$/i)
+ if (m) out.push({ mac: m[1].toUpperCase(), name: m[2].trim() })
+ }
+ return out
+ }
+
+ function refresh() {
+ if (!available) return
+ shell.run("bluetoothctl", ["show"], (code, out) => {
+ serviceOk = code === 0 && out.indexOf("Controller") >= 0
+ powered = /Powered:\s*yes/.test(out)
+ }, 8000)
+ shell.run("bluetoothctl", ["devices"], (c1, all) => {
+ shell.run("bluetoothctl", ["devices", "Paired"], (c2, paired) => {
+ shell.run("bluetoothctl", ["devices", "Connected"], (c3, conn) => {
+ const p = new Set(parseDevices(paired).map(d => d.mac))
+ const c = new Set(parseDevices(conn).map(d => d.mac))
+ const list = parseDevices(all).map(d => ({
+ mac: d.mac, name: d.name, paired: p.has(d.mac), connected: c.has(d.mac)
+ })).filter(d => d.paired || d.name.replace(/-/g, ":").toUpperCase() !== d.mac)
+ list.sort((a, b) => (b.connected - a.connected) || (b.paired - a.paired)
+ || a.name.localeCompare(b.name))
+ devices = list
+ }, 8000)
+ }, 8000)
+ }, 8000)
+ }
+
+ function setPower(on) {
+ shell.run("bluetoothctl", ["power", on ? "on" : "off"], () => refresh(), 8000)
+ }
+
+ function scan() {
+ if (scanning) return
+ if (!powered) setPower(true)
+ scanning = true
+ status = "Söker efter enheter i 20 sekunder. Sätt enheten i parkopplingsläge."
+ shell.run("bluetoothctl", ["--timeout", "20", "scan", "on"], () => {
+ scanning = false
+ status = ""
+ refresh()
+ }, 30000)
+ }
+
+ function iconFor(name) {
+ if (/8bitdo|controller|gamepad|pad|xbox|dualsense|dualshock|joy-?con|pro con/i.test(name)) return "gamepad"
+ if (/keyboard|keys|tangentbord/i.test(name)) return "keyboard"
+ if (/head|buds|airpods|wh-|wf-|earbud|hörlur/i.test(name)) return "headphones"
+ if (/speaker|soundbar|jbl|sonos/i.test(name)) return "speaker"
+ return "device"
+ }
+
+ function activate(d) {
+ if (busyMac !== "") return
+ busyMac = d.mac
+ const done = (msg) => { busyMac = ""; status = msg; refresh() }
+ if (d.connected) {
+ shell.run("bluetoothctl", ["disconnect", d.mac], (c) => done(c === 0 ? "Frånkopplad: " + d.name : "Kunde inte koppla från " + d.name), 15000)
+ } else if (d.paired) {
+ status = "Ansluter till " + d.name + " ..."
+ shell.run("bluetoothctl", ["connect", d.mac], (c, out) =>
+ done(/successful/i.test(out) ? "Ansluten: " + d.name : "Kunde inte ansluta till " + d.name + ". Är den påslagen?"), 20000)
+ } else {
+ status = "Parkopplar " + d.name + " ..."
+ shell.run("bluetoothctl", ["--agent", "NoInputNoOutput", "--timeout", "25", "pair", d.mac], (c, out) => {
+ if (!/Pairing successful|AlreadyExists/i.test(out)) {
+ done("Parkopplingen misslyckades. Sätt " + d.name + " i parkopplingsläge och försök igen.")
+ return
+ }
+ shell.run("bluetoothctl", ["trust", d.mac], () => {
+ shell.run("bluetoothctl", ["connect", d.mac], (c3, out3) =>
+ done(/successful/i.test(out3) ? "Klar! " + d.name + " är ansluten." : "Parkopplad, men kunde inte ansluta ännu."), 20000)
+ }, 8000)
+ }, 35000)
+ }
+ }
+
+ function forget(d) {
+ shell.run("bluetoothctl", ["remove", d.mac], () => { status = "Glömde " + d.name; refresh() }, 8000)
+ }
+
+ Component.onCompleted: refresh()
+ Timer { interval: page.scanning ? 2000 : 6000; running: page.available && page.visible; repeat: true; onTriggered: page.refresh() }
+
+ CardList {
+ id: list
+ anchors.fill: parent
+
+ SettingsCard {
+ visible: !page.available
+ icon: "bluetooth"
+ title: "Bluetooth saknas"
+ subtitle: "Installera BlueZ:\nsudo apt install bluez\nsudo systemctl enable --now bluetooth"
+ }
+ SettingsCard {
+ visible: page.available && !page.serviceOk
+ icon: "bluetooth"
+ title: "Bluetooth-tjänsten svarar inte"
+ subtitle: "Starta den med: sudo systemctl enable --now bluetooth"
+ onActivated: page.refresh()
+ }
+ SettingsCard {
+ visible: page.available && page.serviceOk
+ icon: "bluetooth"
+ title: "Bluetooth"
+ subtitle: page.powered ? "På" : "Av"
+ toggle: page.powered
+ onActivated: page.setPower(!page.powered)
+ }
+ SettingsCard {
+ visible: page.available && page.serviceOk
+ icon: "search"
+ title: page.scanning ? "Söker ..." : "Sök efter nya enheter"
+ subtitle: "Sätt handkontrollen eller tangentbordet i parkopplingsläge först"
+ busy: page.scanning
+ onActivated: page.scan()
+ }
+ Text {
+ width: parent.width
+ visible: page.status !== ""
+ text: page.status
+ color: Theme.accent
+ wrapMode: Text.Wrap
+ topPadding: Theme.dp(10)
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(24)
+ }
+
+ SectionTitle {
+ visible: page.devices.length > 0
+ text: "Enheter"
+ }
+ Repeater {
+ model: page.devices
+ delegate: SettingsCard {
+ required property var modelData
+ icon: page.iconFor(modelData.name)
+ title: modelData.name
+ subtitle: modelData.connected ? "Ansluten · tryck för att koppla från"
+ : modelData.paired ? "Parkopplad · tryck för att ansluta · Y: glöm"
+ : "Ny enhet · tryck för att parkoppla"
+ checked: modelData.connected
+ busy: page.busyMac === modelData.mac
+ onActivated: page.activate(modelData)
+ onMenuRequested: if (modelData.paired) page.forget(modelData)
+ }
+ }
+ }
+}
diff --git a/qml/CardList.qml b/qml/CardList.qml
new file mode 100644
index 0000000..a359b3c
--- /dev/null
+++ b/qml/CardList.qml
@@ -0,0 +1,64 @@
+import QtQuick
+import TvLauncher
+
+// Skrollbar kolumn med kort. Upp/ner flyttar mellan barn som har
+// "focusable: true" och skrollar så att det markerade kortet syns.
+Flickable {
+ id: fl
+
+ default property alias content: col.data
+ property alias spacing: col.spacing
+
+ contentHeight: col.implicitHeight + Theme.dp(40)
+ clip: true
+ boundsBehavior: Flickable.StopAtBounds
+
+ function cards() {
+ const out = []
+ for (let i = 0; i < col.children.length; ++i) {
+ const c = col.children[i]
+ if (c.visible && c.focusable === true)
+ out.push(c)
+ }
+ return out
+ }
+
+ function focusFirst() {
+ const cs = cards()
+ if (cs.length > 0) { cs[0].forceActiveFocus(); ensureVisible(cs[0]) }
+ else fl.forceActiveFocus()
+ }
+
+ function ensureVisible(item) { ensureRange(item.y, item.height) }
+
+ // y är relativt kolumnens topp.
+ function ensureRange(y, h) {
+ const m = Theme.dp(20)
+ if (y - m < contentY)
+ contentY = Math.max(0, y - m)
+ else if (y + h + m > contentY + height)
+ contentY = Math.max(0, Math.min(contentHeight - height, y + h + m - height))
+ }
+
+ function move(d) {
+ const cs = cards()
+ let i = cs.findIndex(c => c.activeFocus)
+ if (i < 0) { focusFirst(); return true }
+ const t = cs[i + d]
+ if (!t) return false
+ t.forceActiveFocus()
+ ensureVisible(t)
+ return true
+ }
+
+ Keys.onUpPressed: (event) => event.accepted = move(-1)
+ Keys.onDownPressed: (event) => event.accepted = move(1)
+
+ Behavior on contentY { NumberAnimation { duration: 150; easing.type: Easing.OutCubic } }
+
+ Column {
+ id: col
+ width: fl.width
+ spacing: Theme.dp(12)
+ }
+}
diff --git a/qml/HeroView.qml b/qml/HeroView.qml
new file mode 100644
index 0000000..8051641
--- /dev/null
+++ b/qml/HeroView.qml
@@ -0,0 +1,126 @@
+import QtQuick
+import TvLauncher
+
+// Förhandsvisningen överst på hemskärmen för en app. Används också i
+// dialogen "Utseende och förhandsvisning" (nerskalad).
+//
+// Appens fält som påverkar visningen:
+// heroImage egen bild (sökväg, ~/..., eller http(s)-adress)
+// heroText egen text under namnet (annars adress/kommando)
+// heroShowIcon false = dölj ikonen
+Item {
+ id: hv
+
+ property var app: null
+ // Höjden på själva förhandsvisningen. Bilden fyller hela vyn (även bakom
+ // raderna på hemskärmen), text och ikon placeras inom heroHeight.
+ property real heroHeight: height
+
+ readonly property bool hasIcon: bigIcon.status === Image.Ready && bigIcon.implicitWidth > 1
+ readonly property bool showIcon: app !== null && app.heroShowIcon !== false
+ readonly property bool hasImage: bgImg.status === Image.Ready
+
+ function hostOf(url) { return (url || "").replace(/^[a-z]+:\/\//i, "").replace(/\/.*$/, "") }
+
+ // Egen bild som täcker hela vyn och tonar ut mot vänster och nedåt.
+ Image {
+ id: bgImg
+ anchors.fill: parent
+ source: hv.app && hv.app.heroImage ? Theme.imageUrl(hv.app.heroImage) : ""
+ fillMode: Image.PreserveAspectCrop
+ horizontalAlignment: Image.AlignRight
+ verticalAlignment: Image.AlignTop
+ sourceSize.width: 1920
+ asynchronous: true
+ visible: status === Image.Ready
+
+ Rectangle {
+ anchors.fill: parent
+ gradient: Gradient {
+ orientation: Gradient.Horizontal
+ GradientStop { position: 0.0; color: "#f2000000" }
+ GradientStop { position: 0.3; color: "#b0000000" }
+ GradientStop { position: 0.65; color: "#00000000" }
+ }
+ }
+ Rectangle {
+ anchors.fill: parent
+ gradient: Gradient {
+ GradientStop { position: 0.0; color: "#00000000" }
+ GradientStop { position: Math.min(0.95, hv.heroHeight / Math.max(1, hv.height) * 0.75); color: "#00000000" }
+ GradientStop { position: 1.0; color: "#f0000000" }
+ }
+ }
+ }
+
+ Item {
+ visible: hv.showIcon
+ anchors { right: parent.right; rightMargin: Theme.dp(220) }
+ y: hv.heroHeight / 2 - height / 2 + Theme.dp(50)
+ width: Theme.dp(240); height: width
+ Image {
+ id: bigIcon
+ anchors.fill: parent
+ sourceSize: Qt.size(256, 256)
+ fillMode: Image.PreserveAspectFit
+ asynchronous: true
+ source: hv.app && hv.app.icon ? "image://icon/" + encodeURIComponent(hv.app.icon) : ""
+ visible: hv.hasIcon
+ }
+ Text {
+ anchors.centerIn: parent
+ visible: !hv.hasIcon && hv.app !== null
+ text: hv.app ? (hv.app.name || "").charAt(0).toUpperCase() : ""
+ color: Theme.text
+ opacity: 0.85
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(200)
+ font.weight: Font.Bold
+ }
+ }
+
+ Column {
+ anchors { left: parent.left; leftMargin: Theme.dp(110) }
+ y: hv.heroHeight - height - Theme.dp(50)
+ width: parent.width * 0.5
+ spacing: Theme.dp(14)
+ visible: hv.app !== null
+
+ Text {
+ text: hv.app ? (hv.app.type === "web" ? "WEBBAPP" : "PROGRAM") + " · " + (hv.app.category || "").toUpperCase() : ""
+ color: Theme.accent
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(22)
+ font.weight: Font.Bold
+ font.letterSpacing: Theme.dp(3)
+ }
+ Text {
+ width: parent.width
+ text: hv.app ? (hv.app.name || "") : ""
+ color: Theme.text
+ elide: Text.ElideRight
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(88)
+ font.weight: Font.Bold
+ }
+ Text {
+ width: parent.width
+ text: {
+ const s = hv.app
+ if (!s) return ""
+ if (s.heroText) return s.heroText
+ if (s.chromiumAppId)
+ return (s.url ? hv.hostOf(s.url) + " · " : "") + "installerad i Chromium"
+ if (s.type === "web")
+ return hv.hostOf(s.url) + (s.engine === "chromium" ? " · öppnas i Chromium" : "")
+ return s.command || ""
+ }
+ color: Theme.textDim
+ wrapMode: Text.Wrap
+ maximumLineCount: 3
+ elide: Text.ElideRight
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(28)
+ }
+ }
+}
diff --git a/qml/HomeScreen.qml b/qml/HomeScreen.qml
new file mode 100644
index 0000000..9c91021
--- /dev/null
+++ b/qml/HomeScreen.qml
@@ -0,0 +1,399 @@
+import QtQuick
+import QtQuick.Controls
+import TvLauncher
+
+// Hemskärm: toppfält med klocka och ikonknappar (Bigscreen), en stor
+// header som visar markerad app (Netflix) och rader per kategori under
+// varandra där varje rad skrollar åt höger.
+FocusScope {
+ id: home
+
+ signal launch(var app)
+ signal editApp(var app)
+ signal editAppearance(var app)
+ signal action(string name, Item source)
+
+ property string rememberId: ""
+ property var current: null
+ readonly property int heroHeight: Theme.dp(600)
+ readonly property int rowHeight: Theme.dp(70) + Theme.tile(310)
+
+ function itemsFor(key) {
+ return key === "__recent" ? apps.recent(12) : apps.appsIn(key)
+ }
+
+ // Alla fält som strängar så att ListModel får samma roller överallt.
+ function norm(a) {
+ return { id: a.id || "", name: a.name || "", type: a.type || "", icon: a.icon || "",
+ url: a.url || "", command: a.command || "", engine: a.engine || "",
+ category: a.category || "", userAgent: a.userAgent || "",
+ color: a.color || "", heroImage: a.heroImage || "", heroText: a.heroText || "",
+ heroShowIcon: a.heroShowIcon !== false,
+ chromiumAppId: a.chromiumAppId || "", chromiumProfile: a.chromiumProfile || "",
+ chromiumBin: a.chromiumBin || "", controllerMode: a.controllerMode || "" }
+ }
+
+ function hostOf(url) { return url.replace(/^[a-z]+:\/\//i, "").replace(/\/.*$/, "") }
+
+ function subtitleFor(a) {
+ if (a.type === "web") return hostOf(a.url)
+ const first = (a.command || "").trim().split(/\s+/)[0] || ""
+ return first.split("/").pop()
+ }
+
+ function syncRows() {
+ const r = []
+ if (apps.recent(1).length > 0) r.push({ key: "__recent", label: "Senaste" })
+ for (const c of apps.categories) r.push({ key: c, label: c })
+
+ let same = r.length === rowsModel.count
+ for (let i = 0; same && i < r.length; ++i)
+ same = rowsModel.get(i).key === r[i].key
+ if (same)
+ return
+ const keepKey = rows.currentIndex >= 0 && rows.currentIndex < rowsModel.count
+ ? rowsModel.get(rows.currentIndex).key : ""
+ const hadRowFocus = rows.activeFocus
+ rowsModel.clear()
+ for (const row of r) rowsModel.append(row)
+ const idx = r.findIndex(x => x.key === keepKey)
+ rows.currentIndex = idx >= 0 ? idx : 0
+ Qt.callLater(() => {
+ if (hadRowFocus) focusRows()
+ updateCurrent()
+ })
+ }
+
+ function updateCurrent() {
+ const row = rows.currentItem
+ const l = row ? row.list : null
+ if (l && l.currentIndex >= 0 && l.currentIndex < l.count)
+ home.current = norm(l.model.get(l.currentIndex))
+ else if (!home.current)
+ home.current = null
+ }
+
+ function focusRows() {
+ if (rowsModel.count > 0) rows.forceActiveFocus()
+ else topBar.forceActiveFocus()
+ }
+ function focusTopBar() { topBar.forceActiveFocus() }
+ function restoreFocus() { focusRows(); updateCurrent() }
+
+ Keys.onUpPressed: focusTopBar()
+ Keys.onPressed: (event) => {
+ if (event.key === Qt.Key_PageUp) { rows.decrementCurrentIndex(); focusRows(); event.accepted = true }
+ else if (event.key === Qt.Key_PageDown) { rows.incrementCurrentIndex(); focusRows(); event.accepted = true }
+ }
+
+ ListModel { id: rowsModel }
+
+ Connections {
+ target: apps
+ function onChanged() { home.syncRows() }
+ }
+ Component.onCompleted: {
+ syncRows()
+ Qt.callLater(focusRows)
+ }
+
+ // Mörkare nertill så att raderna syns mot bakgrundsbilden.
+ Rectangle {
+ anchors.fill: parent
+ gradient: Gradient {
+ GradientStop { position: 0.0; color: "#00000000" }
+ GradientStop { position: 0.45; color: "#30000000" }
+ GradientStop { position: 1.0; color: "#c0000000" }
+ }
+ }
+
+ // ---------------------------------------------------------------- hero
+ Item {
+ id: hero
+ anchors.fill: parent
+
+ property var shown: null
+
+ Connections {
+ target: home
+ function onCurrentChanged() {
+ const a = hero.shown, b = home.current
+ if (!a || !b || a.id !== b.id || a.heroImage !== b.heroImage) swap.restart()
+ else hero.shown = b
+ }
+ }
+ SequentialAnimation {
+ id: swap
+ NumberAnimation { target: heroContent; property: "opacity"; to: 0; duration: 90 }
+ ScriptAction { script: hero.shown = home.current }
+ NumberAnimation { target: heroContent; property: "opacity"; to: 1; duration: 220; easing.type: Easing.OutCubic }
+ }
+
+ // Mörkt från vänster bakom texten (hela höjden så att ingen kant syns).
+ Rectangle {
+ x: 0; y: 0
+ width: parent.width
+ height: home.height
+ gradient: Gradient {
+ orientation: Gradient.Horizontal
+ GradientStop { position: 0.0; color: "#b0000000" }
+ GradientStop { position: 0.45; color: "#60000000" }
+ GradientStop { position: 0.75; color: "#00000000" }
+ }
+ }
+
+ HeroView {
+ id: heroContent
+ anchors.fill: parent
+ heroHeight: home.heroHeight
+ app: hero.shown
+ }
+ }
+
+ // ------------------------------------------------------------ toppfält
+ component TopButton: Item {
+ id: tb
+ property string icon
+ property string label
+ signal clicked()
+
+ width: Theme.dp(82); height: width
+ Keys.onReturnPressed: tb.clicked()
+ Keys.onEnterPressed: tb.clicked()
+
+ Rectangle {
+ anchors.fill: parent
+ radius: width / 2
+ color: tb.activeFocus ? "#40ffffff" : "transparent"
+ border.width: tb.activeFocus ? Theme.dp(3) : 0
+ border.color: Theme.accent
+ }
+ Icon {
+ anchors.centerIn: parent
+ width: Theme.dp(42); height: width
+ name: tb.icon
+ }
+ Text {
+ visible: tb.activeFocus
+ anchors { top: parent.bottom; topMargin: Theme.dp(8); horizontalCenter: parent.horizontalCenter }
+ text: tb.label
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(20)
+ }
+ MouseArea {
+ anchors.fill: parent
+ onClicked: { tb.forceActiveFocus(); tb.clicked() }
+ }
+ }
+
+ FocusScope {
+ id: topBar
+ anchors { left: parent.left; right: parent.right; top: parent.top }
+ height: Theme.dp(190)
+
+ property int idx: 0
+ readonly property var buttons: [
+ { icon: "search", label: "Sök", action: "search" },
+ { icon: "add", label: "Lägg till", action: "add" },
+ { icon: "settings", label: "Inställningar", action: "settings" },
+ { icon: "volume", label: "Ljud", action: "audio" },
+ { icon: "wifi", label: "Wi‑Fi", action: "wifi" },
+ { icon: "bluetooth", label: "Bluetooth", action: "bluetooth" },
+ { icon: "power", label: "Ström", action: "power" }
+ ]
+
+ Keys.onLeftPressed: idx = Math.max(0, idx - 1)
+ Keys.onRightPressed: idx = Math.min(buttons.length - 1, idx + 1)
+ Keys.onDownPressed: home.focusRows()
+ Keys.onUpPressed: {}
+
+ Row {
+ anchors { left: parent.left; leftMargin: Theme.dp(110); verticalCenter: parent.verticalCenter }
+ spacing: Theme.dp(30)
+ Text {
+ id: clock
+ anchors.baseline: date.baseline
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(64)
+ font.weight: Font.Light
+ }
+ Text {
+ id: date
+ color: Theme.text
+ opacity: 0.85
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(34)
+ }
+ Timer {
+ interval: 5000; running: true; repeat: true; triggeredOnStart: true
+ onTriggered: {
+ const now = new Date()
+ clock.text = Qt.formatTime(now, "HH:mm")
+ const d = now.toLocaleDateString(Qt.locale("sv_SE"), "dddd d MMMM yyyy")
+ date.text = d.charAt(0).toUpperCase() + d.slice(1)
+ }
+ }
+ }
+
+ Row {
+ anchors { right: parent.right; rightMargin: Theme.dp(100); verticalCenter: parent.verticalCenter }
+ spacing: Theme.dp(14)
+
+ Icon {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: input.connected
+ width: Theme.dp(40); height: width
+ opacity: 0.6
+ name: "gamepad"
+ }
+ Item { width: Theme.dp(20); height: 1; visible: input.connected }
+
+ Repeater {
+ model: topBar.buttons
+ delegate: TopButton {
+ id: topButton
+ required property var modelData
+ required property int index
+ focus: index === topBar.idx
+ icon: modelData.icon
+ label: modelData.label
+ onClicked: {
+ topBar.idx = index
+ home.action(modelData.action, topButton)
+ }
+ }
+ }
+ }
+ }
+
+ // --------------------------------------------------------- app-raderna
+ ListView {
+ id: rows
+ anchors { left: parent.left; right: parent.right; top: parent.top; topMargin: home.heroHeight; bottom: parent.bottom }
+ focus: true
+ clip: true
+ model: rowsModel
+ cacheBuffer: 10000
+ spacing: 0
+ highlightRangeMode: ListView.StrictlyEnforceRange
+ preferredHighlightBegin: Theme.dp(10)
+ preferredHighlightEnd: Theme.dp(10) + home.rowHeight
+ highlightMoveDuration: 280
+ boundsBehavior: Flickable.StopAtBounds
+ onCurrentIndexChanged: Qt.callLater(home.updateCurrent)
+
+ delegate: FocusScope {
+ id: row
+ required property string key
+ required property string label
+ required property int index
+ property alias list: list
+
+ width: rows.width
+ height: home.rowHeight
+ focus: ListView.isCurrentItem
+ opacity: ListView.isCurrentItem || !rows.activeFocus ? 1 : 0.7
+ Behavior on opacity { NumberAnimation { duration: 200 } }
+
+ Text {
+ id: title
+ x: Theme.dp(110)
+ text: row.label
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(44)
+ font.weight: Font.Light
+ }
+
+ ListView {
+ id: list
+ anchors { left: parent.left; right: parent.right; top: title.bottom; topMargin: Theme.dp(14) }
+ height: Theme.tile(310)
+ orientation: ListView.Horizontal
+ focus: true
+ spacing: Theme.dp(28)
+ leftMargin: Theme.dp(110)
+ rightMargin: Theme.dp(110)
+ clip: false
+ highlightRangeMode: ListView.ApplyRange
+ preferredHighlightBegin: Theme.dp(110)
+ preferredHighlightEnd: width - Theme.tile(460)
+ highlightMoveDuration: 220
+ boundsBehavior: Flickable.StopAtBounds
+ model: ListModel { id: lm }
+
+ onCurrentIndexChanged: if (row.index === rows.currentIndex) home.updateCurrent()
+
+ // Uppdatera på plats så att markeringen inte hoppar.
+ function sync() {
+ const items = home.itemsFor(row.key).map(home.norm)
+ let same = items.length === lm.count
+ for (let i = 0; same && i < items.length; ++i)
+ same = lm.get(i).id === items[i].id
+ if (same) {
+ for (let i = 0; i < items.length; ++i) lm.set(i, items[i])
+ } else {
+ const oldIndex = currentIndex
+ const oldId = oldIndex >= 0 && oldIndex < lm.count ? lm.get(oldIndex).id : ""
+ lm.clear()
+ for (const it of items) lm.append(it)
+ let idx = items.findIndex(a => a.id === home.rememberId)
+ if (idx < 0) idx = items.findIndex(a => a.id === oldId)
+ if (idx < 0) idx = Math.min(Math.max(oldIndex, 0), items.length - 1)
+ currentIndex = idx
+ }
+ if (row.index === rows.currentIndex) home.updateCurrent()
+ }
+
+ delegate: AppTile {
+ id: tile
+ required property var model
+ required property int index
+ focus: ListView.isCurrentItem
+ name: model.name
+ subtitle: home.subtitleFor(model)
+ icon: model.icon
+ customColor: model.color
+ isWeb: model.type === "web"
+
+ onActivated: {
+ const item = home.norm(model)
+ home.rememberId = item.id
+ home.launch(item)
+ }
+ onMenuRequested: {
+ const item = home.norm(model)
+ home.rememberId = item.id
+ tileMenu.app = item
+ tileMenu.popup(tile, tile.width / 2, Theme.dp(60))
+ }
+ onHovered: {
+ rows.currentIndex = row.index
+ list.currentIndex = index
+ rows.forceActiveFocus()
+ }
+ }
+ }
+
+ Connections {
+ target: apps
+ function onChanged() { list.sync() }
+ }
+ Component.onCompleted: list.sync()
+ }
+ }
+
+ TvMenu {
+ id: tileMenu
+ property var app: ({})
+
+ Action { text: "Starta"; onTriggered: home.launch(tileMenu.app) }
+ Action { text: "Utseende och förhandsvisning"; onTriggered: home.editAppearance(tileMenu.app) }
+ Action { text: "Redigera"; onTriggered: home.editApp(tileMenu.app) }
+ Action { text: "Flytta vänster"; onTriggered: apps.move(tileMenu.app.id, -1) }
+ Action { text: "Flytta höger"; onTriggered: apps.move(tileMenu.app.id, 1) }
+ Action { text: "Ta bort"; onTriggered: apps.remove(tileMenu.app.id) }
+ }
+}
diff --git a/qml/Icon.qml b/qml/Icon.qml
new file mode 100644
index 0000000..2de8746
--- /dev/null
+++ b/qml/Icon.qml
@@ -0,0 +1,10 @@
+import QtQuick
+
+// Linjeikon från qml/icons/<name>.svg
+Image {
+ property string name
+ source: name !== "" ? Qt.resolvedUrl("icons/" + name + ".svg") : ""
+ sourceSize: Qt.size(width * 2, height * 2)
+ fillMode: Image.PreserveAspectFit
+ smooth: true
+}
diff --git a/qml/ImagePicker.qml b/qml/ImagePicker.qml
new file mode 100644
index 0000000..4e1d8dc
--- /dev/null
+++ b/qml/ImagePicker.qml
@@ -0,0 +1,104 @@
+import QtQuick
+import QtQuick.Controls
+import TvLauncher
+
+// Välj en bild bland ~/Bilder, ~/Pictures och systemets bakgrundsmappar.
+Popup {
+ id: picker
+
+ signal picked(string path)
+
+ property var images: []
+
+ parent: Overlay.overlay
+ anchors.centerIn: parent
+ width: parent.width - Theme.dp(160)
+ height: parent.height - Theme.dp(140)
+ modal: true
+ focus: true
+ padding: Theme.dp(36)
+
+ background: Rectangle { color: Theme.alpha(Theme.surface, 0.97); radius: Theme.r(18); border.color: Theme.borderSoft }
+ Overlay.modal: Rectangle { color: Theme.scrim }
+
+ onAboutToShow: images = prefs.findWallpapers()
+ onOpened: grid.forceActiveFocus()
+
+ contentItem: Item {
+ Text {
+ id: title
+ text: "Välj bild"
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(36)
+ }
+ Text {
+ anchors { left: title.right; leftMargin: Theme.dp(24); baseline: title.baseline }
+ text: "Bilder från ~/Bilder och ~/Pictures"
+ color: Theme.textDim
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(22)
+ }
+
+ Text {
+ anchors.centerIn: parent
+ visible: picker.images.length === 0
+ width: parent.width * 0.7
+ horizontalAlignment: Text.AlignHCenter
+ wrapMode: Text.Wrap
+ text: "Inga bilder hittades.\nLägg bilder (jpg/png) i ~/Bilder, eller skriv en sökväg eller webbadress i fältet."
+ color: Theme.textDim
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(26)
+ }
+
+ GridView {
+ id: grid
+ anchors { left: parent.left; right: parent.right; top: title.bottom; topMargin: Theme.dp(24); bottom: parent.bottom }
+ clip: true
+ model: picker.images
+ readonly property int columns: 4
+ cellWidth: Math.floor(width / columns)
+ cellHeight: Math.round(cellWidth * 0.62)
+ keyNavigationWraps: false
+ highlightMoveDuration: 120
+
+ delegate: Item {
+ id: cell
+ required property string modelData
+ required property int index
+ width: grid.cellWidth
+ height: grid.cellHeight
+ readonly property bool current: GridView.isCurrentItem && grid.activeFocus
+
+ function choose() { picker.close(); picker.picked(modelData) }
+ Keys.onReturnPressed: choose()
+ Keys.onEnterPressed: choose()
+
+ Rectangle {
+ anchors.fill: parent
+ anchors.margins: Theme.dp(8)
+ radius: Theme.r(10)
+ color: Theme.card
+ border.width: cell.current ? Theme.dp(4) : 0
+ border.color: Theme.accent
+ clip: true
+ Image {
+ anchors.fill: parent
+ anchors.margins: cell.current ? Theme.dp(4) : 0
+ source: "file://" + cell.modelData
+ sourceSize.width: 400
+ fillMode: Image.PreserveAspectCrop
+ asynchronous: true
+ }
+ }
+ MouseArea {
+ anchors.fill: parent
+ hoverEnabled: true
+ onEntered: { grid.currentIndex = cell.index; grid.forceActiveFocus() }
+ onClicked: cell.choose()
+ }
+ }
+ }
+ }
+}
diff --git a/qml/InstalledPicker.qml b/qml/InstalledPicker.qml
new file mode 100644
index 0000000..64174fd
--- /dev/null
+++ b/qml/InstalledPicker.qml
@@ -0,0 +1,133 @@
+import QtQuick
+import QtQuick.Controls
+import TvLauncher
+
+// Lista över installerade program (.desktop-filer). Välj ett för att
+// lägga till det på hemskärmen.
+Popup {
+ id: picker
+
+ signal picked(var app)
+
+ property var all: []
+ property var filtered: {
+ const q = search.text.trim().toLowerCase()
+ return q === "" ? all : all.filter(a => a.name.toLowerCase().indexOf(q) >= 0)
+ }
+
+ parent: Overlay.overlay
+ anchors.centerIn: parent
+ width: Math.min(parent.width - Theme.dp(120), Theme.dp(1100))
+ height: parent.height - Theme.dp(120)
+ modal: true
+ focus: true
+ padding: Theme.dp(40)
+
+ background: Rectangle { color: Theme.bg; radius: Theme.r(18); border.color: Theme.borderSoft }
+ Overlay.modal: Rectangle { color: Theme.scrim }
+
+ onAboutToShow: {
+ search.text = ""
+ all = scanner.scan()
+ }
+ onOpened: list.forceActiveFocus()
+
+ contentItem: Item {
+ Text {
+ id: title
+ text: "Installerade program"
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(36)
+ }
+
+ TextField {
+ id: search
+ anchors { left: parent.left; right: parent.right; top: title.bottom; topMargin: Theme.dp(20) }
+ height: Theme.dp(60)
+ placeholderText: "Sök ..."
+ placeholderTextColor: Theme.placeholder
+ color: Theme.text
+ font.pixelSize: Theme.dp(24)
+ leftPadding: Theme.dp(16)
+ KeyNavigation.down: list
+ background: Rectangle {
+ radius: Theme.r(8)
+ color: search.activeFocus ? Theme.surfaceHi : Theme.surface
+ border.width: search.activeFocus ? Theme.dp(3) : Theme.dp(1)
+ border.color: search.activeFocus ? Theme.accent : Theme.border
+ }
+ }
+
+ ListView {
+ id: list
+ anchors { left: parent.left; right: parent.right; top: search.bottom; bottom: parent.bottom; topMargin: Theme.dp(20) }
+ clip: true
+ model: picker.filtered
+ spacing: Theme.dp(6)
+ highlightMoveDuration: 120
+ // Börja skriva för att söka.
+ Keys.onPressed: (event) => {
+ if (event.text.length === 1 && event.text.trim() !== "" && !(event.modifiers & Qt.ControlModifier)) {
+ search.forceActiveFocus()
+ search.text += event.text
+ event.accepted = true
+ } else if (event.key === Qt.Key_Up && currentIndex === 0) {
+ search.forceActiveFocus()
+ event.accepted = true
+ }
+ }
+
+ delegate: Rectangle {
+ id: entry
+ required property var modelData
+ required property int index
+ width: ListView.view.width
+ height: Theme.dp(80)
+ radius: Theme.r(10)
+ readonly property bool current: ListView.isCurrentItem && list.activeFocus
+ color: current ? Theme.surfaceHi : "transparent"
+ border.width: current ? Theme.dp(3) : 0
+ border.color: Theme.accent
+
+ function choose() { picker.close(); picker.picked(modelData) }
+ Keys.onReturnPressed: choose()
+ Keys.onEnterPressed: choose()
+
+ Image {
+ id: icon
+ anchors { left: parent.left; leftMargin: Theme.dp(16); verticalCenter: parent.verticalCenter }
+ width: Theme.dp(52); height: width
+ sourceSize: Qt.size(128, 128)
+ asynchronous: true
+ source: entry.modelData.icon ? "image://icon/" + encodeURIComponent(entry.modelData.icon) : ""
+ }
+ Column {
+ anchors { left: icon.right; leftMargin: Theme.dp(20); right: parent.right; rightMargin: Theme.dp(16); verticalCenter: parent.verticalCenter }
+ Text {
+ width: parent.width
+ text: entry.modelData.name
+ color: Theme.text
+ elide: Text.ElideRight
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(26)
+ }
+ Text {
+ width: parent.width
+ text: entry.modelData.command
+ color: Theme.textDim
+ elide: Text.ElideRight
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(18)
+ }
+ }
+ MouseArea {
+ anchors.fill: parent
+ hoverEnabled: true
+ onEntered: { list.currentIndex = entry.index; list.forceActiveFocus() }
+ onClicked: entry.choose()
+ }
+ }
+ }
+ }
+}
diff --git a/qml/Main.qml b/qml/Main.qml
new file mode 100644
index 0000000..a25aa44
--- /dev/null
+++ b/qml/Main.qml
@@ -0,0 +1,363 @@
+import QtQuick
+import QtQuick.Controls
+import QtQuick.Window
+import TvLauncher
+
+ApplicationWindow {
+ id: root
+
+ property var webApp: ({})
+
+ visible: true
+ width: 1280
+ height: 720
+ visibility: windowedMode ? Window.Windowed : Window.FullScreen
+ title: "TV"
+ color: Theme.bg
+ font.family: Theme.fontFamily
+
+ Binding { target: Theme; property: "s"; value: root.height / 1080 }
+ // Temat följer de sparade inställningarna.
+ Binding { target: Theme; property: "preset"; value: prefs.themePreset }
+ Binding { target: Theme; property: "accent"; value: prefs.accent }
+ Binding { target: Theme; property: "tileScale"; value: Number(prefs.tileScale) }
+ Binding { target: Theme; property: "radiusScale"; value: Number(prefs.radiusScale) }
+ Binding { target: Theme; property: "tileMode"; value: prefs.tileMode }
+ Binding { target: Theme; property: "tileOpacity"; value: Number(prefs.tileOpacity) }
+ Binding { target: Theme; property: "homePath"; value: prefs.homePath }
+ Binding { target: input; property: "webMode"; value: webLoader.active }
+
+ // Spel och emulatorer läser kontrollen själva; allt annat får mus och tangentbord.
+ function controllerModeFor(app) {
+ const m = app.controllerMode || "auto"
+ if (m !== "auto") return m
+ const games = /retroarch|emulationstation|es-de|dolphin|pcsx2|duckstation|ppsspp|mgba|mupen|snes9x|flycast|mame|ryujinx|cemu|rpcs3|xemu|steam|lutris|heroic|supertux|0ad|minetest|luanti/i
+ return app.category === "Spel" || games.test(app.command || "") ? "gamepad" : "keyboard"
+ }
+
+ function launch(app) {
+ if (app.id)
+ apps.markUsed(app.id)
+ input.externalMode = controllerModeFor(app)
+ if (app.chromiumAppId) {
+ // Webbapp installerad i Chromium ("Installera sidan som app").
+ launcher.launchChromiumApp(app.name, app.chromiumBin || "", app.chromiumProfile || "", app.chromiumAppId)
+ } else if (app.type === "web") {
+ if (app.engine === "chromium") {
+ launcher.launchChromium(app.name, app.id, app.url, app.userAgent || "")
+ } else {
+ root.webApp = app
+ webLoader.active = true
+ }
+ } else {
+ launcher.launchCommand(app.name, app.command)
+ }
+ }
+
+ function closeWeb() {
+ if (!webLoader.active)
+ return
+ webLoader.active = false
+ refocus()
+ }
+
+ function openSettings(page, focusContent) {
+ settingsLoader.active = true
+ settingsLoader.item.openPage(page, focusContent)
+ }
+
+ function closeSettings() {
+ if (!settingsLoader.active)
+ return
+ settingsLoader.active = false
+ refocus()
+ }
+
+ // Ger fokus till den vy som syns.
+ function refocus() {
+ if (webLoader.active) webLoader.item.forceActiveFocus()
+ else if (settingsLoader.active) settingsLoader.item.focusContentArea()
+ else { home.forceActiveFocus(); Qt.callLater(home.restoreFocus) }
+ }
+
+ // Om fokus försvann (t.ex. för att rutan som hade fokus byggdes om).
+ function refocusIfLost() {
+ const f = root.activeFocusItem
+ if (!f || f === root.contentItem || !f.visible)
+ refocus()
+ }
+
+ // ---------------------------------------------------- skärmtangentbord
+ property Item oskTarget: null
+ property string oskMode: "" // "field" | "keys" | "external"
+
+ function openOsk() {
+ if (launcher.running) {
+ // Ett externt program syns: eget fönster ovanpå, texten skrivs in efteråt.
+ oskMode = "external"
+ extOsk.reset("", "")
+ input.oskActive = true
+ input.setKeyWindow(oskWindow)
+ oskWindow.showFullScreen()
+ oskWindow.requestActivate()
+ extOsk.forceActiveFocus()
+ return
+ }
+ const t = root.activeFocusItem
+ const isField = t !== null && ("cursorPosition" in t) && ("text" in t)
+ oskTarget = t
+ oskMode = isField ? "field" : "keys"
+ inOsk.reset(isField ? t.text : "", isField && t.placeholderText ? t.placeholderText : "")
+ input.oskActive = true
+ oskPopup.open()
+ }
+
+ function finishOsk(text, enter, ok) {
+ if (oskMode === "external") {
+ oskWindow.hide()
+ input.setKeyWindow(null)
+ input.oskActive = false
+ if (ok) { externalType.text = text; externalType.enter = enter; externalType.restart() }
+ return
+ }
+ oskPopup.close()
+ input.oskActive = false
+ const t = oskTarget
+ if (!ok || !t) return
+ t.forceActiveFocus()
+ if (oskMode === "field") {
+ t.text = text
+ if (enter && t.accepted) t.accepted()
+ } else {
+ Qt.callLater(() => input.typeIntoFocus(text, enter))
+ }
+ }
+
+ // Vänta tills programmet under fått tillbaka fokus innan texten skrivs.
+ Timer {
+ id: externalType
+ property string text
+ property bool enter
+ interval: 400
+ onTriggered: input.typeExternal(text, enter)
+ }
+
+ Popup {
+ id: oskPopup
+ parent: Overlay.overlay
+ x: (parent.width - width) / 2
+ y: parent.height - height - Theme.dp(20)
+ width: Math.min(parent.width - Theme.dp(40), Theme.dp(1700))
+ height: Math.min(parent.height * 0.62, Theme.dp(640))
+ modal: true
+ focus: true
+ padding: 0
+ closePolicy: Popup.NoAutoClose
+ background: Item {}
+ Overlay.modal: Rectangle { color: "#70000000" }
+ onOpened: inOsk.forceActiveFocus()
+
+ contentItem: OnScreenKeyboard {
+ id: inOsk
+ onAccepted: (text, enter) => root.finishOsk(text, enter, true)
+ onCancelled: root.finishOsk("", false, false)
+ }
+ }
+
+ Window {
+ id: oskWindow
+ visible: false
+ title: "Tangentbord"
+ color: "transparent"
+
+ Rectangle { anchors.fill: parent; color: "#66000000" }
+ OnScreenKeyboard {
+ id: extOsk
+ anchors { left: parent.left; right: parent.right; bottom: parent.bottom; margins: Theme.dp(20) }
+ height: Math.min(parent.height * 0.62, Theme.dp(640))
+ focus: true
+ onAccepted: (text, enter) => root.finishOsk(text, enter, true)
+ onCancelled: root.finishOsk("", false, false)
+ }
+ }
+
+ Connections {
+ target: input
+ function onOskRequested() { root.openOsk() }
+ }
+
+ function goHome() {
+ if (oskPopup.opened || oskWindow.visible)
+ finishOsk("", false, false)
+ editor.close()
+ appearance.close()
+ picker.close()
+ search.close()
+ powerMenu.dismiss()
+ addMenu.dismiss()
+ webLoader.active = false
+ settingsLoader.active = false
+ home.forceActiveFocus()
+ Qt.callLater(home.restoreFocus)
+ }
+
+ Backdrop { anchors.fill: parent }
+
+ HomeScreen {
+ id: home
+ anchors.fill: parent
+ focus: true
+ visible: !webLoader.active && !settingsLoader.active
+
+ onLaunch: (app) => root.launch(app)
+ onEditApp: (app) => editor.openFor(app)
+ onEditAppearance: (app) => appearance.openFor(app)
+ onAction: (name, source) => {
+ switch (name) {
+ case "search": search.open(); break
+ case "add": addMenu.popup(source, source.width / 2 - addMenu.width / 2, source.height + Theme.dp(40)); break
+ case "settings": root.openSettings("apps", false); break
+ case "audio":
+ case "wifi":
+ case "bluetooth": root.openSettings(name, true); break
+ case "power": powerMenu.popup(source, source.width - powerMenu.width, source.height + Theme.dp(40)); break
+ }
+ }
+ }
+
+ Loader {
+ id: settingsLoader
+ anchors.fill: parent
+ active: false
+ focus: active
+ sourceComponent: Component {
+ SettingsView {
+ onCloseRequested: root.closeSettings()
+ onEditApp: (app) => editor.openFor(app)
+ onAddApp: (type) => editor.openFor({ type: type, category: type === "web" ? "Webb" : "Program" })
+ onPickInstalled: picker.open()
+ }
+ }
+ }
+
+ Loader {
+ id: webLoader
+ anchors.fill: parent
+ active: false
+ focus: active
+ sourceComponent: Component {
+ WebAppView {
+ app: root.webApp
+ onCloseRequested: root.closeWeb()
+ }
+ }
+ onLoaded: item.forceActiveFocus()
+ }
+
+ // Visas medan ett externt program startar eller om det inte öppnar något fönster.
+ Rectangle {
+ anchors.fill: parent
+ visible: launcher.running
+ color: Theme.alpha(Theme.bg, 0.94)
+ z: 500
+ MouseArea { anchors.fill: parent }
+
+ Column {
+ anchors.centerIn: parent
+ spacing: Theme.dp(30)
+ Text {
+ anchors.horizontalCenter: parent.horizontalCenter
+ text: "Startar " + launcher.runningName + " ..."
+ color: Theme.text
+ font.pixelSize: Theme.dp(40)
+ font.weight: Font.Light
+ }
+ Text {
+ anchors.horizontalCenter: parent.horizontalCenter
+ text: "Håll Home-knappen för att stänga"
+ color: Theme.textDim
+ font.pixelSize: Theme.dp(24)
+ }
+ TvButton {
+ anchors.horizontalCenter: parent.horizontalCenter
+ text: "Stäng"
+ onClicked: launcher.stop()
+ }
+ }
+ }
+
+ AppEditor {
+ id: editor
+ onClosed: Qt.callLater(root.refocusIfLost)
+ }
+
+ AppearanceDialog {
+ id: appearance
+ onClosed: Qt.callLater(root.refocusIfLost)
+ }
+
+ InstalledPicker {
+ id: picker
+ onPicked: (app) => editor.openFor(app)
+ onClosed: Qt.callLater(root.refocusIfLost)
+ }
+
+ SearchPopup {
+ id: search
+ onChosen: (app) => root.launch(app)
+ onClosed: Qt.callLater(root.refocusIfLost)
+ }
+
+ TvMenu {
+ id: addMenu
+ Action { text: "Lägg till program"; onTriggered: editor.openFor({ type: "app", category: "Program" }) }
+ Action { text: "Lägg till webbapp"; onTriggered: editor.openFor({ type: "web", category: "Webb" }) }
+ Action { text: "Från installerade"; onTriggered: picker.open() }
+ }
+
+ TvMenu {
+ id: powerMenu
+ Action { text: "Stäng av"; onTriggered: launcher.powerOff() }
+ Action { text: "Starta om"; onTriggered: launcher.reboot() }
+ Action { text: "Starta om launchern"; onTriggered: Qt.exit(1) }
+ Action { text: "Avbryt" }
+ }
+
+ Toast { id: toast }
+
+ Connections {
+ target: launcher
+ function onLaunchFailed(name, error) { toast.show(name + ": " + error) }
+ }
+
+ Connections {
+ target: input
+ function onVirtualInputMissing() {
+ toast.show("Kontrollen kan inte styra mus och tangentbord ännu. Kör en gång i en terminal:\n"
+ + "sudo ~/tv-launcher/scripts/setup-uinput.sh")
+ }
+ }
+
+ Connections {
+ target: chromiumApps
+ function onAppsAdded(names) {
+ toast.show((names.length === 1 ? "Ny webbapp från Chromium: " : "Nya webbappar från Chromium: ")
+ + names.join(", "), false)
+ }
+ }
+
+ Connections {
+ target: input
+ function onBackPressed() {
+ if (webLoader.item)
+ webLoader.item.back()
+ }
+ function onHomePressed() { root.goHome() }
+ function onHomeLongPressed() {
+ if (launcher.running)
+ launcher.stop()
+ else
+ root.goHome()
+ }
+ }
+}
diff --git a/qml/OnScreenKeyboard.qml b/qml/OnScreenKeyboard.qml
new file mode 100644
index 0000000..94cc781
--- /dev/null
+++ b/qml/OnScreenKeyboard.qml
@@ -0,0 +1,235 @@
+import QtQuick
+import TvLauncher
+
+// Skärmtangentbord som styrs med handkontrollen (eller fjärr/piltangenter).
+// Man skriver i en egen rad överst och trycker Klar; texten skickas sedan
+// dit den ska (fältet i launchern, webbappen eller det externa programmet).
+//
+// D-pad flytta A skriv tecknet B avbryt
+// X radera RB mellanslag Y/Start klar
+FocusScope {
+ id: osk
+
+ property string text: ""
+ property string title: ""
+ property bool shift: false
+ property bool symbols: false
+ property int row: 1
+ property int col: 0
+
+ signal accepted(string text, bool enter)
+ signal cancelled()
+
+ function reset(initial, heading) {
+ text = initial || ""
+ title = heading || ""
+ shift = false
+ symbols = false
+ row = 1
+ col = 0
+ }
+
+ // Tangent: { l: etikett, v: värde, w: bredd, a: åtgärd }
+ function k(l, w, a) { return { l: l, v: l, w: w || 1, a: a || "" } }
+ readonly property var letters: [
+ ["1","2","3","4","5","6","7","8","9","0","+"].map(c => k(c)).concat([k("⌫", 1, "back")]),
+ ["q","w","e","r","t","y","u","i","o","p","å"].map(c => k(c)).concat([k("?")]),
+ ["a","s","d","f","g","h","j","k","l","ö","ä"].map(c => k(c)).concat([k("'")]),
+ [k("⇧", 1.5, "shift")].concat(["z","x","c","v","b","n","m",",",".","-"].map(c => k(c))).concat([k("@")]),
+ [k("?123", 1.5, "symbols"), k("mellanslag", 4.5, "space"), k(".com", 1.5, "text"),
+ k("Klar", 1.5, "done"), k("Klar ↵", 1.5, "enter")]
+ ]
+ readonly property var symbolRows: [
+ ["1","2","3","4","5","6","7","8","9","0","="].map(c => k(c)).concat([k("⌫", 1, "back")]),
+ ["!","\"","#","%","&","/","(",")","?","+","*"].map(c => k(c)),
+ ["@","$","£","€","{","}","[","]","<",">","|"].map(c => k(c)),
+ [k("\\"), k("_"), k(";"), k(":"), k("'"), k(","), k("."), k("-")],
+ [k("ABC", 1.5, "symbols"), k("mellanslag", 4.5, "space"), k("www.", 1.5, "text"),
+ k("Klar", 1.5, "done"), k("Klar ↵", 1.5, "enter")]
+ ]
+ readonly property var rows: symbols ? symbolRows : letters
+
+ function labelFor(key) {
+ if (key.a === "" && shift && !symbols) return key.l.toUpperCase()
+ return key.l
+ }
+
+ function press(key) {
+ switch (key.a) {
+ case "back": text = text.slice(0, -1); break
+ case "shift": shift = !shift; break
+ case "symbols": symbols = !symbols; clampCol(); break
+ case "space": text += " "; break
+ case "done": osk.accepted(text, false); break
+ case "enter": osk.accepted(text, true); break
+ case "text": text += key.v; break
+ default:
+ text += shift && !symbols ? key.v.toUpperCase() : key.v
+ shift = false
+ }
+ }
+
+ function centerOf(r, c) {
+ let x = 0
+ for (let i = 0; i < c; ++i) x += rows[r][i].w
+ return x + rows[r][c].w / 2
+ }
+ function clampCol() { col = Math.min(col, rows[row].length - 1) }
+ function moveRow(d) {
+ const r = row + d
+ if (r < 0 || r >= rows.length) return
+ const cx = centerOf(row, col)
+ let best = 0, bestDist = 1e9
+ for (let c = 0; c < rows[r].length; ++c) {
+ const dist = Math.abs(centerOf(r, c) - cx)
+ if (dist < bestDist) { bestDist = dist; best = c }
+ }
+ row = r
+ col = best
+ }
+
+ Keys.onPressed: (event) => {
+ switch (event.key) {
+ case Qt.Key_Left: col = Math.max(0, col - 1); break
+ case Qt.Key_Right: col = Math.min(rows[row].length - 1, col + 1); break
+ case Qt.Key_Up: moveRow(-1); break
+ case Qt.Key_Down: moveRow(1); break
+ case Qt.Key_Return:
+ case Qt.Key_Enter: press(rows[row][col]); break
+ case Qt.Key_Escape: osk.cancelled(); break
+ case Qt.Key_Menu: osk.accepted(text, false); break
+ case Qt.Key_Backspace:
+ case Qt.Key_PageUp: text = text.slice(0, -1); break
+ case Qt.Key_PageDown: text += " "; break
+ default:
+ // Riktigt tangentbord: skriv direkt.
+ if (event.text.length === 1 && event.text >= " ") text += event.text
+ else return
+ }
+ event.accepted = true
+ }
+
+ Rectangle {
+ anchors.fill: parent
+ color: Theme.alpha(Theme.bg, 0.97)
+ radius: Theme.r(18)
+ border.color: Theme.borderSoft
+ }
+
+ Column {
+ anchors { fill: parent; margins: Theme.dp(28) }
+ spacing: Theme.dp(18)
+
+ // Textraden
+ Rectangle {
+ width: parent.width
+ height: Theme.dp(76)
+ radius: Theme.r(10)
+ color: Theme.surface
+ border.color: Theme.accent
+ border.width: Theme.dp(2)
+ clip: true
+
+ Text {
+ id: label
+ visible: osk.title !== ""
+ anchors { left: parent.left; leftMargin: Theme.dp(20); verticalCenter: parent.verticalCenter }
+ text: osk.title
+ color: Theme.textDim
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(24)
+ }
+ Item {
+ anchors { left: label.visible ? label.right : parent.left; leftMargin: Theme.dp(20)
+ right: parent.right; rightMargin: Theme.dp(20); top: parent.top; bottom: parent.bottom }
+ clip: true
+ Text {
+ id: typed
+ anchors.verticalCenter: parent.verticalCenter
+ x: Math.min(0, parent.width - contentWidth - caret.width - Theme.dp(4))
+ text: osk.text
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(32)
+ }
+ Rectangle {
+ id: caret
+ x: typed.x + typed.contentWidth + Theme.dp(2)
+ anchors.verticalCenter: parent.verticalCenter
+ width: Theme.dp(3); height: Theme.dp(40)
+ color: Theme.accent
+ SequentialAnimation on opacity {
+ loops: Animation.Infinite
+ NumberAnimation { to: 0; duration: 500 }
+ NumberAnimation { to: 1; duration: 500 }
+ }
+ }
+ }
+ }
+
+ // Tangenterna
+ Column {
+ id: keys
+ anchors.horizontalCenter: parent.horizontalCenter
+ spacing: Theme.dp(10)
+ readonly property real unit: Math.min((osk.width - Theme.dp(56)) / 12, Theme.dp(130))
+
+ Repeater {
+ model: osk.rows.length
+ delegate: Row {
+ id: keyRow
+ required property int index
+ readonly property int r: index
+ anchors.horizontalCenter: parent.horizontalCenter
+ spacing: 0
+ Repeater {
+ model: osk.rows[keyRow.r]
+ delegate: Item {
+ id: keyItem
+ required property var modelData
+ required property int index
+ readonly property bool current: osk.row === keyRow.r && osk.col === index
+ readonly property bool special: modelData.a !== "" && modelData.a !== "text"
+ width: keys.unit * modelData.w
+ height: Theme.dp(78)
+
+ Rectangle {
+ anchors { fill: parent; margins: Theme.dp(4) }
+ radius: Theme.r(10)
+ color: keyItem.current ? Theme.accent
+ : (keyItem.modelData.a === "shift" && osk.shift) ? Theme.alpha(Theme.accent, 0.45)
+ : keyItem.special ? Theme.surfaceHi : Theme.card
+ scale: keyItem.current ? 1.06 : 1
+ Behavior on scale { NumberAnimation { duration: 90 } }
+ Text {
+ anchors.centerIn: parent
+ text: osk.labelFor(keyItem.modelData)
+ color: keyItem.current ? Theme.onAccent : Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: keyItem.modelData.l.length > 2 ? Theme.dp(24) : Theme.dp(32)
+ }
+ }
+ MouseArea {
+ anchors.fill: parent
+ onClicked: {
+ osk.row = keyRow.r
+ osk.col = keyItem.index
+ osk.press(keyItem.modelData)
+ osk.forceActiveFocus()
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ Text {
+ anchors.horizontalCenter: parent.horizontalCenter
+ text: "A skriv · X radera · RB mellanslag · Y klar · B avbryt"
+ color: Theme.textDim
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(20)
+ }
+ }
+}
diff --git a/qml/OptionCycler.qml b/qml/OptionCycler.qml
new file mode 100644
index 0000000..89a3402
--- /dev/null
+++ b/qml/OptionCycler.qml
@@ -0,0 +1,70 @@
+import QtQuick
+import TvLauncher
+
+// Väljare som fungerar med handkontroll: vänster/höger eller A byter värde.
+// Upp/ner lämnas fria för att flytta mellan fält.
+FocusScope {
+ id: cycler
+
+ property var options: [] // [{ value: ..., label: "..." }]
+ property var value
+ readonly property int index: {
+ for (let i = 0; i < options.length; ++i)
+ if (options[i].value === value) return i
+ return -1
+ }
+
+ implicitHeight: Theme.dp(60)
+ activeFocusOnTab: true
+
+ function step(d) {
+ if (options.length === 0) return
+ const i = index < 0 ? 0 : (index + d + options.length) % options.length
+ value = options[i].value
+ }
+
+ Keys.onLeftPressed: step(-1)
+ Keys.onRightPressed: step(1)
+ Keys.onReturnPressed: step(1)
+ Keys.onEnterPressed: step(1)
+
+ Rectangle {
+ anchors.fill: parent
+ radius: Theme.r(8)
+ color: cycler.activeFocus ? Theme.surfaceHi : Theme.surface
+ border.width: cycler.activeFocus ? Theme.dp(3) : Theme.dp(1)
+ border.color: cycler.activeFocus ? Theme.accent : Theme.border
+
+ Text {
+ anchors { left: parent.left; leftMargin: Theme.dp(18); verticalCenter: parent.verticalCenter }
+ text: "‹"
+ color: Theme.textDim
+ font.pixelSize: Theme.dp(32)
+ }
+ Text {
+ anchors.centerIn: parent
+ width: parent.width - Theme.dp(100)
+ horizontalAlignment: Text.AlignHCenter
+ elide: Text.ElideRight
+ text: cycler.index >= 0 ? cycler.options[cycler.index].label : ""
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(24)
+ }
+ Text {
+ anchors { right: parent.right; rightMargin: Theme.dp(18); verticalCenter: parent.verticalCenter }
+ text: "›"
+ color: Theme.textDim
+ font.pixelSize: Theme.dp(32)
+ }
+ }
+
+ MouseArea {
+ anchors.fill: parent
+ acceptedButtons: Qt.LeftButton | Qt.RightButton
+ onClicked: (mouse) => {
+ cycler.forceActiveFocus()
+ cycler.step(mouse.button === Qt.RightButton || mouse.x < width / 3 ? -1 : 1)
+ }
+ }
+}
diff --git a/qml/SearchPopup.qml b/qml/SearchPopup.qml
new file mode 100644
index 0000000..4f78454
--- /dev/null
+++ b/qml/SearchPopup.qml
@@ -0,0 +1,149 @@
+import QtQuick
+import QtQuick.Controls
+import TvLauncher
+
+// Sök bland apparna på hemskärmen. Skriv för att filtrera, Enter startar.
+Popup {
+ id: popup
+
+ signal chosen(var app)
+
+ property var all: []
+ readonly property var filtered: {
+ const q = field.text.trim().toLowerCase()
+ if (q === "") return all
+ return all.filter(a => a.name.toLowerCase().indexOf(q) >= 0
+ || (a.url || "").toLowerCase().indexOf(q) >= 0
+ || (a.command || "").toLowerCase().indexOf(q) >= 0)
+ }
+
+ parent: Overlay.overlay
+ x: (parent.width - width) / 2
+ y: Theme.dp(140)
+ width: Math.min(parent.width - Theme.dp(160), Theme.dp(1100))
+ height: parent.height - Theme.dp(280)
+ modal: true
+ focus: true
+ padding: Theme.dp(30)
+
+ background: Rectangle { color: Theme.alpha(Theme.surface, 0.94); radius: Theme.r(18); border.color: Theme.border }
+ Overlay.modal: Rectangle { color: Theme.scrim }
+
+ onAboutToShow: {
+ field.text = ""
+ let list = []
+ for (const c of apps.categories) list = list.concat(apps.appsIn(c))
+ all = list
+ }
+ onOpened: field.forceActiveFocus()
+
+ contentItem: Item {
+ Rectangle {
+ id: box
+ anchors { left: parent.left; right: parent.right; top: parent.top }
+ height: Theme.dp(76)
+ radius: Theme.r(10)
+ color: Theme.surface
+ border.width: field.activeFocus ? Theme.dp(3) : Theme.dp(1)
+ border.color: field.activeFocus ? Theme.accent : Theme.border
+
+ Icon {
+ id: searchIcon
+ anchors { left: parent.left; leftMargin: Theme.dp(22); verticalCenter: parent.verticalCenter }
+ width: Theme.dp(36); height: width
+ name: "search"
+ }
+ TextField {
+ id: field
+ anchors { left: searchIcon.right; leftMargin: Theme.dp(12); right: parent.right; rightMargin: Theme.dp(12); verticalCenter: parent.verticalCenter }
+ placeholderText: "Sök efter appar ..."
+ placeholderTextColor: Theme.placeholder
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(30)
+ background: Item {}
+ KeyNavigation.down: results
+ onAccepted: if (popup.filtered.length > 0) { popup.close(); popup.chosen(popup.filtered[0]) }
+ }
+ }
+
+ ListView {
+ id: results
+ anchors { left: parent.left; right: parent.right; top: box.bottom; topMargin: Theme.dp(20); bottom: parent.bottom }
+ clip: true
+ spacing: Theme.dp(6)
+ model: popup.filtered
+ Keys.onPressed: (event) => {
+ if (event.key === Qt.Key_Up && currentIndex === 0) {
+ field.forceActiveFocus(); event.accepted = true
+ } else if (event.text.length === 1 && event.text.trim() !== "") {
+ field.forceActiveFocus(); field.text += event.text; event.accepted = true
+ }
+ }
+
+ delegate: Rectangle {
+ id: entry
+ required property var modelData
+ required property int index
+ width: ListView.view.width
+ height: Theme.dp(86)
+ radius: Theme.r(10)
+ readonly property bool current: ListView.isCurrentItem && results.activeFocus
+ color: current ? Theme.surfaceHi : "transparent"
+ border.width: current ? Theme.dp(3) : 0
+ border.color: Theme.accent
+
+ function choose() { popup.close(); popup.chosen(modelData) }
+ Keys.onReturnPressed: choose()
+ Keys.onEnterPressed: choose()
+
+ Rectangle {
+ id: thumb
+ anchors { left: parent.left; leftMargin: Theme.dp(14); verticalCenter: parent.verticalCenter }
+ width: Theme.dp(96); height: Theme.dp(60)
+ radius: Theme.r(6)
+ color: Theme.tileColor(entry.modelData.name, entry.modelData.color || "")
+ Image {
+ id: ti
+ anchors.centerIn: parent
+ width: Theme.dp(40); height: width
+ sourceSize: Qt.size(128, 128)
+ source: entry.modelData.icon ? "image://icon/" + encodeURIComponent(entry.modelData.icon) : ""
+ visible: status === Image.Ready && implicitWidth > 1
+ }
+ Text {
+ anchors.centerIn: parent
+ visible: !ti.visible
+ text: entry.modelData.name.charAt(0).toUpperCase()
+ color: Theme.text
+ font.pixelSize: Theme.dp(30)
+ font.weight: Font.DemiBold
+ }
+ }
+ Column {
+ anchors { left: thumb.right; leftMargin: Theme.dp(20); right: parent.right; verticalCenter: parent.verticalCenter }
+ Text {
+ text: entry.modelData.name
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(28)
+ }
+ Text {
+ text: entry.modelData.category + " · " + (entry.modelData.type === "web" ? entry.modelData.url : entry.modelData.command)
+ color: Theme.textDim
+ elide: Text.ElideRight
+ width: parent.width - Theme.dp(20)
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(20)
+ }
+ }
+ MouseArea {
+ anchors.fill: parent
+ hoverEnabled: true
+ onEntered: { results.currentIndex = entry.index; results.forceActiveFocus() }
+ onClicked: entry.choose()
+ }
+ }
+ }
+ }
+}
diff --git a/qml/SectionTitle.qml b/qml/SectionTitle.qml
new file mode 100644
index 0000000..98e242b
--- /dev/null
+++ b/qml/SectionTitle.qml
@@ -0,0 +1,11 @@
+import QtQuick
+import TvLauncher
+
+Text {
+ width: parent ? parent.width : implicitWidth
+ topPadding: Theme.dp(26)
+ bottomPadding: Theme.dp(4)
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(32)
+}
diff --git a/qml/SettingsCard.qml b/qml/SettingsCard.qml
new file mode 100644
index 0000000..7b09b30
--- /dev/null
+++ b/qml/SettingsCard.qml
@@ -0,0 +1,179 @@
+import QtQuick
+import TvLauncher
+
+// Rad på inställningssidorna: ikon, rubrik, undertext och valfri
+// av/på-knapp, bock eller text till höger.
+Rectangle {
+ id: card
+
+ property bool focusable: true
+ property string icon
+ property string appIcon // ikon via image://icon (appar)
+ property string title
+ property string subtitle
+ property string valueText
+ property var toggle: undefined // true/false visar en av/på-knapp
+ property bool checked: false // visar en bock
+ property bool busy: false
+ // Val som bläddras med vänster/höger: [{ value, label }]
+ property var options: []
+ property var value
+ readonly property int optionIndex: options.findIndex(o => o.value === value)
+
+ signal chosen(var value)
+
+ function cycle(d) {
+ if (options.length === 0) return false
+ const i = ((optionIndex < 0 ? 0 : optionIndex) + d + options.length) % options.length
+ card.chosen(options[i].value)
+ return true
+ }
+
+ signal activated()
+ signal menuRequested()
+
+ width: parent ? parent.width : Theme.dp(800)
+ implicitHeight: Math.max(Theme.dp(88), col.implicitHeight + Theme.dp(32))
+ height: implicitHeight
+ radius: Theme.r(10)
+ color: activeFocus ? Theme.cardFocus : Theme.card
+ border.width: activeFocus ? Theme.dp(3) : 0
+ border.color: Theme.accent
+ activeFocusOnTab: true
+
+ Keys.onReturnPressed: options.length > 0 ? cycle(1) : card.activated()
+ Keys.onEnterPressed: options.length > 0 ? cycle(1) : card.activated()
+ Keys.onSpacePressed: card.activated()
+ Keys.onLeftPressed: (event) => event.accepted = cycle(-1)
+ Keys.onRightPressed: (event) => event.accepted = cycle(1)
+ Keys.onMenuPressed: card.menuRequested()
+
+ Item {
+ id: ic
+ visible: card.icon !== "" || card.appIcon !== ""
+ anchors { left: parent.left; leftMargin: Theme.dp(26); verticalCenter: parent.verticalCenter }
+ width: card.appIcon !== "" ? Theme.dp(52) : Theme.dp(40); height: width
+ Icon {
+ anchors.fill: parent
+ visible: card.appIcon === ""
+ name: card.icon
+ }
+ Image {
+ id: appImg
+ anchors.fill: parent
+ visible: card.appIcon !== "" && status === Image.Ready && implicitWidth > 1
+ sourceSize: Qt.size(128, 128)
+ asynchronous: true
+ source: card.appIcon !== "" ? "image://icon/" + encodeURIComponent(card.appIcon) : ""
+ }
+ Rectangle {
+ anchors.fill: parent
+ visible: card.appIcon !== "" && !appImg.visible
+ radius: Theme.r(8)
+ color: Qt.darker(Theme.colorFor(card.title), 1.15)
+ Text {
+ anchors.centerIn: parent
+ text: card.title.charAt(0).toUpperCase()
+ color: Theme.text
+ font.pixelSize: Theme.dp(28)
+ font.weight: Font.DemiBold
+ }
+ }
+ }
+
+ Column {
+ id: col
+ anchors {
+ left: ic.visible ? ic.right : parent.left
+ leftMargin: Theme.dp(24)
+ right: rightRow.left
+ rightMargin: Theme.dp(20)
+ verticalCenter: parent.verticalCenter
+ }
+ spacing: Theme.dp(6)
+ Text {
+ width: parent.width
+ text: card.title
+ color: Theme.text
+ elide: Text.ElideRight
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(28)
+ }
+ Text {
+ width: parent.width
+ visible: text !== ""
+ text: card.subtitle
+ color: Theme.textDim
+ wrapMode: Text.Wrap
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(22)
+ }
+ }
+
+ Row {
+ id: rightRow
+ anchors { right: parent.right; rightMargin: Theme.dp(26); verticalCenter: parent.verticalCenter }
+ spacing: Theme.dp(16)
+
+ Text {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: card.busy
+ text: "…"
+ color: Theme.textDim
+ font.pixelSize: Theme.dp(32)
+ SequentialAnimation on opacity {
+ running: card.busy; loops: Animation.Infinite
+ NumberAnimation { to: 0.2; duration: 500 }
+ NumberAnimation { to: 1; duration: 500 }
+ }
+ }
+ Text {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: card.valueText !== ""
+ text: card.valueText
+ color: Theme.textDim
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(24)
+ }
+ Text {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: card.options.length > 0
+ text: "◀ " + (card.optionIndex >= 0 ? card.options[card.optionIndex].label : "") + " ▶"
+ color: card.activeFocus ? Theme.text : Theme.textDim
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(24)
+ }
+ Icon {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: card.checked
+ width: Theme.dp(34); height: width
+ name: "check"
+ }
+ Rectangle {
+ anchors.verticalCenter: parent.verticalCenter
+ visible: card.toggle !== undefined
+ width: Theme.dp(72); height: Theme.dp(38)
+ radius: height / 2
+ color: card.toggle === true ? Theme.accent : Theme.track
+ Rectangle {
+ width: parent.height - Theme.dp(8); height: width
+ radius: width / 2
+ y: Theme.dp(4)
+ x: card.toggle === true ? parent.width - width - Theme.dp(4) : Theme.dp(4)
+ color: "white"
+ Behavior on x { NumberAnimation { duration: 120 } }
+ }
+ }
+ }
+
+ MouseArea {
+ anchors.fill: parent
+ acceptedButtons: Qt.LeftButton | Qt.RightButton
+ onClicked: (mouse) => {
+ card.forceActiveFocus()
+ if (mouse.button === Qt.RightButton) card.menuRequested()
+ else if (card.options.length > 0) card.cycle(1)
+ else card.activated()
+ }
+ }
+}
diff --git a/qml/SettingsView.qml b/qml/SettingsView.qml
new file mode 100644
index 0000000..1b9104f
--- /dev/null
+++ b/qml/SettingsView.qml
@@ -0,0 +1,151 @@
+import QtQuick
+import TvLauncher
+
+// Inställningar i Bigscreen-stil: sidomeny till vänster, innehåll till höger.
+// B/Esc i innehållet går till sidomenyn, i sidomenyn tillbaka till hem.
+FocusScope {
+ id: view
+
+ property string page: "apps"
+
+ signal closeRequested()
+ signal editApp(var app)
+ signal addApp(string type)
+ signal pickInstalled()
+
+ readonly property var pages: [
+ { key: "audio", label: "Ljud", icon: "volume", title: "Ljud" },
+ { key: "bluetooth", label: "Bluetooth", icon: "bluetooth", title: "Bluetooth" },
+ { key: "wifi", label: "Wi‑Fi", icon: "wifi", title: "Wi‑Fi" },
+ { key: "theme", label: "Tema", icon: "palette", title: "Tema" },
+ { key: "wallpaper", label: "Bakgrund", icon: "image", title: "Bakgrund" },
+ { key: "apps", label: "Appar", icon: "apps", title: "Appar och webbappar" }
+ ]
+
+ function openPage(key, focusContent) {
+ const i = pages.findIndex(p => p.key === key)
+ nav.currentIndex = i >= 0 ? i : 0
+ if (focusContent) Qt.callLater(focusContentArea)
+ else nav.forceActiveFocus()
+ }
+
+ function focusContentArea() {
+ if (content.item && content.item.focusFirst) content.item.focusFirst()
+ }
+
+ Keys.onEscapePressed: {
+ if (nav.activeFocus) view.closeRequested()
+ else nav.forceActiveFocus()
+ }
+ Keys.onLeftPressed: nav.forceActiveFocus()
+
+ // ---------------------------------------------------------- sidomeny
+ Rectangle {
+ id: side
+ anchors { left: parent.left; top: parent.top; bottom: parent.bottom }
+ width: Math.round(parent.width * 0.28)
+ color: Theme.alpha(Theme.sidebar, 0.45)
+
+ Text {
+ id: sideTitle
+ x: Theme.dp(40); y: Theme.dp(80)
+ text: "Inställningar"
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(52)
+ font.weight: Font.Light
+ }
+
+ ListView {
+ id: nav
+ anchors { left: parent.left; right: parent.right; top: sideTitle.bottom; bottom: parent.bottom; margins: Theme.dp(28); topMargin: Theme.dp(60) }
+ model: view.pages
+ spacing: Theme.dp(10)
+ focus: true
+ interactive: false
+ keyNavigationEnabled: true
+ onCurrentIndexChanged: view.page = view.pages[currentIndex].key
+
+ Keys.onRightPressed: view.focusContentArea()
+ Keys.onReturnPressed: view.focusContentArea()
+ Keys.onEnterPressed: view.focusContentArea()
+
+ delegate: Rectangle {
+ id: navItem
+ required property var modelData
+ required property int index
+ readonly property bool current: ListView.isCurrentItem
+ width: ListView.view.width
+ height: Theme.dp(84)
+ radius: Theme.r(10)
+ color: current ? (nav.activeFocus ? Theme.alpha(Theme.accent, 0.3) : "#33ffffff") : "transparent"
+ border.width: current && nav.activeFocus ? Theme.dp(3) : 0
+ border.color: Theme.accent
+
+ Icon {
+ id: navIcon
+ anchors { left: parent.left; leftMargin: Theme.dp(30); verticalCenter: parent.verticalCenter }
+ width: Theme.dp(40); height: width
+ name: navItem.modelData.icon
+ }
+ Text {
+ anchors { left: navIcon.right; leftMargin: Theme.dp(28); verticalCenter: parent.verticalCenter }
+ text: navItem.modelData.label
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(32)
+ }
+ MouseArea {
+ anchors.fill: parent
+ onClicked: { nav.currentIndex = navItem.index; nav.forceActiveFocus() }
+ }
+ }
+ }
+ }
+
+ // ---------------------------------------------------------- innehåll
+ Rectangle {
+ anchors { left: side.right; right: parent.right; top: parent.top; bottom: parent.bottom }
+ color: Theme.alpha(Theme.panel, 0.95)
+
+ Text {
+ id: pageTitle
+ x: Theme.dp(60); y: Theme.dp(80)
+ text: view.pages[nav.currentIndex].title
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(52)
+ font.weight: Font.Light
+ }
+
+ Loader {
+ id: content
+ anchors { left: parent.left; right: parent.right; top: pageTitle.bottom; bottom: parent.bottom
+ leftMargin: Theme.dp(60); rightMargin: Theme.dp(60); topMargin: Theme.dp(40) }
+ sourceComponent: {
+ switch (view.page) {
+ case "audio": return audioPage
+ case "bluetooth": return bluetoothPage
+ case "wifi": return wifiPage
+ case "wallpaper": return wallpaperPage
+ case "theme": return themePage
+ default: return appsPage
+ }
+ }
+ }
+ }
+
+ Component { id: audioPage; AudioPage {} }
+ Component { id: bluetoothPage; BluetoothPage {} }
+ Component { id: wifiPage; WifiPage {} }
+ Component { id: wallpaperPage; WallpaperPage {} }
+ Component { id: themePage; ThemePage {} }
+ Component {
+ id: appsPage
+ AppsPage {
+ onEditApp: (app) => view.editApp(app)
+ onAddApp: (type) => view.addApp(type)
+ onPickInstalled: view.pickInstalled()
+ }
+ }
+}
diff --git a/qml/SliderCard.qml b/qml/SliderCard.qml
new file mode 100644
index 0000000..6ae9d61
--- /dev/null
+++ b/qml/SliderCard.qml
@@ -0,0 +1,83 @@
+import QtQuick
+import TvLauncher
+
+// Reglage som styrs med vänster/höger (t.ex. volym).
+Rectangle {
+ id: card
+
+ property bool focusable: true
+ property string icon
+ property string title
+ property real value: 0 // 0..1
+ property real step: 0.05
+ property string valueText: Math.round(value * 100) + " %"
+
+ signal moved(real value)
+ signal activated()
+
+ width: parent ? parent.width : Theme.dp(800)
+ implicitHeight: Theme.dp(120)
+ height: implicitHeight
+ radius: Theme.r(10)
+ color: activeFocus ? Theme.cardFocus : Theme.card
+ border.width: activeFocus ? Theme.dp(3) : 0
+ border.color: Theme.accent
+ activeFocusOnTab: true
+
+ function nudge(d) {
+ const v = Math.max(0, Math.min(1, Math.round((value + d) / step) * step))
+ card.moved(v)
+ }
+ Keys.onLeftPressed: nudge(-step)
+ Keys.onRightPressed: nudge(step)
+ Keys.onReturnPressed: card.activated()
+ Keys.onEnterPressed: card.activated()
+
+ Icon {
+ id: ic
+ visible: card.icon !== ""
+ anchors { left: parent.left; leftMargin: Theme.dp(26); verticalCenter: parent.verticalCenter }
+ width: Theme.dp(40); height: width
+ name: card.icon
+ }
+
+ Text {
+ id: titleText
+ anchors { left: ic.visible ? ic.right : parent.left; leftMargin: Theme.dp(24); top: parent.top; topMargin: Theme.dp(20) }
+ text: card.title
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(28)
+ }
+ Text {
+ anchors { right: parent.right; rightMargin: Theme.dp(26); verticalCenter: titleText.verticalCenter }
+ text: "◀ " + card.valueText + " ▶"
+ color: card.activeFocus ? Theme.text : Theme.textDim
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(24)
+ }
+
+ Rectangle {
+ id: track
+ anchors { left: titleText.left; right: parent.right; rightMargin: Theme.dp(26); bottom: parent.bottom; bottomMargin: Theme.dp(24) }
+ height: Theme.dp(8)
+ radius: height / 2
+ color: Theme.track
+ Rectangle {
+ width: parent.width * card.value
+ height: parent.height
+ radius: parent.radius
+ color: Theme.accent
+ }
+ }
+
+ MouseArea {
+ anchors.fill: parent
+ onClicked: (mouse) => {
+ card.forceActiveFocus()
+ const p = mapToItem(track, mouse.x, mouse.y)
+ if (p.x >= 0 && p.x <= track.width)
+ card.moved(Math.round(p.x / track.width / card.step) * card.step)
+ }
+ }
+}
diff --git a/qml/Theme.qml b/qml/Theme.qml
new file mode 100644
index 0000000..3cb6125
--- /dev/null
+++ b/qml/Theme.qml
@@ -0,0 +1,142 @@
+pragma Singleton
+import QtQuick
+
+// Alla färger och mått på ett ställe (motsvarar CSS-variabler).
+// Komponenterna läser t.ex. Theme.card och Theme.accent; när ett värde
+// här ändras uppdateras hela gränssnittet direkt.
+//
+// preset, accent, tileScale och radiusScale sätts från inställningarna
+// (Main.qml binder dem till prefs, som sparas i settings.ini).
+QtObject {
+ id: theme
+
+ // ---- skalning -------------------------------------------------------
+ property real s: 1 // fönsterhöjd / 1080
+ property real tileScale: 1 // rutstorlek
+ property real radiusScale: 1 // hörnens rundning
+ function dp(v) { return Math.round(v * s) }
+ function tile(v) { return Math.round(v * s * tileScale) }
+ function r(v) { return Math.round(v * s * radiusScale) }
+
+ // ---- val ------------------------------------------------------------
+ property string preset: "standard"
+ property color accent: "#3daee9"
+ property string tileMode: "app" // "app" | "theme" | "accent"
+ property real tileOpacity: 1 // 1 = helt täckande
+ property string homePath: ""
+
+ readonly property var presets: ({
+ standard: { name: "Standard",
+ bg: "#0f1317", bgTop: "#1a2330", surface: "#1e252e", surfaceHi: "#2a333f",
+ card: "#2f353d", cardFocus: "#3a4350", panel: "#262a31", sidebar: "#141820",
+ border: "#3a4552", borderSoft: "#2f3a46", track: "#55606c",
+ text: "#eef1f4", textDim: "#98a3af", placeholder: "#66717d",
+ backdropTop: "#2a2350", backdropMid: "#1a1d33", backdropBottom: "#101320", backdropGlow: "#a0507a" },
+ midnight: { name: "Midnatt",
+ bg: "#0a0f1e", bgTop: "#121b36", surface: "#141c33", surfaceHi: "#1f2a4a",
+ card: "#1b2440", cardFocus: "#26335a", panel: "#121a30", sidebar: "#0a1020",
+ border: "#2c3a63", borderSoft: "#222e52", track: "#3a4a78",
+ text: "#eef2fb", textDim: "#93a1c4", placeholder: "#5f6c90",
+ backdropTop: "#13235a", backdropMid: "#0c1736", backdropBottom: "#070c1c", backdropGlow: "#2d6bd6" },
+ oled: { name: "OLED svart",
+ bg: "#000000", bgTop: "#050505", surface: "#101010", surfaceHi: "#1c1c1c",
+ card: "#141414", cardFocus: "#242424", panel: "#0a0a0a", sidebar: "#000000",
+ border: "#2a2a2a", borderSoft: "#1e1e1e", track: "#3a3a3a",
+ text: "#f2f2f2", textDim: "#9a9a9a", placeholder: "#5e5e5e",
+ backdropTop: "#000000", backdropMid: "#000000", backdropBottom: "#000000", backdropGlow: "#000000" },
+ warm: { name: "Varm",
+ bg: "#17110d", bgTop: "#2a1d15", surface: "#241a14", surfaceHi: "#33261d",
+ card: "#2e221a", cardFocus: "#3d2e23", panel: "#221912", sidebar: "#150f0b",
+ border: "#4a372a", borderSoft: "#3a2b20", track: "#5e4636",
+ text: "#f6efe8", textDim: "#b3a191", placeholder: "#7d6b5c",
+ backdropTop: "#4a2a1a", backdropMid: "#2a1a12", backdropBottom: "#120c08", backdropGlow: "#c0702a" },
+ forest: { name: "Skog",
+ bg: "#0d1512", bgTop: "#15261f", surface: "#16221d", surfaceHi: "#203029",
+ card: "#1c2a24", cardFocus: "#273a31", panel: "#14201b", sidebar: "#0b1310",
+ border: "#2f4a3e", borderSoft: "#253b31", track: "#3e5e50",
+ text: "#eef5f1", textDim: "#98b0a5", placeholder: "#5f7a6e",
+ backdropTop: "#173a2c", backdropMid: "#10241c", backdropBottom: "#08120e", backdropGlow: "#3a9a6a" }
+ })
+ readonly property var presetKeys: ["standard", "midnight", "oled", "warm", "forest"]
+
+ readonly property var accents: [
+ { name: "Blå", color: "#3daee9" }, { name: "Lila", color: "#9b59b6" },
+ { name: "Rosa", color: "#e93d8c" }, { name: "Röd", color: "#da4453" },
+ { name: "Orange", color: "#f67400" }, { name: "Gul", color: "#fdbc4b" },
+ { name: "Grön", color: "#27ae60" }, { name: "Turkos", color: "#1abc9c" },
+ { name: "Vit", color: "#e8e8e8" }
+ ]
+
+ readonly property var p: presets[preset] || presets.standard
+
+ // ---- färger ---------------------------------------------------------
+ readonly property color bg: p.bg
+ readonly property color bgTop: p.bgTop
+ readonly property color surface: p.surface // fält, dialoger
+ readonly property color surfaceHi: p.surfaceHi // markerade fält
+ readonly property color card: p.card // kort i inställningar
+ readonly property color cardFocus: p.cardFocus
+ readonly property color panel: p.panel // inställningarnas innehållsyta
+ readonly property color sidebar: p.sidebar
+ readonly property color border: p.border
+ readonly property color borderSoft: p.borderSoft
+ readonly property color track: p.track // reglage, av-läge
+ readonly property color text: p.text
+ readonly property color textDim: p.textDim
+ readonly property color placeholder: p.placeholder
+ readonly property color danger: "#e5534b"
+ readonly property color onAccent: Qt.colorEqual(accent, "#e8e8e8") || Qt.colorEqual(accent, "#fdbc4b")
+ ? "#111111" : "#ffffff"
+ readonly property color scrim: "#b0000000"
+
+ readonly property color backdropTop: p.backdropTop
+ readonly property color backdropMid: p.backdropMid
+ readonly property color backdropBottom: p.backdropBottom
+ readonly property color backdropGlow: p.backdropGlow
+
+ function alpha(c, a) {
+ const col = Qt.lighter(c, 1.0) // tar även emot strängar som "#ff0000"
+ return Qt.rgba(col.r, col.g, col.b, a)
+ }
+
+ // Färg att välja för en app (Utseende). Tom = automatiskt.
+ readonly property var tileColorChoices: [
+ { value: "", label: "Automatisk" },
+ { value: "#2d5d8a", label: "Blå" }, { value: "#3e5a8f", label: "Kungsblå" },
+ { value: "#2b7a8a", label: "Petrol" }, { value: "#2f7d5b", label: "Grön" },
+ { value: "#5c6b2d", label: "Oliv" }, { value: "#a2552b", label: "Orange" },
+ { value: "#8a2d4b", label: "Vinröd" }, { value: "#7a3e8f", label: "Lila" },
+ { value: "#3a3f47", label: "Grå" }, { value: "#111111", label: "Svart" },
+ { value: "#e8e8e8", label: "Vit" }
+ ]
+
+ // Rutans bakgrund: appens egen färg, annars enligt tileMode.
+ function tileColor(name, custom) {
+ let base
+ if (custom && custom !== "") base = custom
+ else if (tileMode === "theme") base = cardFocus
+ else if (tileMode === "accent") base = Qt.darker(accent, 1.6)
+ else base = Qt.darker(colorFor(name), 1.15)
+ return alpha(base, tileOpacity)
+ }
+
+ // Bildsökväg eller webbadress -> URL för Image.
+ function imageUrl(p) {
+ if (!p) return ""
+ if (/^[a-z]+:\/\//i.test(p)) return p
+ if (p.startsWith("~/")) return "file://" + homePath + p.slice(1)
+ return "file://" + p
+ }
+
+ readonly property string fontFamily: "Noto Sans"
+
+ readonly property var tileColors: ["#2d5d8a", "#7a3e8f", "#2f7d5b", "#a2552b",
+ "#8a2d4b", "#3e5a8f", "#5c6b2d", "#2b7a8a"]
+
+ function colorFor(name) {
+ let h = 0
+ for (let i = 0; i < name.length; ++i)
+ h = (h * 31 + name.charCodeAt(i)) >>> 0
+ return tileColors[h % tileColors.length]
+ }
+}
diff --git a/qml/ThemePage.qml b/qml/ThemePage.qml
new file mode 100644
index 0000000..78bbc9e
--- /dev/null
+++ b/qml/ThemePage.qml
@@ -0,0 +1,187 @@
+import QtQuick
+import TvLauncher
+
+// Tema: färgtema, accentfärg, rutstorlek och hörn. Allt ändras direkt
+// och sparas i ~/.config/tv-launcher/settings.ini.
+Item {
+ id: page
+
+ function focusFirst() { list.focusFirst() }
+
+ // Vågrät rad med val (färgteman, accentfärger). Upp/ner går vidare i listan.
+ component ChoiceRow: ListView {
+ id: row
+ property bool focusable: true
+ property var selected
+ signal picked(var value)
+
+ width: parent ? parent.width : 0
+ orientation: ListView.Horizontal
+ spacing: Theme.dp(18)
+ clip: false
+ keyNavigationWraps: false
+ boundsBehavior: Flickable.StopAtBounds
+ highlightRangeMode: ListView.ApplyRange
+ preferredHighlightBegin: Theme.dp(10)
+ preferredHighlightEnd: width - Theme.dp(10)
+ highlightMoveDuration: 150
+ onActiveFocusChanged: if (activeFocus) list.ensureVisible(row)
+ }
+
+ CardList {
+ id: list
+ anchors.fill: parent
+
+ SectionTitle { text: "Färgtema"; topPadding: 0 }
+
+ ChoiceRow {
+ id: presetRow
+ height: Theme.dp(190)
+ model: Theme.presetKeys
+ selected: prefs.themePreset
+ currentIndex: Math.max(0, Theme.presetKeys.indexOf(prefs.themePreset))
+ delegate: Item {
+ id: presetItem
+ required property string modelData
+ required property int index
+ readonly property var pal: Theme.presets[modelData]
+ readonly property bool current: ListView.isCurrentItem && presetRow.activeFocus
+ width: Theme.dp(220)
+ height: presetRow.height
+
+ Keys.onReturnPressed: prefs.themePreset = modelData
+ Keys.onEnterPressed: prefs.themePreset = modelData
+
+ // Miniatyr av temat: bakgrund, kort och accent.
+ Rectangle {
+ id: swatch
+ width: parent.width
+ height: Theme.dp(130)
+ radius: Theme.r(12)
+ border.width: presetItem.current ? Theme.dp(4) : Theme.dp(1)
+ border.color: presetItem.current ? Theme.accent : Theme.border
+ gradient: Gradient {
+ GradientStop { position: 0; color: presetItem.pal.backdropTop }
+ GradientStop { position: 1; color: presetItem.pal.bg }
+ }
+ Column {
+ anchors { left: parent.left; right: parent.right; bottom: parent.bottom; margins: Theme.dp(16) }
+ spacing: Theme.dp(8)
+ Rectangle { width: parent.width; height: Theme.dp(20); radius: Theme.r(4); color: presetItem.pal.cardFocus; border.width: Theme.dp(2); border.color: Theme.accent }
+ Rectangle { width: parent.width * 0.7; height: Theme.dp(20); radius: Theme.r(4); color: presetItem.pal.card }
+ }
+ Rectangle {
+ visible: prefs.themePreset === presetItem.modelData
+ anchors { right: parent.right; top: parent.top; margins: Theme.dp(10) }
+ width: Theme.dp(36); height: width; radius: width / 2
+ color: Theme.accent
+ Icon { anchors.centerIn: parent; width: Theme.dp(24); height: width; name: "check" }
+ }
+ }
+ Text {
+ anchors { top: swatch.bottom; topMargin: Theme.dp(12); horizontalCenter: parent.horizontalCenter }
+ text: presetItem.pal.name
+ color: presetItem.current ? Theme.text : Theme.textDim
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(24)
+ }
+ MouseArea {
+ anchors.fill: parent
+ onClicked: { presetRow.currentIndex = presetItem.index; presetRow.forceActiveFocus(); prefs.themePreset = presetItem.modelData }
+ }
+ }
+ }
+
+ SectionTitle { text: "Accentfärg" }
+
+ ChoiceRow {
+ id: accentRow
+ height: Theme.dp(130)
+ model: Theme.accents
+ currentIndex: Math.max(0, Theme.accents.findIndex(a => Qt.colorEqual(a.color, prefs.accent)))
+ delegate: Item {
+ id: accentItem
+ required property var modelData
+ required property int index
+ readonly property bool current: ListView.isCurrentItem && accentRow.activeFocus
+ readonly property bool selected: Qt.colorEqual(modelData.color, prefs.accent)
+ width: Theme.dp(96)
+ height: accentRow.height
+
+ Keys.onReturnPressed: prefs.accent = modelData.color
+ Keys.onEnterPressed: prefs.accent = modelData.color
+
+ Rectangle {
+ id: dot
+ anchors.horizontalCenter: parent.horizontalCenter
+ y: Theme.dp(6)
+ width: Theme.dp(72); height: width
+ radius: width / 2
+ color: accentItem.modelData.color
+ border.width: accentItem.current ? Theme.dp(5) : 0
+ border.color: Theme.text
+ scale: accentItem.current ? 1.1 : 1
+ Behavior on scale { NumberAnimation { duration: 120 } }
+ Icon {
+ visible: accentItem.selected
+ anchors.centerIn: parent
+ width: Theme.dp(36); height: width
+ name: "check"
+ }
+ }
+ Text {
+ anchors { top: dot.bottom; topMargin: Theme.dp(12); horizontalCenter: parent.horizontalCenter }
+ text: accentItem.modelData.name
+ color: accentItem.current ? Theme.text : Theme.textDim
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(20)
+ }
+ MouseArea {
+ anchors.fill: parent
+ onClicked: { accentRow.currentIndex = accentItem.index; accentRow.forceActiveFocus(); prefs.accent = accentItem.modelData.color }
+ }
+ }
+ }
+
+ SectionTitle { text: "Utseende" }
+
+ SettingsCard {
+ icon: "palette"
+ title: "Rutornas färg"
+ subtitle: "En app med egen färg (Y → Utseende) behåller den"
+ options: [{ value: "app", label: "Färg per app" }, { value: "theme", label: "Temats färg" },
+ { value: "accent", label: "Accentfärgen" }]
+ value: prefs.tileMode
+ onChosen: (v) => prefs.tileMode = v
+ }
+ SliderCard {
+ icon: "image"
+ title: "Rutornas genomskinlighet"
+ // 0 % = täckande, 90 % = nästan genomskinlig
+ value: (1 - Number(prefs.tileOpacity)) / 0.9
+ valueText: Math.round((1 - Number(prefs.tileOpacity)) * 100) + " %"
+ onMoved: (v) => prefs.tileOpacity = 1 - v * 0.9
+ }
+ SettingsCard {
+ icon: "apps"
+ title: "Rutstorlek"
+ subtitle: "Storlek på apparna på hemskärmen"
+ options: [{ value: 0.85, label: "Liten" }, { value: 1.0, label: "Normal" }, { value: 1.15, label: "Stor" }]
+ value: Number(prefs.tileScale)
+ onChosen: (v) => prefs.tileScale = v
+ }
+ SettingsCard {
+ icon: "image"
+ title: "Hörn"
+ subtitle: "Hur rundade rutor, kort och knappar är"
+ options: [{ value: 0.3, label: "Raka" }, { value: 1.0, label: "Rundade" }, { value: 1.8, label: "Extra rundade" }]
+ value: Number(prefs.radiusScale)
+ onChosen: (v) => prefs.radiusScale = v
+ }
+ SettingsCard {
+ icon: "refresh"
+ title: "Återställ standardtemat"
+ onActivated: prefs.resetTheme()
+ }
+ }
+}
diff --git a/qml/Toast.qml b/qml/Toast.qml
new file mode 100644
index 0000000..e42b815
--- /dev/null
+++ b/qml/Toast.qml
@@ -0,0 +1,41 @@
+import QtQuick
+import TvLauncher
+
+Rectangle {
+ id: toast
+
+ property bool isError: true
+
+ function show(msg, error) {
+ isError = error !== false
+ label.text = msg
+ opacity = 1
+ hideTimer.restart()
+ }
+
+ anchors { horizontalCenter: parent.horizontalCenter; bottom: parent.bottom; bottomMargin: Theme.dp(90) }
+ width: Math.min(label.implicitWidth + Theme.dp(60), parent.width - Theme.dp(160))
+ height: label.implicitHeight + Theme.dp(30)
+ radius: Theme.r(12)
+ color: Theme.alpha(Theme.surface, 0.92)
+ border.color: isError ? Theme.danger : Theme.accent
+ border.width: Theme.dp(2)
+ opacity: 0
+ visible: opacity > 0
+ z: 1000
+
+ Behavior on opacity { NumberAnimation { duration: 250 } }
+
+ Text {
+ id: label
+ anchors.centerIn: parent
+ width: parent.width - Theme.dp(60)
+ horizontalAlignment: Text.AlignHCenter
+ wrapMode: Text.Wrap
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(24)
+ }
+
+ Timer { id: hideTimer; interval: 5000; onTriggered: toast.opacity = 0 }
+}
diff --git a/qml/TvButton.qml b/qml/TvButton.qml
new file mode 100644
index 0000000..0f05329
--- /dev/null
+++ b/qml/TvButton.qml
@@ -0,0 +1,29 @@
+import QtQuick
+import QtQuick.Controls
+import QtQuick.Layouts
+import TvLauncher
+
+Button {
+ id: btn
+ property bool danger: false
+ Layout.preferredHeight: Theme.dp(60)
+ Layout.preferredWidth: Theme.dp(200)
+ implicitHeight: Theme.dp(60)
+ implicitWidth: Math.max(Theme.dp(200), label.implicitWidth + Theme.dp(48))
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(24)
+ Keys.onReturnPressed: clicked()
+ Keys.onEnterPressed: clicked()
+ contentItem: Text {
+ id: label
+ text: btn.text
+ font: btn.font
+ color: btn.activeFocus && !btn.danger ? Theme.onAccent : Theme.text
+ horizontalAlignment: Text.AlignHCenter
+ verticalAlignment: Text.AlignVCenter
+ }
+ background: Rectangle {
+ radius: Theme.r(8)
+ color: btn.activeFocus ? (btn.danger ? Theme.danger : Theme.accent) : Theme.surfaceHi
+ }
+}
diff --git a/qml/TvMenu.qml b/qml/TvMenu.qml
new file mode 100644
index 0000000..1af6735
--- /dev/null
+++ b/qml/TvMenu.qml
@@ -0,0 +1,42 @@
+import QtQuick
+import QtQuick.Controls
+import TvLauncher
+
+// Mörk meny med tydlig markering, styrs med upp/ner + Enter.
+Menu {
+ id: menu
+
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(26)
+ padding: Theme.dp(10)
+ margins: Theme.dp(20)
+ implicitWidth: Theme.dp(380)
+
+ background: Rectangle {
+ color: Theme.surface
+ radius: Theme.r(14)
+ border.color: Theme.border
+ border.width: Theme.dp(1)
+ }
+
+ delegate: MenuItem {
+ id: item
+ implicitHeight: Theme.dp(64)
+ Keys.onReturnPressed: item.click()
+ Keys.onEnterPressed: item.click()
+ contentItem: Text {
+ leftPadding: Theme.dp(20)
+ text: item.text
+ font: item.font
+ color: item.highlighted ? Theme.onAccent : Theme.text
+ verticalAlignment: Text.AlignVCenter
+ }
+ background: Rectangle {
+ radius: Theme.r(10)
+ color: item.highlighted ? Theme.accent : "transparent"
+ }
+ }
+
+ // Första valet markeras direkt så att man ser var man är med kontrollen.
+ onOpened: currentIndex = 0
+}
diff --git a/qml/WallpaperPage.qml b/qml/WallpaperPage.qml
new file mode 100644
index 0000000..326996a
--- /dev/null
+++ b/qml/WallpaperPage.qml
@@ -0,0 +1,107 @@
+import QtQuick
+import TvLauncher
+
+// Välj bakgrundsbild bland bilder i ~/Bilder, ~/Pictures och systemets mappar.
+Item {
+ id: page
+
+ property var images: []
+
+ function focusFirst() { list.focusFirst() }
+
+ Component.onCompleted: images = prefs.findWallpapers()
+
+ CardList {
+ id: list
+ anchors.fill: parent
+
+ SliderCard {
+ icon: "image"
+ title: "Dämpning av bakgrunden"
+ value: prefs.dim / 0.9
+ valueText: Math.round(prefs.dim * 100) + " %"
+ onMoved: (v) => prefs.dim = v * 0.9
+ }
+ SettingsCard {
+ icon: "image"
+ title: "Ingen bild"
+ subtitle: "Mörk färgtoning"
+ checked: prefs.wallpaper === ""
+ onActivated: prefs.wallpaper = ""
+ }
+
+ SectionTitle { text: "Bilder" }
+ SettingsCard {
+ visible: page.images.length === 0
+ focusable: false
+ icon: "image"
+ title: "Inga bilder hittades"
+ subtitle: "Lägg bilder (jpg/png) i ~/Bilder så dyker de upp här."
+ }
+
+ GridView {
+ id: grid
+ property bool focusable: page.images.length > 0
+ visible: page.images.length > 0
+ width: parent.width
+ readonly property int columns: 4
+ cellWidth: Math.floor(width / columns)
+ cellHeight: Math.round(cellWidth * 0.62)
+ height: Math.ceil(page.images.length / columns) * cellHeight
+ interactive: false // kolumnen runt omkring skrollar
+ keyNavigationEnabled: true // annars stänger interactive:false av piltangenterna
+ model: page.images
+ keyNavigationWraps: false
+
+ onCurrentIndexChanged: if (currentItem) list.ensureRange(y + currentItem.y, cellHeight)
+ onActiveFocusChanged: if (activeFocus && currentItem) list.ensureRange(y + currentItem.y, cellHeight)
+
+ delegate: Item {
+ id: cell
+ required property string modelData
+ required property int index
+ width: grid.cellWidth
+ height: grid.cellHeight
+ readonly property bool current: GridView.isCurrentItem && grid.activeFocus
+
+ Keys.onReturnPressed: prefs.wallpaper = modelData
+ Keys.onEnterPressed: prefs.wallpaper = modelData
+
+ Rectangle {
+ anchors.fill: parent
+ anchors.margins: Theme.dp(8)
+ radius: Theme.r(10)
+ color: Theme.card
+ border.width: cell.current ? Theme.dp(4) : 0
+ border.color: Theme.accent
+ clip: true
+
+ Image {
+ anchors.fill: parent
+ anchors.margins: cell.current ? Theme.dp(4) : 0
+ source: "file://" + cell.modelData
+ sourceSize.width: 400
+ fillMode: Image.PreserveAspectCrop
+ asynchronous: true
+ }
+ Rectangle {
+ visible: prefs.wallpaper === cell.modelData
+ anchors { right: parent.right; top: parent.top; margins: Theme.dp(10) }
+ width: Theme.dp(44); height: width
+ radius: width / 2
+ color: Theme.accent
+ Icon { anchors.centerIn: parent; width: Theme.dp(28); height: width; name: "check" }
+ }
+ }
+ MouseArea {
+ anchors.fill: parent
+ onClicked: {
+ grid.currentIndex = cell.index
+ grid.forceActiveFocus()
+ prefs.wallpaper = cell.modelData
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/qml/WebAppView.qml b/qml/WebAppView.qml
new file mode 100644
index 0000000..6f0a44c
--- /dev/null
+++ b/qml/WebAppView.qml
@@ -0,0 +1,99 @@
+import QtQuick
+import QtWebEngine
+import TvLauncher
+
+// Inbyggd webbapp. Varje app får en egen profil så att inloggningar och
+// cookies sparas och hålls isär (~/.local/share/tv-launcher/QtWebEngine/web-<id>).
+FocusScope {
+ id: view
+
+ property var app: ({})
+ signal closeRequested()
+
+ function back() {
+ if (web.isFullScreen)
+ web.fullScreenCancelled()
+ else if (web.canGoBack)
+ web.goBack()
+ else
+ view.closeRequested()
+ }
+
+ Rectangle { anchors.fill: parent; color: "black" }
+
+ WebEngineProfile {
+ id: profile
+ storageName: "web-" + (view.app.id || "default")
+ // VIKTIGT: utan denna rad blir profilen privat (off-the-record) och
+ // inloggningar/cookies sparas bara i minnet. Varningen "Storage name is
+ // empty ..." i loggen är ofarlig; profilen blir disk-baserad direkt efter.
+ offTheRecord: false
+ persistentCookiesPolicy: WebEngineProfile.ForcePersistentCookies
+ httpUserAgent: view.app.userAgent || ""
+ }
+
+ WebEngineView {
+ id: web
+ anchors.fill: parent
+ focus: true
+ profile: profile
+ url: view.app.url || "about:blank"
+ // Större text på 4K-skärmar.
+ zoomFactor: Math.max(1.0, Theme.s)
+ backgroundColor: "black"
+
+ settings.playbackRequiresUserGesture: false
+ settings.fullScreenSupportEnabled: true
+ settings.showScrollBars: false
+ settings.focusOnNavigationEnabled: true
+
+ onFullScreenRequested: (request) => request.accept()
+ onNewWindowRequested: (request) => { web.url = request.requestedUrl }
+ onLoadingChanged: (info) => {
+ if (info.status === WebEngineView.LoadFailedStatus)
+ errorText.text = "Kunde inte ladda " + info.url + "\n" + info.errorString
+ else if (info.status === WebEngineView.LoadSucceededStatus)
+ errorText.text = ""
+ }
+ }
+
+ Rectangle {
+ anchors { left: parent.left; top: parent.top }
+ height: Theme.dp(4)
+ width: parent.width * web.loadProgress / 100
+ color: Theme.accent
+ visible: web.loading
+ }
+
+ Text {
+ id: errorText
+ anchors.centerIn: parent
+ width: parent.width * 0.7
+ horizontalAlignment: Text.AlignHCenter
+ wrapMode: Text.Wrap
+ visible: text !== ""
+ color: Theme.text
+ font.pixelSize: Theme.dp(28)
+ }
+
+ // Kort hjälptext när appen öppnas.
+ Rectangle {
+ id: hint
+ anchors { horizontalCenter: parent.horizontalCenter; top: parent.top; topMargin: Theme.dp(30) }
+ width: hintText.implicitWidth + Theme.dp(48)
+ height: hintText.implicitHeight + Theme.dp(24)
+ radius: height / 2
+ color: Theme.alpha(Theme.bg, 0.82)
+ opacity: 1
+ Text {
+ id: hintText
+ anchors.centerIn: parent
+ text: "B / Esc: tillbaka · Home: till hemskärmen"
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(22)
+ }
+ Behavior on opacity { NumberAnimation { duration: 600 } }
+ Timer { interval: 4000; running: true; onTriggered: hint.opacity = 0 }
+ }
+}
diff --git a/qml/WifiPage.qml b/qml/WifiPage.qml
new file mode 100644
index 0000000..a14048f
--- /dev/null
+++ b/qml/WifiPage.qml
@@ -0,0 +1,244 @@
+import QtQuick
+import QtQuick.Controls
+import QtQuick.Layouts
+import TvLauncher
+
+// Wi‑Fi via NetworkManager (nmcli).
+Item {
+ id: page
+
+ readonly property bool available: shell.has("nmcli")
+ property bool serviceOk: true
+ property bool enabled: false
+ property var networks: []
+ property var known: []
+ property bool scanning: false
+ property string busySsid: ""
+ property string status: ""
+
+ function focusFirst() { list.focusFirst() }
+
+ // nmcli -t: fält separeras med ':' och ':' i värden skrivs '\:'.
+ function splitTerse(line) {
+ const out = []
+ let cur = ""
+ for (let i = 0; i < line.length; ++i) {
+ const ch = line[i]
+ if (ch === "\\" && i + 1 < line.length) cur += line[++i]
+ else if (ch === ":") { out.push(cur); cur = "" }
+ else cur += ch
+ }
+ out.push(cur)
+ return out
+ }
+
+ function refresh(rescan) {
+ if (!available) return
+ shell.run("nmcli", ["radio", "wifi"], (code, out) => {
+ serviceOk = code === 0
+ enabled = out.trim() === "enabled"
+ }, 8000)
+ shell.run("nmcli", ["-t", "-f", "NAME,TYPE", "connection", "show"], (code, out) => {
+ known = out.split("\n").map(splitTerse).filter(f => f[1] === "802-11-wireless").map(f => f[0])
+ }, 8000)
+ if (rescan) scanning = true
+ shell.run("nmcli", ["-t", "-f", "IN-USE,SIGNAL,SECURITY,SSID", "device", "wifi", "list", "--rescan", rescan ? "yes" : "auto"],
+ (code, out) => {
+ scanning = false
+ if (code !== 0) return
+ const bySsid = {}
+ for (const line of out.split("\n")) {
+ if (line.trim() === "") continue
+ const f = splitTerse(line)
+ const ssid = f.slice(3).join(":")
+ if (ssid === "") continue
+ const n = { ssid: ssid, inUse: f[0] === "*", signal: parseInt(f[1]) || 0,
+ secured: f[2] !== "" && f[2] !== "--" }
+ const old = bySsid[ssid]
+ if (!old || n.inUse || (!old.inUse && n.signal > old.signal)) bySsid[ssid] = n
+ }
+ networks = Object.values(bySsid).sort((a, b) => (b.inUse - a.inUse) || (b.signal - a.signal))
+ }, 30000)
+ }
+
+ function bars(signal) {
+ return signal > 75 ? "▂▄▆█" : signal > 50 ? "▂▄▆" : signal > 25 ? "▂▄" : "▂"
+ }
+
+ function finish(ssid, code, out, err) {
+ busySsid = ""
+ status = code === 0 ? "Ansluten till " + ssid
+ : "Kunde inte ansluta: " + ((err || out).trim().split("\n").pop() || "okänt fel")
+ refresh(false)
+ }
+
+ function activate(n) {
+ if (busySsid !== "" || n.inUse) return
+ if (page.known.indexOf(n.ssid) >= 0) {
+ busySsid = n.ssid
+ status = "Ansluter till " + n.ssid + " ..."
+ shell.run("nmcli", ["connection", "up", "id", n.ssid], (c, o, e) => finish(n.ssid, c, o, e), 45000)
+ } else if (!n.secured) {
+ busySsid = n.ssid
+ status = "Ansluter till " + n.ssid + " ..."
+ shell.run("nmcli", ["device", "wifi", "connect", n.ssid], (c, o, e) => finish(n.ssid, c, o, e), 45000)
+ } else {
+ passwordDialog.ssid = n.ssid
+ passwordDialog.open()
+ }
+ }
+
+ function connectWithPassword(ssid, password) {
+ busySsid = ssid
+ status = "Ansluter till " + ssid + " ..."
+ shell.run("nmcli", ["device", "wifi", "connect", ssid, "password", password],
+ (c, o, e) => finish(ssid, c, o, e), 45000)
+ }
+
+ function forget(n) {
+ if (page.known.indexOf(n.ssid) < 0) return
+ shell.run("nmcli", ["connection", "delete", "id", n.ssid], () => { status = "Glömde " + n.ssid; refresh(false) }, 8000)
+ }
+
+ Component.onCompleted: refresh(false)
+ Timer { interval: 10000; running: page.available && page.visible; repeat: true; onTriggered: page.refresh(false) }
+
+ CardList {
+ id: list
+ anchors.fill: parent
+
+ SettingsCard {
+ visible: !page.available
+ icon: "wifi"
+ title: "NetworkManager saknas"
+ subtitle: "Installera med:\nsudo apt install network-manager\nOm Wi‑Fi är inställt i /etc/network/interfaces behöver det tas bort därifrån."
+ }
+ SettingsCard {
+ visible: page.available && !page.serviceOk
+ icon: "wifi"
+ title: "NetworkManager svarar inte"
+ subtitle: "Starta den med: sudo systemctl enable --now NetworkManager"
+ onActivated: page.refresh(false)
+ }
+ SettingsCard {
+ visible: page.available && page.serviceOk
+ icon: "wifi"
+ title: "Wi‑Fi"
+ subtitle: page.enabled ? "På" : "Av"
+ toggle: page.enabled
+ onActivated: shell.run("nmcli", ["radio", "wifi", page.enabled ? "off" : "on"], () => page.refresh(false))
+ }
+ SettingsCard {
+ visible: page.available && page.serviceOk && page.enabled
+ icon: "refresh"
+ title: page.scanning ? "Söker ..." : "Sök efter nätverk"
+ busy: page.scanning
+ onActivated: page.refresh(true)
+ }
+ Text {
+ width: parent.width
+ visible: page.status !== ""
+ text: page.status
+ color: Theme.accent
+ wrapMode: Text.Wrap
+ topPadding: Theme.dp(10)
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(24)
+ }
+
+ SectionTitle {
+ visible: page.enabled && page.networks.length > 0
+ text: "Nätverk"
+ }
+ Repeater {
+ model: page.enabled ? page.networks : []
+ delegate: SettingsCard {
+ required property var modelData
+ icon: modelData.secured ? "lock" : "wifi"
+ title: modelData.ssid
+ subtitle: modelData.inUse ? "Ansluten"
+ : page.known.indexOf(modelData.ssid) >= 0 ? "Sparat · Y: glöm"
+ : modelData.secured ? "Skyddat" : "Öppet"
+ valueText: page.bars(modelData.signal)
+ checked: modelData.inUse
+ busy: page.busySsid === modelData.ssid
+ onActivated: page.activate(modelData)
+ onMenuRequested: page.forget(modelData)
+ }
+ }
+ }
+
+ Popup {
+ id: passwordDialog
+ property string ssid
+ parent: Overlay.overlay
+ anchors.centerIn: parent
+ width: Math.min(parent.width - Theme.dp(120), Theme.dp(900))
+ modal: true
+ focus: true
+ padding: Theme.dp(40)
+ background: Rectangle { color: Theme.bg; radius: Theme.r(18); border.color: Theme.borderSoft }
+ Overlay.modal: Rectangle { color: Theme.scrim }
+ onOpened: { pw.text = ""; pw.forceActiveFocus() }
+
+ function submit() {
+ if (pw.text.length < 8) return
+ close()
+ page.connectWithPassword(ssid, pw.text)
+ }
+
+ contentItem: ColumnLayout {
+ spacing: Theme.dp(20)
+ Text {
+ text: "Lösenord för " + passwordDialog.ssid
+ color: Theme.text
+ font.family: Theme.fontFamily
+ font.pixelSize: Theme.dp(32)
+ }
+ TextField {
+ id: pw
+ Layout.fillWidth: true
+ Layout.preferredHeight: Theme.dp(64)
+ echoMode: showPw.checked ? TextInput.Normal : TextInput.Password
+ color: Theme.text
+ font.pixelSize: Theme.dp(28)
+ leftPadding: Theme.dp(16)
+ KeyNavigation.down: showPw
+ onAccepted: passwordDialog.submit()
+ background: Rectangle {
+ radius: Theme.r(8)
+ color: pw.activeFocus ? Theme.surfaceHi : Theme.surface
+ border.width: pw.activeFocus ? Theme.dp(3) : Theme.dp(1)
+ border.color: pw.activeFocus ? Theme.accent : Theme.border
+ }
+ }
+ SettingsCard {
+ id: showPw
+ property bool checked: false
+ Layout.fillWidth: true
+ title: "Visa lösenordet"
+ toggle: checked
+ onActivated: checked = !checked
+ KeyNavigation.up: pw
+ KeyNavigation.down: connectBtn
+ }
+ RowLayout {
+ spacing: Theme.dp(20)
+ TvButton {
+ id: connectBtn
+ text: "Anslut"
+ enabled: pw.text.length >= 8
+ onClicked: passwordDialog.submit()
+ KeyNavigation.up: showPw
+ KeyNavigation.right: cancelBtn
+ }
+ TvButton {
+ id: cancelBtn
+ text: "Avbryt"
+ onClicked: passwordDialog.close()
+ KeyNavigation.up: showPw
+ }
+ }
+ }
+ }
+}
diff --git a/qml/icons/add.svg b/qml/icons/add.svg
new file mode 100644
index 0000000..6921178
--- /dev/null
+++ b/qml/icons/add.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M12 4v16M4 12h16"/></svg>
diff --git a/qml/icons/apps.svg b/qml/icons/apps.svg
new file mode 100644
index 0000000..a56cda8
--- /dev/null
+++ b/qml/icons/apps.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><circle cx="5" cy="5" r="1.3" fill="#fff"/><circle cx="12" cy="5" r="1.3" fill="#fff"/><circle cx="19" cy="5" r="1.3" fill="#fff"/><circle cx="5" cy="12" r="1.3" fill="#fff"/><circle cx="12" cy="12" r="1.3" fill="#fff"/><circle cx="19" cy="12" r="1.3" fill="#fff"/><circle cx="5" cy="19" r="1.3" fill="#fff"/><circle cx="12" cy="19" r="1.3" fill="#fff"/><circle cx="19" cy="19" r="1.3" fill="#fff"/></svg>
diff --git a/qml/icons/bluetooth.svg b/qml/icons/bluetooth.svg
new file mode 100644
index 0000000..3197651
--- /dev/null
+++ b/qml/icons/bluetooth.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M7 7l10 10-5 5V2l5 5L7 17"/></svg>
diff --git a/qml/icons/check.svg b/qml/icons/check.svg
new file mode 100644
index 0000000..6871b4f
--- /dev/null
+++ b/qml/icons/check.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12.5l4.5 4.5L19 7.5"/></svg>
diff --git a/qml/icons/device.svg b/qml/icons/device.svg
new file mode 100644
index 0000000..1f355d2
--- /dev/null
+++ b/qml/icons/device.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="2.5" width="10" height="19" rx="2"/><path d="M11 18.5h2"/></svg>
diff --git a/qml/icons/edit.svg b/qml/icons/edit.svg
new file mode 100644
index 0000000..7066b91
--- /dev/null
+++ b/qml/icons/edit.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20l4.2-1L19 8.2 15.8 5 5 15.8z"/><path d="M13.8 7l3.2 3.2"/></svg>
diff --git a/qml/icons/gamepad.svg b/qml/icons/gamepad.svg
new file mode 100644
index 0000000..46b6c92
--- /dev/null
+++ b/qml/icons/gamepad.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M7 7.5h10a4.5 4.5 0 0 1 4.5 4.5v2.2a3 3 0 0 1-5.3 1.9L14.8 14.5H9.2l-1.4 1.6A3 3 0 0 1 2.5 14.2V12A4.5 4.5 0 0 1 7 7.5z"/><path d="M7.5 10.2v3.6M5.7 12h3.6"/><circle cx="15.8" cy="11" r=".9" fill="#fff"/><circle cx="17.8" cy="13" r=".9" fill="#fff"/></svg>
diff --git a/qml/icons/globe.svg b/qml/icons/globe.svg
new file mode 100644
index 0000000..3abfdb1
--- /dev/null
+++ b/qml/icons/globe.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="9"/><ellipse cx="12" cy="12" rx="4" ry="9"/><path d="M3 12h18"/></svg>
diff --git a/qml/icons/headphones.svg b/qml/icons/headphones.svg
new file mode 100644
index 0000000..e0349c8
--- /dev/null
+++ b/qml/icons/headphones.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M4 15v-3a8 8 0 0 1 16 0v3"/><rect x="3" y="14" width="4" height="6" rx="1.5"/><rect x="17" y="14" width="4" height="6" rx="1.5"/></svg>
diff --git a/qml/icons/home.svg b/qml/icons/home.svg
new file mode 100644
index 0000000..97d1cce
--- /dev/null
+++ b/qml/icons/home.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M3.5 11L12 4l8.5 7"/><path d="M5.5 9.5V20h13V9.5"/><path d="M10 20v-5h4v5"/></svg>
diff --git a/qml/icons/image.svg b/qml/icons/image.svg
new file mode 100644
index 0000000..7a456fd
--- /dev/null
+++ b/qml/icons/image.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><circle cx="8.5" cy="10" r="1.6"/><path d="M21 16l-5-5-9 8"/></svg>
diff --git a/qml/icons/keyboard.svg b/qml/icons/keyboard.svg
new file mode 100644
index 0000000..38c5b5e
--- /dev/null
+++ b/qml/icons/keyboard.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><rect x="2.5" y="6" width="19" height="12" rx="2"/><path d="M6 10h.01M9 10h.01M12 10h.01M15 10h.01M18 10h.01M6 14h.01M18 14h.01M9 14h6"/></svg>
diff --git a/qml/icons/lock.svg b/qml/icons/lock.svg
new file mode 100644
index 0000000..c2b45a6
--- /dev/null
+++ b/qml/icons/lock.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><rect x="5.5" y="11" width="13" height="9" rx="2"/><path d="M8.5 11V8a3.5 3.5 0 0 1 7 0v3"/></svg>
diff --git a/qml/icons/palette.svg b/qml/icons/palette.svg
new file mode 100644
index 0000000..5910060
--- /dev/null
+++ b/qml/icons/palette.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3a9 9 0 1 0 0 18c1.4 0 2-1 2-2 0-1.4-1.2-1.6-1.2-2.8 0-1 .8-1.7 1.8-1.7H17a4 4 0 0 0 4-4C21 6.4 17 3 12 3z"/><circle cx="7.5" cy="11" r="1.2" fill="#fff"/><circle cx="10" cy="7" r="1.2" fill="#fff"/><circle cx="14.5" cy="7" r="1.2" fill="#fff"/></svg>
diff --git a/qml/icons/power.svg b/qml/icons/power.svg
new file mode 100644
index 0000000..7bc0b04
--- /dev/null
+++ b/qml/icons/power.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3v8"/><path d="M7.2 6.2a8 8 0 1 0 9.6 0"/></svg>
diff --git a/qml/icons/refresh.svg b/qml/icons/refresh.svg
new file mode 100644
index 0000000..ee4d262
--- /dev/null
+++ b/qml/icons/refresh.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M20 12a8 8 0 1 1-2.4-5.7"/><path d="M20 4v5h-5"/></svg>
diff --git a/qml/icons/search.svg b/qml/icons/search.svg
new file mode 100644
index 0000000..6c49bed
--- /dev/null
+++ b/qml/icons/search.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><circle cx="10.5" cy="10.5" r="6.5"/><path d="M15.5 15.5L21 21"/></svg>
diff --git a/qml/icons/settings.svg b/qml/icons/settings.svg
new file mode 100644
index 0000000..bbd159a
--- /dev/null
+++ b/qml/icons/settings.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8h10M17 8h4M3 16h3M10 16h11"/><circle cx="15" cy="8" r="2"/><circle cx="8" cy="16" r="2"/></svg>
diff --git a/qml/icons/speaker.svg b/qml/icons/speaker.svg
new file mode 100644
index 0000000..657391a
--- /dev/null
+++ b/qml/icons/speaker.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><rect x="6" y="3" width="12" height="18" rx="2"/><circle cx="12" cy="14" r="3.5"/><circle cx="12" cy="7.5" r="1" fill="#fff"/></svg>
diff --git a/qml/icons/volume-mute.svg b/qml/icons/volume-mute.svg
new file mode 100644
index 0000000..67b0c96
--- /dev/null
+++ b/qml/icons/volume-mute.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M3.5 9.5h3.5l5-4v13l-5-4H3.5z" fill="#ffffff"/><path d="M16 9.5l5 5M21 9.5l-5 5"/></svg>
diff --git a/qml/icons/volume.svg b/qml/icons/volume.svg
new file mode 100644
index 0000000..e338424
--- /dev/null
+++ b/qml/icons/volume.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M3.5 9.5h3.5l5-4v13l-5-4H3.5z" fill="#ffffff"/><path d="M15.5 9a4.2 4.2 0 0 1 0 6M18.2 6.3a8 8 0 0 1 0 11.4"/></svg>
diff --git a/qml/icons/wifi.svg b/qml/icons/wifi.svg
new file mode 100644
index 0000000..2d59368
--- /dev/null
+++ b/qml/icons/wifi.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="96" height="96" fill="none" stroke="#ffffff" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M2.5 9a14 14 0 0 1 19 0M5.5 12.5a9.5 9.5 0 0 1 13 0M8.5 16a5 5 0 0 1 7 0"/><circle cx="12" cy="19.3" r="1.1" fill="#ffffff" stroke="none"/></svg>
diff --git a/scripts/setup-adguard.sh b/scripts/setup-adguard.sh
new file mode 100755
index 0000000..f1c68e8
--- /dev/null
+++ b/scripts/setup-adguard.sh
@@ -0,0 +1,198 @@
+#!/bin/bash
+# Installerar AdGuard Home som reklam- och spårningsblockerande DNS för
+# den här datorn (lyssnar bara på 127.0.0.1).
+#
+# sudo ~/tv-launcher/scripts/setup-adguard.sh installera
+# sudo ~/tv-launcher/scripts/setup-adguard.sh uninstall ta bort och återställ DNS
+#
+# Webbgränssnitt: http://127.0.0.1 (lösenordet sparas i
+# ~/.config/tv-launcher/adguard.txt)
+set -euo pipefail
+
+ACTION="${1:-install}"
+INSTALL_DIR=/opt/AdGuardHome
+RESOLV_BACKUP=/etc/resolv.conf.tv-launcher-backup
+NM_CONF=/etc/NetworkManager/conf.d/90-tv-launcher-dns.conf
+DHCPCD_MARK="# tv-launcher: AdGuard Home sköter DNS"
+FALLBACK_DNS=9.9.9.9
+
+download() { # download <katalog>: hämtar senaste versionen och kontrollerar checksumman
+ python3 -I - "$1" <<'PY'
+import hashlib, json, os, sys, tarfile, urllib.request
+dest = sys.argv[1]
+ua = {"User-Agent": "tv-launcher-setup"}
+def get(url):
+ return urllib.request.urlopen(urllib.request.Request(url, headers=ua), timeout=60).read()
+rel = json.loads(get("https://api.github.com/repos/AdguardTeam/AdGuardHome/releases/latest"))
+tag = rel["tag_name"]
+base = f"https://github.com/AdguardTeam/AdGuardHome/releases/download/{tag}/"
+name = "AdGuardHome_linux_amd64.tar.gz"
+data = get(base + name)
+sums = get(base + "checksums.txt").decode()
+want = next(l.split()[0] for l in sums.splitlines() if l.strip().endswith(name))
+if hashlib.sha256(data).hexdigest() != want:
+ sys.exit("Fel checksumma, avbryter")
+tar_path = os.path.join(dest, name)
+open(tar_path, "wb").write(data)
+with tarfile.open(tar_path) as t:
+ member = t.getmember("./AdGuardHome/AdGuardHome")
+ member.name = "AdGuardHome"
+ t.extract(member, dest, filter="data")
+print(f"AdGuard Home {tag} hämtad och kontrollerad")
+PY
+}
+
+if [ "$ACTION" = "--download-test" ]; then # för test utan root
+ download "$2"
+ exit 0
+fi
+
+if [ "$(id -u)" -ne 0 ]; then
+ echo "Kör med sudo: sudo $0 $ACTION" >&2
+ exit 1
+fi
+
+TARGET_USER="${SUDO_USER:-$(logname 2>/dev/null || echo root)}"
+USER_HOME="$(getent passwd "$TARGET_USER" | cut -d: -f6)"
+PASS_FILE="$USER_HOME/.config/tv-launcher/adguard.txt"
+
+restore_dns() {
+ if [ -f "$RESOLV_BACKUP" ]; then
+ cp "$RESOLV_BACKUP" /etc/resolv.conf
+ rm -f "$RESOLV_BACKUP"
+ fi
+ if [ -f /etc/dhcpcd.conf ] && grep -q "$DHCPCD_MARK" /etc/dhcpcd.conf; then
+ sed -i "/$DHCPCD_MARK/,+1d" /etc/dhcpcd.conf
+ fi
+ rm -f "$NM_CONF"
+ systemctl reload NetworkManager 2>/dev/null || true
+}
+
+if [ "$ACTION" = "uninstall" ]; then
+ restore_dns
+ if [ -x "$INSTALL_DIR/AdGuardHome" ]; then
+ "$INSTALL_DIR/AdGuardHome" -s uninstall || true
+ fi
+ rm -rf "$INSTALL_DIR"
+ rm -f "$PASS_FILE"
+ echo "AdGuard Home borttagen och DNS återställd."
+ exit 0
+fi
+
+# ---------------------------------------------------------------- installera
+if systemctl is-active --quiet AdGuardHome 2>/dev/null; then
+ echo "AdGuard Home är redan installerat. Ta bort först med: sudo $0 uninstall" >&2
+ exit 1
+fi
+
+WORK="$(mktemp -d)"
+trap 'rm -rf "$WORK"' EXIT
+echo "==> Hämtar AdGuard Home"
+download "$WORK"
+
+echo "==> Installerar i $INSTALL_DIR"
+install -d -m 755 "$INSTALL_DIR"
+install -m 755 "$WORK/AdGuardHome" "$INSTALL_DIR/AdGuardHome"
+"$INSTALL_DIR/AdGuardHome" -s install -w "$INSTALL_DIR"
+
+echo "==> Ställer in (bara lokalt, krypterad DNS uppströms, blockeringslistor)"
+PASSWORD="$(python3 -I -c 'import secrets; print(secrets.token_urlsafe(12))')"
+python3 -I - "$PASSWORD" <<'PY'
+import base64, json, sys, time, urllib.request
+pw = sys.argv[1]
+# Guiden körs på port 3000; det färdiga webbgränssnittet på port 80
+# (samma port som guiden går inte, den är upptagen av guiden själv).
+def call(path, body, auth=False, port=80):
+ req = urllib.request.Request(f"http://127.0.0.1:{port}" + path, data=json.dumps(body).encode(),
+ headers={"Content-Type": "application/json"}, method="POST")
+ if auth:
+ req.add_header("Authorization", "Basic " + base64.b64encode(f"admin:{pw}".encode()).decode())
+ return urllib.request.urlopen(req, timeout=30).read()
+
+# Vänta på installationsguiden
+for _ in range(60):
+ try:
+ urllib.request.urlopen("http://127.0.0.1:3000/control/install/get_addresses", timeout=2)
+ break
+ except Exception:
+ time.sleep(1)
+else:
+ sys.exit("AdGuard Home startade inte")
+
+call("/control/install/configure", {
+ "web": {"ip": "127.0.0.1", "port": 80},
+ "dns": {"ip": "127.0.0.1", "port": 53},
+ "username": "admin", "password": pw,
+}, port=3000)
+
+# Efter guiden startar den om; vänta på inloggat API
+for _ in range(60):
+ try:
+ call("/control/dns_config", {
+ "upstream_dns": ["https://dns.quad9.net/dns-query", "https://cloudflare-dns.com/dns-query"],
+ "bootstrap_dns": ["9.9.9.9", "1.1.1.1"],
+ "upstream_mode": "parallel",
+ }, auth=True)
+ break
+ except Exception:
+ time.sleep(1)
+else:
+ sys.exit("Kunde inte ställa in DNS-servrar")
+
+for name, url in [("OISD small", "https://small.oisd.nl/"),
+ ("AdAway", "https://adaway.org/hosts.txt")]:
+ try:
+ call("/control/filtering/add_url", {"name": name, "url": url, "whitelist": False}, auth=True)
+ except Exception as e:
+ print(f" (kunde inte lägga till {name}: {e})")
+print(" klart")
+PY
+
+echo "==> Testar att AdGuard svarar"
+python3 -I - <<'PY'
+import socket, struct, sys, time
+def query(name):
+ q = struct.pack(">HHHHHH", 0x1234, 0x0100, 1, 0, 0, 0)
+ q += b"".join(bytes([len(p)]) + p.encode() for p in name.split(".")) + b"\0" + struct.pack(">HH", 1, 1)
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM); s.settimeout(5)
+ s.sendto(q, ("127.0.0.1", 53)); r = s.recv(512)
+ return struct.unpack(">H", r[6:8])[0] # antal svar
+for _ in range(10):
+ try:
+ if query("debian.org") > 0:
+ print(" debian.org slås upp korrekt")
+ sys.exit(0)
+ except Exception:
+ pass
+ time.sleep(2)
+sys.exit("AdGuard svarar inte; DNS-inställningen lämnas orörd")
+PY
+
+echo "==> Pekar datorns DNS till AdGuard Home"
+[ -f "$RESOLV_BACKUP" ] || cp -P /etc/resolv.conf "$RESOLV_BACKUP"
+if [ -f /etc/dhcpcd.conf ] && ! grep -q "$DHCPCD_MARK" /etc/dhcpcd.conf; then
+ printf '\n%s\nnohook resolv.conf\n' "$DHCPCD_MARK" >> /etc/dhcpcd.conf
+fi
+if [ -d /etc/NetworkManager/conf.d ]; then
+ printf '# tv-launcher: AdGuard Home sköter DNS\n[main]\ndns=none\n' > "$NM_CONF"
+ systemctl reload NetworkManager 2>/dev/null || true
+fi
+rm -f /etc/resolv.conf
+cat > /etc/resolv.conf <<EOF
+# tv-launcher: AdGuard Home (http://127.0.0.1)
+# Reserv om AdGuard inte svarar. Återställ med: sudo $0 uninstall
+nameserver 127.0.0.1
+nameserver $FALLBACK_DNS
+options timeout:2 attempts:2
+EOF
+
+install -d -o "$TARGET_USER" -g "$TARGET_USER" "$(dirname "$PASS_FILE")"
+printf 'Webbgränssnitt: http://127.0.0.1\nAnvändare: admin\nLösenord: %s\n' "$PASSWORD" > "$PASS_FILE"
+chown "$TARGET_USER:" "$PASS_FILE"
+chmod 600 "$PASS_FILE"
+
+echo
+echo "Klart! AdGuard Home blockerar nu reklam och spårare på den här datorn."
+echo " Webbgränssnitt: http://127.0.0.1 (lägg gärna till som webbapp i launchern)"
+echo " Användare: admin Lösenord: $PASSWORD"
+echo " (sparat i $PASS_FILE)"
diff --git a/scripts/setup-uinput.sh b/scripts/setup-uinput.sh
new file mode 100755
index 0000000..ae96bc7
--- /dev/null
+++ b/scripts/setup-uinput.sh
@@ -0,0 +1,24 @@
+#!/bin/sh
+# Ger den inloggade användaren rätt att skapa en virtuell mus/tangentbord
+# (/dev/uinput). Behövs för att styra webbappar och program med handkontrollen.
+# Kör en gång: sudo ~/tv-launcher/scripts/setup-uinput.sh
+set -e
+if [ "$(id -u)" -ne 0 ]; then
+ echo "Kör med sudo: sudo $0" >&2
+ exit 1
+fi
+
+cat > /etc/udev/rules.d/70-tv-launcher-uinput.rules <<'RULE'
+# tv-launcher: låt användaren i den aktiva sessionen skapa virtuella indataenheter
+KERNEL=="uinput", SUBSYSTEM=="misc", OPTIONS+="static_node=uinput", TAG+="uaccess"
+RULE
+
+echo uinput > /etc/modules-load.d/tv-launcher-uinput.conf
+modprobe uinput 2>/dev/null || true
+udevadm control --reload-rules
+udevadm trigger --action=change --sysname-match=uinput
+sleep 1
+ls -l /dev/uinput
+echo
+echo "Klart. Starta om launchern (Ström -> Starta om launchern)."
+echo "Om det inte fungerar: starta om datorn en gång."
diff --git a/scripts/tv-session.sh b/scripts/tv-session.sh
new file mode 100755
index 0000000..2559fe3
--- /dev/null
+++ b/scripts/tv-session.sh
@@ -0,0 +1,26 @@
+#!/bin/sh
+# Startar TV-launchern i cage. Körs från tty1 (se README.md).
+# Program som launchern startar ärver WAYLAND_DISPLAY och visas av cage i helskärm.
+
+export XDG_SESSION_TYPE=wayland
+export QT_QPA_PLATFORM=wayland
+export QT_WAYLAND_DISABLE_WINDOWDECORATION=1
+export SDL_VIDEODRIVER=wayland
+export MOZ_ENABLE_WAYLAND=1
+export LIBVA_DRIVER_NAME=iHD
+
+# Samma tangentbordslayout som resten av systemet (t.ex. svensk), annars kör
+# cage med amerikansk layout och åäö saknas.
+if [ -r /etc/default/keyboard ]; then
+ . /etc/default/keyboard
+ export XKB_DEFAULT_MODEL="${XKBMODEL:-pc105}"
+ export XKB_DEFAULT_LAYOUT="${XKBLAYOUT:-se}"
+ [ -n "${XKBVARIANT:-}" ] && export XKB_DEFAULT_VARIANT="$XKBVARIANT"
+ [ -n "${XKBOPTIONS:-}" ] && export XKB_DEFAULT_OPTIONS="$XKBOPTIONS"
+fi
+
+LAUNCHER="${TV_LAUNCHER:-$HOME/.local/bin/tv-launcher}"
+
+# -d: inga fönsterramar, -s: tillåt Ctrl+Alt+F2 för att nå en terminal.
+# Launchern startas om automatiskt om den kraschar (avslutas med kod != 0).
+exec cage -d -s -- sh -c "until \"$LAUNCHER\"; do sleep 1; done"
diff --git a/src/appstore.cpp b/src/appstore.cpp
new file mode 100644
index 0000000..9d8c8b9
--- /dev/null
+++ b/src/appstore.cpp
@@ -0,0 +1,381 @@
+#include "appstore.h"
+
+#include <QDateTime>
+#include <QSet>
+#include <QDir>
+#include <algorithm>
+#include <QFile>
+#include <QJsonArray>
+#include <QJsonDocument>
+#include <QJsonObject>
+#include <QSaveFile>
+#include <QStandardPaths>
+#include <QUrl>
+#include <QUuid>
+
+static const QStringList kKnownCategories{"Media", "Musik", "Spel", "Webb", "Program"};
+
+AppStore::AppStore(QObject *parent) : QObject(parent)
+{
+ const QString dir = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
+ QDir().mkpath(dir);
+ m_path = dir + "/apps.json";
+ load();
+
+ QString base = qEnvironmentVariable("TV_MEDIA_DIR");
+ if (base.isEmpty()) {
+ const QString bilder = QDir::homePath() + "/Bilder";
+ base = (QDir(bilder).exists() ? bilder
+ : QStandardPaths::writableLocation(QStandardPaths::PicturesLocation)) + "/TV";
+ }
+ m_iconDir = base + "/Ikoner";
+ m_previewDir = base + QString::fromUtf8("/Förhandsbilder");
+ QDir().mkpath(m_iconDir);
+ QDir().mkpath(m_previewDir);
+ m_mediaWatcher.addPaths({m_iconDir, m_previewDir});
+ connect(&m_mediaWatcher, &QFileSystemWatcher::directoryChanged, this, [this] {
+ scanMediaFolders();
+ bump();
+ });
+ scanMediaFolders();
+}
+
+QString AppStore::normalizeName(const QString &s)
+{
+ QString out;
+ for (const QChar c : s.toLower())
+ if (c.isLetterOrNumber())
+ out += c;
+ return out;
+}
+
+void AppStore::scanMediaFolders()
+{
+ auto scan = [](const QString &dir) {
+ QHash<QString, QString> map;
+ const auto files = QDir(dir).entryInfoList({"*.png", "*.jpg", "*.jpeg", "*.webp", "*.svg"}, QDir::Files);
+ for (const QFileInfo &fi : files)
+ map.insert(normalizeName(fi.completeBaseName()), fi.absoluteFilePath());
+ return map;
+ };
+ m_iconFiles = scan(m_iconDir);
+ m_previewFiles = scan(m_previewDir);
+}
+
+// Lägger på ikon och förhandsbild från mapparna. En ikonfil vinner alltid
+// (den har lagts dit med flit); en förhandsbild bara om ingen annan är vald.
+QVariantMap AppStore::decorate(QVariantMap app) const
+{
+ const QString byName = normalizeName(app.value("name").toString());
+ const QString byId = normalizeName(app.value("id").toString());
+ const QString icon = m_iconFiles.value(byName, m_iconFiles.value(byId));
+ if (!icon.isEmpty())
+ app["icon"] = icon;
+ if (app.value("heroImage").toString().isEmpty()) {
+ const QString preview = m_previewFiles.value(byName, m_previewFiles.value(byId));
+ if (!preview.isEmpty())
+ app["heroImage"] = preview;
+ }
+ return app;
+}
+
+QStringList AppStore::knownCategories() const { return kKnownCategories; }
+
+QString AppStore::tvUserAgent() const
+{
+ // En smart-TV-UA gör att t.ex. youtube.com/tv visar sitt TV-gränssnitt.
+ return QStringLiteral("Mozilla/5.0 (SMART-TV; Linux; Tizen 6.0) AppleWebKit/537.36 "
+ "(KHTML, like Gecko) 76.0.3809.146/6.0 TV Safari/537.36");
+}
+
+QStringList AppStore::categories() const
+{
+ // Kända kategorier först i fast ordning, sedan egna, bara de som har appar.
+ QStringList present;
+ for (const auto &a : m_apps) {
+ const QString c = a.value("category").toString();
+ if (!present.contains(c))
+ present << c;
+ }
+ QStringList out;
+ for (const QString &c : kKnownCategories)
+ if (present.contains(c))
+ out << c;
+ for (const QString &c : present)
+ if (!out.contains(c))
+ out << c;
+ return out;
+}
+
+QVariantList AppStore::appsIn(const QString &category) const
+{
+ QVariantList out;
+ for (const auto &a : m_apps)
+ if (a.value("category").toString() == category)
+ out << decorate(a);
+ return out;
+}
+
+int AppStore::indexOf(const QString &id) const
+{
+ for (int i = 0; i < m_apps.size(); ++i)
+ if (m_apps[i].value("id").toString() == id)
+ return i;
+ return -1;
+}
+
+QVariantMap AppStore::get(const QString &id) const
+{
+ const int i = indexOf(id);
+ return i < 0 ? QVariantMap{} : decorate(m_apps[i]);
+}
+
+QString AppStore::save(const QVariantMap &input)
+{
+ QVariantMap app;
+ app["id"] = input.value("id").toString();
+ app["name"] = input.value("name").toString().trimmed();
+ app["type"] = input.value("type").toString() == "web" ? "web" : "app";
+ app["command"] = input.value("command").toString().trimmed();
+ app["engine"] = input.value("engine").toString() == "chromium" ? "chromium" : "builtin";
+ app["icon"] = input.value("icon").toString().trimmed();
+ app["userAgent"] = input.value("userAgent").toString();
+ if (input.contains("controllerMode"))
+ app["controllerMode"] = input.value("controllerMode").toString();
+ QString category = input.value("category").toString().trimmed();
+ app["category"] = category.isEmpty() ? (app["type"] == "web" ? "Webb" : "Program") : category;
+
+ QString url = input.value("url").toString().trimmed();
+ if (!url.isEmpty() && !url.contains("://"))
+ url.prepend("https://");
+ app["url"] = url;
+
+ QString id = app["id"].toString();
+ if (id.isEmpty()) {
+ id = QUuid::createUuid().toString(QUuid::WithoutBraces).left(8);
+ app["id"] = id;
+ m_apps << app;
+ } else {
+ const int i = indexOf(id);
+ if (i < 0) {
+ m_apps << app;
+ } else {
+ // Behåll fält som redigeraren inte känner till (lastUsed, utseende ...).
+ QVariantMap merged = m_apps[i];
+ for (auto it = app.cbegin(); it != app.cend(); ++it)
+ merged.insert(it.key(), it.value());
+ m_apps[i] = merged;
+ }
+ }
+ persist();
+ bump();
+
+ if (app["type"] == "web" && app["icon"].toString().isEmpty() && !url.isEmpty())
+ emit iconWanted(id, url);
+ return id;
+}
+
+void AppStore::remove(const QString &id)
+{
+ const int i = indexOf(id);
+ if (i < 0)
+ return;
+ // Borttagen Chromium-app ska inte läggas till igen vid nästa sökning.
+ const QString crx = m_apps[i].value("chromiumAppId").toString();
+ if (!crx.isEmpty() && !m_ignoredChromium.contains(crx))
+ m_ignoredChromium << crx;
+ m_apps.removeAt(i);
+ persist();
+ bump();
+}
+
+void AppStore::move(const QString &id, int delta)
+{
+ // Flyttar appen förbi närmaste granne i samma kategori.
+ const int i = indexOf(id);
+ if (i < 0 || delta == 0)
+ return;
+ const QString cat = m_apps[i].value("category").toString();
+ const int step = delta > 0 ? 1 : -1;
+ for (int j = i + step; j >= 0 && j < m_apps.size(); j += step) {
+ if (m_apps[j].value("category").toString() == cat) {
+ m_apps.swapItemsAt(i, j);
+ persist();
+ bump();
+ return;
+ }
+ }
+}
+
+void AppStore::setIconIfEmpty(const QString &id, const QString &iconPath)
+{
+ const int i = indexOf(id);
+ if (i < 0 || !m_apps[i].value("icon").toString().isEmpty())
+ return;
+ m_apps[i]["icon"] = iconPath;
+ persist();
+ bump();
+}
+
+void AppStore::patch(const QString &id, const QVariantMap &fields)
+{
+ const int i = indexOf(id);
+ if (i < 0)
+ return;
+ for (auto it = fields.cbegin(); it != fields.cend(); ++it) {
+ if (it.value().isNull() || (it.value().typeId() == QMetaType::QString && it.value().toString().isEmpty()))
+ m_apps[i].remove(it.key());
+ else
+ m_apps[i].insert(it.key(), it.value());
+ }
+ persist();
+ bump();
+}
+
+void AppStore::markUsed(const QString &id)
+{
+ const int i = indexOf(id);
+ if (i < 0)
+ return;
+ m_apps[i]["lastUsed"] = QDateTime::currentMSecsSinceEpoch();
+ persist();
+ bump();
+}
+
+QVariantList AppStore::recent(int max) const
+{
+ QList<QVariantMap> used;
+ for (const auto &a : m_apps)
+ if (a.value("lastUsed").toLongLong() > 0)
+ used << a;
+ std::sort(used.begin(), used.end(), [](const QVariantMap &a, const QVariantMap &b) {
+ return a.value("lastUsed").toLongLong() > b.value("lastUsed").toLongLong();
+ });
+ QVariantList out;
+ for (int i = 0; i < used.size() && i < max; ++i)
+ out << decorate(used[i]);
+ return out;
+}
+
+QStringList AppStore::syncChromiumApps(const QList<QVariantMap> &found)
+{
+ QStringList added;
+ QSet<QString> present;
+ bool dirty = false;
+
+ for (const QVariantMap &f : found) {
+ const QString crx = f.value("chromiumAppId").toString();
+ present.insert(crx);
+ if (m_ignoredChromium.contains(crx))
+ continue;
+ int i = -1;
+ for (int j = 0; j < m_apps.size(); ++j)
+ if (m_apps[j].value("chromiumAppId").toString() == crx) { i = j; break; }
+
+ if (i < 0) {
+ QVariantMap app = f;
+ app["id"] = "crx-" + crx.left(8);
+ app["type"] = "web";
+ app["engine"] = "chromium";
+ app["category"] = "Webb";
+ m_apps << app;
+ added << f.value("name").toString();
+ dirty = true;
+ } else {
+ // Uppdatera tekniska fält, men behåll det användaren ändrat.
+ QVariantMap &app = m_apps[i];
+ for (const char *key : {"chromiumProfile", "chromiumBin"}) {
+ if (app.value(key) != f.value(key)) { app[key] = f.value(key); dirty = true; }
+ }
+ if (app.value("url").toString().isEmpty() && !f.value("url").toString().isEmpty()) {
+ app["url"] = f.value("url"); dirty = true;
+ }
+ if (app.value("icon").toString().isEmpty() && !f.value("icon").toString().isEmpty()) {
+ app["icon"] = f.value("icon"); dirty = true;
+ }
+ }
+ }
+
+ // Avinstallerade i Chromium: ta bort från launchern och glöm ignoreringen.
+ for (int j = m_apps.size() - 1; j >= 0; --j) {
+ const QString crx = m_apps[j].value("chromiumAppId").toString();
+ if (!crx.isEmpty() && !present.contains(crx)) {
+ m_apps.removeAt(j);
+ dirty = true;
+ }
+ }
+ const int before = m_ignoredChromium.size();
+ m_ignoredChromium.removeIf([&](const QString &crx) { return !present.contains(crx); });
+ dirty |= before != m_ignoredChromium.size();
+
+ if (dirty) {
+ persist();
+ bump();
+ }
+ return added;
+}
+
+void AppStore::fetchMissingIcons()
+{
+ for (const auto &a : std::as_const(m_apps)) {
+ if (a.value("type") == "web" && a.value("icon").toString().isEmpty()
+ && !a.value("url").toString().isEmpty())
+ emit iconWanted(a.value("id").toString(), a.value("url").toString());
+ }
+}
+
+void AppStore::bump()
+{
+ ++m_revision;
+ emit changed();
+}
+
+void AppStore::load()
+{
+ QFile f(m_path);
+ if (!f.open(QIODevice::ReadOnly)) {
+ loadDefaults();
+ persist();
+ return;
+ }
+ const QJsonObject root = QJsonDocument::fromJson(f.readAll()).object();
+ for (const auto &v : root.value("ignoredChromiumApps").toArray())
+ m_ignoredChromium << v.toString();
+ const QJsonArray arr = root.value("apps").toArray();
+ for (const auto &v : arr) {
+ QVariantMap m = v.toObject().toVariantMap();
+ if (m.value("id").toString().isEmpty())
+ m["id"] = QUuid::createUuid().toString(QUuid::WithoutBraces).left(8);
+ m_apps << m;
+ }
+}
+
+void AppStore::persist()
+{
+ QJsonArray arr;
+ for (const auto &a : m_apps)
+ arr << QJsonObject::fromVariantMap(a);
+ QSaveFile f(m_path);
+ if (!f.open(QIODevice::WriteOnly)) {
+ qWarning("Kunde inte spara %s", qPrintable(m_path));
+ return;
+ }
+ f.write(QJsonDocument(QJsonObject{{"version", 1}, {"apps", arr},
+ {"ignoredChromiumApps", QJsonArray::fromStringList(m_ignoredChromium)}}).toJson());
+ f.commit();
+}
+
+void AppStore::loadDefaults()
+{
+ auto add = [this](const QVariantMap &m) { m_apps << m; };
+ add({{"id", "jellyfin"}, {"name", "Jellyfin"}, {"type", "web"}, {"engine", "builtin"},
+ {"url", "http://localhost:8096"}, {"category", "Media"}, {"icon", ""}, {"userAgent", ""}});
+ add({{"id", "youtube"}, {"name", "YouTube"}, {"type", "web"}, {"engine", "builtin"},
+ {"url", "https://www.youtube.com/tv"}, {"category", "Media"}, {"icon", ""},
+ {"userAgent", tvUserAgent()}});
+ add({{"id", "retroarch"}, {"name", "RetroArch"}, {"type", "app"},
+ {"command", "retroarch"}, {"category", "Spel"}, {"icon", "com.libretro.RetroArch"}});
+ add({{"id", "chromium"}, {"name", "Chromium"}, {"type", "app"},
+ {"command", "chromium --ozone-platform=wayland --start-fullscreen"},
+ {"category", "Program"}, {"icon", "chromium"}});
+}
diff --git a/src/appstore.h b/src/appstore.h
new file mode 100644
index 0000000..4f1c926
--- /dev/null
+++ b/src/appstore.h
@@ -0,0 +1,80 @@
+#pragma once
+
+#include <QFileSystemWatcher>
+#include <QHash>
+#include <QObject>
+#include <QStringList>
+#include <QVariantList>
+#include <QVariantMap>
+
+// Håller listan över appar på hemskärmen och sparar den i
+// ~/.config/tv-launcher/apps.json.
+//
+// En app är en map med fälten:
+// id, name, type ("app" | "web"), command, url,
+// engine ("builtin" | "chromium"), icon, category, userAgent
+class AppStore : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(int revision READ revision NOTIFY changed)
+ Q_PROPERTY(QStringList categories READ categories NOTIFY changed)
+ Q_PROPERTY(QStringList knownCategories READ knownCategories CONSTANT)
+ Q_PROPERTY(QString tvUserAgent READ tvUserAgent CONSTANT)
+ Q_PROPERTY(QString iconDir READ iconDir CONSTANT)
+ Q_PROPERTY(QString previewDir READ previewDir CONSTANT)
+
+public:
+ explicit AppStore(QObject *parent = nullptr);
+
+ int revision() const { return m_revision; }
+ QStringList categories() const;
+ QStringList knownCategories() const;
+ QString tvUserAgent() const;
+
+ Q_INVOKABLE QVariantList appsIn(const QString &category) const;
+ Q_INVOKABLE QVariantMap get(const QString &id) const;
+ Q_INVOKABLE QString save(const QVariantMap &app);
+ Q_INVOKABLE void remove(const QString &id);
+ Q_INVOKABLE void move(const QString &id, int delta);
+ Q_INVOKABLE QString configPath() const { return m_path; }
+ QString iconDir() const { return m_iconDir; }
+ QString previewDir() const { return m_previewDir; }
+ Q_INVOKABLE void markUsed(const QString &id);
+ // Ändrar enstaka fält; tom sträng tar bort fältet.
+ Q_INVOKABLE void patch(const QString &id, const QVariantMap &fields);
+ Q_INVOKABLE QVariantList recent(int max = 10) const;
+
+ // Synkar webbappar installerade i Chromium. Returnerar namnen på nya appar.
+ QStringList syncChromiumApps(const QList<QVariantMap> &found);
+
+ // Hämtar ikoner för webbappar som saknar en (anropas vid start).
+ void fetchMissingIcons();
+
+public slots:
+ void setIconIfEmpty(const QString &id, const QString &iconPath);
+
+signals:
+ void changed();
+ void iconWanted(const QString &id, const QString &url);
+
+private:
+ int indexOf(const QString &id) const;
+ void load();
+ void persist();
+ void loadDefaults();
+ void bump();
+ void scanMediaFolders();
+ QVariantMap decorate(QVariantMap app) const;
+ static QString normalizeName(const QString &s);
+
+ QList<QVariantMap> m_apps;
+ QStringList m_ignoredChromium;
+
+ // ~/Bilder/TV/Ikoner och ~/Bilder/TV/Förhandsbilder: filer som heter
+ // som appen används automatiskt.
+ QString m_iconDir, m_previewDir;
+ QHash<QString, QString> m_iconFiles, m_previewFiles; // normaliserat namn -> sökväg
+ QFileSystemWatcher m_mediaWatcher; // Chromium-appar som tagits bort i launchern
+ QString m_path;
+ int m_revision = 0;
+};
diff --git a/src/chromiumapps.cpp b/src/chromiumapps.cpp
new file mode 100644
index 0000000..8ab239f
--- /dev/null
+++ b/src/chromiumapps.cpp
@@ -0,0 +1,129 @@
+#include "chromiumapps.h"
+
+#include "appstore.h"
+
+#include <QDir>
+#include <QFile>
+#include <QFileInfo>
+#include <QProcess>
+#include <QRegularExpression>
+#include <QStandardPaths>
+#include <QTextStream>
+
+static QString applicationsDir()
+{
+ return QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/applications";
+}
+
+static QHash<QString, QString> readDesktopEntry(const QString &path)
+{
+ QHash<QString, QString> out;
+ QFile f(path);
+ if (!f.open(QIODevice::ReadOnly | QIODevice::Text))
+ return out;
+ QTextStream in(&f);
+ bool inEntry = false;
+ while (!in.atEnd()) {
+ const QString line = in.readLine().trimmed();
+ if (line.startsWith('[')) {
+ if (inEntry)
+ break;
+ inEntry = line == QLatin1String("[Desktop Entry]");
+ continue;
+ }
+ const int eq = line.indexOf('=');
+ if (inEntry && eq > 0)
+ out.insert(line.left(eq).trimmed(), line.mid(eq + 1).trimmed());
+ }
+ return out;
+}
+
+// Chromium sparar appens start-adress i profilens synkdatabas (LevelDB).
+// Vi letar efter http(s)-adresser nära app-id:t och tar den kortaste som
+// inte är en bild eller ett manifest. Bästa möjliga gissning; tomt om inget.
+static QString findStartUrl(const QString &profileDir, const QString &appId)
+{
+ static const QRegularExpression urlRe(QStringLiteral("https?://[^\\s\\x00-\\x1f\"'<>*]+"));
+ static const QRegularExpression skipRe(QStringLiteral("\\.(png|ico|svg|jpe?g|webp|json|webmanifest)(\\?|$)"),
+ QRegularExpression::CaseInsensitiveOption);
+ QDir dir(profileDir + "/Sync Data/LevelDB");
+ QString best;
+ const auto files = dir.entryInfoList({"*.log", "*.ldb"}, QDir::Files);
+ for (const QFileInfo &fi : files) {
+ QFile f(fi.absoluteFilePath());
+ if (fi.size() > 32 * 1024 * 1024 || !f.open(QIODevice::ReadOnly))
+ continue;
+ const QByteArray data = f.readAll();
+ qsizetype idx = data.indexOf(appId.toLatin1());
+ while (idx >= 0) {
+ const qsizetype from = qMax<qsizetype>(0, idx - 3000);
+ const QString window = QString::fromLatin1(data.mid(from, 6000));
+ auto it = urlRe.globalMatch(window);
+ while (it.hasNext()) {
+ const QString u = it.next().captured(0);
+ if (skipRe.match(u).hasMatch())
+ continue;
+ if (best.isEmpty() || u.size() < best.size())
+ best = u;
+ }
+ idx = data.indexOf(appId.toLatin1(), idx + 1);
+ }
+ }
+ return best;
+}
+
+ChromiumApps::ChromiumApps(AppStore *store, QObject *parent)
+ : QObject(parent), m_store(store)
+{
+ const QString dir = applicationsDir();
+ QDir().mkpath(dir);
+ m_watcher.addPath(dir);
+ m_debounce.setSingleShot(true);
+ m_debounce.setInterval(1500);
+ connect(&m_watcher, &QFileSystemWatcher::directoryChanged, &m_debounce, qOverload<>(&QTimer::start));
+ connect(&m_debounce, &QTimer::timeout, this, &ChromiumApps::scan);
+}
+
+void ChromiumApps::scan()
+{
+ static const QRegularExpression nameRe(
+ QStringLiteral("^(chrome|chromium)-([a-p]{32})-(.+)\\.desktop$"));
+
+ QList<QVariantMap> found;
+ QDir dir(applicationsDir());
+ const auto files = dir.entryList({"chrome-*.desktop", "chromium-*.desktop"}, QDir::Files);
+ for (const QString &file : files) {
+ const auto m = nameRe.match(file);
+ if (!m.hasMatch())
+ continue;
+ const auto e = readDesktopEntry(dir.filePath(file));
+ const QString exec = e.value("Exec");
+ if (e.value("Name").isEmpty() || !exec.contains("--app-id="))
+ continue;
+
+ const QString appId = m.captured(2);
+ const QStringList parts = QProcess::splitCommand(exec);
+ const QString bin = parts.value(0);
+ QString profile = "Default";
+ for (const QString &p : parts)
+ if (p.startsWith("--profile-directory="))
+ profile = p.mid(20);
+
+ const QString configName = QFileInfo(bin).fileName().contains("chrome") &&
+ !QFileInfo(bin).fileName().contains("chromium")
+ ? "google-chrome" : "chromium";
+ const QString profileDir = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation)
+ + "/" + configName + "/" + profile;
+
+ found << QVariantMap{{"chromiumAppId", appId},
+ {"chromiumProfile", profile},
+ {"chromiumBin", bin},
+ {"name", e.value("Name")},
+ {"icon", e.value("Icon")},
+ {"url", findStartUrl(profileDir, appId)}};
+ }
+
+ const QStringList added = m_store->syncChromiumApps(found);
+ if (!added.isEmpty())
+ emit appsAdded(added);
+}
diff --git a/src/chromiumapps.h b/src/chromiumapps.h
new file mode 100644
index 0000000..97e3513
--- /dev/null
+++ b/src/chromiumapps.h
@@ -0,0 +1,28 @@
+#pragma once
+
+#include <QFileSystemWatcher>
+#include <QObject>
+#include <QTimer>
+
+class AppStore;
+
+// Hittar webbappar som installerats i Chromium/Chrome ("Installera sidan
+// som app" / "Skapa genväg") via deras .desktop-filer i
+// ~/.local/share/applications och håller launcherns lista i synk.
+class ChromiumApps : public QObject
+{
+ Q_OBJECT
+public:
+ explicit ChromiumApps(AppStore *store, QObject *parent = nullptr);
+
+public slots:
+ void scan();
+
+signals:
+ void appsAdded(const QStringList &names);
+
+private:
+ AppStore *m_store;
+ QFileSystemWatcher m_watcher;
+ QTimer m_debounce;
+};
diff --git a/src/desktopscanner.cpp b/src/desktopscanner.cpp
new file mode 100644
index 0000000..2fca17b
--- /dev/null
+++ b/src/desktopscanner.cpp
@@ -0,0 +1,106 @@
+#include "desktopscanner.h"
+
+#include <QDir>
+#include <QFile>
+#include <QHash>
+#include <QLocale>
+#include <QRegularExpression>
+#include <QSet>
+#include <QStandardPaths>
+#include <QTextStream>
+#include <algorithm>
+
+static QHash<QString, QString> parseDesktopEntry(const QString &path)
+{
+ QHash<QString, QString> out;
+ QFile f(path);
+ if (!f.open(QIODevice::ReadOnly | QIODevice::Text))
+ return out;
+ QTextStream in(&f);
+ bool inEntry = false;
+ while (!in.atEnd()) {
+ const QString line = in.readLine().trimmed();
+ if (line.startsWith('[')) {
+ if (inEntry)
+ break;
+ inEntry = (line == QLatin1String("[Desktop Entry]"));
+ continue;
+ }
+ if (!inEntry || line.isEmpty() || line.startsWith('#'))
+ continue;
+ const int eq = line.indexOf('=');
+ if (eq > 0)
+ out.insert(line.left(eq).trimmed(), line.mid(eq + 1).trimmed());
+ }
+ return out;
+}
+
+static QString cleanExec(QString exec)
+{
+ static const QRegularExpression codes(QStringLiteral("\\s*%[fFuUdDnNickvm]"));
+ exec.remove(codes);
+ exec.replace(QLatin1String("%%"), QLatin1String("%"));
+ return exec.trimmed();
+}
+
+static QString guessCategory(const QString &cats)
+{
+ if (cats.contains("Game"))
+ return "Spel";
+ if (cats.contains("Audio") && !cats.contains("Video"))
+ return "Musik";
+ if (cats.contains("AudioVideo") || cats.contains("Video"))
+ return "Media";
+ if (cats.contains("WebBrowser") || cats.contains("Network"))
+ return "Webb";
+ return "Program";
+}
+
+QVariantList DesktopScanner::scan() const
+{
+ QStringList dirs = QStandardPaths::standardLocations(QStandardPaths::ApplicationsLocation);
+ dirs << QDir::homePath() + "/.local/share/flatpak/exports/share/applications"
+ << "/var/lib/flatpak/exports/share/applications";
+
+ const QString lang = QLocale().name(); // sv_SE
+ const QString shortLang = lang.section('_', 0, 0); // sv
+
+ QSet<QString> seen;
+ QVariantList out;
+ for (const QString &dir : std::as_const(dirs)) {
+ QDir d(dir);
+ const auto files = d.entryInfoList({"*.desktop"}, QDir::Files);
+ for (const QFileInfo &fi : files) {
+ if (seen.contains(fi.fileName()))
+ continue;
+ seen.insert(fi.fileName());
+
+ const auto e = parseDesktopEntry(fi.absoluteFilePath());
+ if (e.value("Type") != QLatin1String("Application")
+ || e.value("NoDisplay") == QLatin1String("true")
+ || e.value("Hidden") == QLatin1String("true")
+ || e.value("Terminal") == QLatin1String("true")
+ || e.value("Exec").isEmpty())
+ continue;
+
+ QString name = e.value("Name[" + lang + "]");
+ if (name.isEmpty())
+ name = e.value("Name[" + shortLang + "]");
+ if (name.isEmpty())
+ name = e.value("Name");
+ if (name.isEmpty())
+ continue;
+
+ out << QVariantMap{{"name", name},
+ {"type", "app"},
+ {"command", cleanExec(e.value("Exec"))},
+ {"icon", e.value("Icon")},
+ {"category", guessCategory(e.value("Categories"))}};
+ }
+ }
+ std::sort(out.begin(), out.end(), [](const QVariant &a, const QVariant &b) {
+ return a.toMap().value("name").toString().compare(b.toMap().value("name").toString(),
+ Qt::CaseInsensitive) < 0;
+ });
+ return out;
+}
diff --git a/src/desktopscanner.h b/src/desktopscanner.h
new file mode 100644
index 0000000..f08982c
--- /dev/null
+++ b/src/desktopscanner.h
@@ -0,0 +1,14 @@
+#pragma once
+
+#include <QObject>
+#include <QVariantList>
+
+// Läser installerade program från .desktop-filer så att de kan läggas
+// till på hemskärmen.
+class DesktopScanner : public QObject
+{
+ Q_OBJECT
+public:
+ using QObject::QObject;
+ Q_INVOKABLE QVariantList scan() const;
+};
diff --git a/src/iconfetcher.cpp b/src/iconfetcher.cpp
new file mode 100644
index 0000000..b920cb8
--- /dev/null
+++ b/src/iconfetcher.cpp
@@ -0,0 +1,122 @@
+#include "iconfetcher.h"
+
+#include <QDir>
+#include <QNetworkReply>
+#include <QRegularExpression>
+#include <QStandardPaths>
+
+static constexpr int kGoodEnough = 128;
+
+static QNetworkRequest makeRequest(const QUrl &url)
+{
+ QNetworkRequest req(url);
+ req.setHeader(QNetworkRequest::UserAgentHeader,
+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) "
+ "Chrome/130.0 Safari/537.36");
+ req.setTransferTimeout(8000);
+ return req;
+}
+
+// Plockar ut ikonlänkar ur HTML; apple-touch-icon först eftersom de är stora.
+static QList<QUrl> iconLinks(const QString &html, const QUrl &base)
+{
+ static const QRegularExpression linkRe(QStringLiteral("<link\\b[^>]*>"),
+ QRegularExpression::CaseInsensitiveOption);
+ static const QRegularExpression relRe(QStringLiteral("rel\\s*=\\s*[\"']([^\"']+)[\"']"),
+ QRegularExpression::CaseInsensitiveOption);
+ static const QRegularExpression hrefRe(QStringLiteral("href\\s*=\\s*[\"']([^\"']+)[\"']"),
+ QRegularExpression::CaseInsensitiveOption);
+ QList<QUrl> touch, icons;
+ auto it = linkRe.globalMatch(html);
+ while (it.hasNext()) {
+ const QString tag = it.next().captured(0);
+ const QString rel = relRe.match(tag).captured(1).toLower();
+ const QString href = hrefRe.match(tag).captured(1);
+ if (href.isEmpty())
+ continue;
+ const QUrl resolved = base.resolved(QUrl(href));
+ if (rel.contains("apple-touch-icon"))
+ touch << resolved;
+ else if (rel.split(' ').contains("icon"))
+ icons << resolved;
+ }
+ return touch + icons;
+}
+
+IconFetcher::IconFetcher(QObject *parent) : QObject(parent) {}
+
+void IconFetcher::fetch(const QString &id, const QString &urlString)
+{
+ const QUrl url(urlString);
+ if (!url.isValid() || url.host().isEmpty())
+ return;
+
+ auto *job = new Job;
+ job->id = id;
+ job->pages << url;
+ QUrl root = url.resolved(QUrl("/"));
+ if (root != url)
+ job->pages << root;
+ nextPage(job);
+}
+
+void IconFetcher::nextPage(Job *job)
+{
+ if (job->pages.isEmpty()) {
+ nextCandidate(job);
+ return;
+ }
+ const QUrl page = job->pages.takeFirst();
+ QNetworkReply *reply = m_nam.get(makeRequest(page));
+ connect(reply, &QNetworkReply::finished, this, [this, reply, job, page] {
+ reply->deleteLater();
+ const QUrl base = reply->url().isValid() ? reply->url() : page;
+ if (reply->error() == QNetworkReply::NoError) {
+ const QString html = QString::fromUtf8(reply->read(512 * 1024));
+ for (const QUrl &u : iconLinks(html, base))
+ if (!job->candidates.contains(u))
+ job->candidates << u;
+ }
+ // Standardplatserna sist, en gång per webbplats.
+ for (const char *path : {"/apple-touch-icon.png", "/favicon.ico"}) {
+ const QUrl u = base.resolved(QUrl(QString::fromLatin1(path)));
+ if (job->pages.isEmpty() && !job->candidates.contains(u))
+ job->candidates << u;
+ }
+ nextPage(job);
+ });
+}
+
+void IconFetcher::nextCandidate(Job *job)
+{
+ if (job->candidates.isEmpty() || job->best.width() >= kGoodEnough) {
+ finish(job);
+ return;
+ }
+ const QUrl next = job->candidates.takeFirst();
+ QNetworkReply *reply = m_nam.get(makeRequest(next));
+ connect(reply, &QNetworkReply::finished, this, [this, reply, job] {
+ reply->deleteLater();
+ if (reply->error() == QNetworkReply::NoError) {
+ const QImage img = QImage::fromData(reply->readAll());
+ if (!img.isNull() && img.width() > job->best.width())
+ job->best = img;
+ }
+ nextCandidate(job);
+ });
+}
+
+void IconFetcher::finish(Job *job)
+{
+ QImage img = job->best;
+ if (!img.isNull()) {
+ const QString dir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/icons";
+ QDir().mkpath(dir);
+ const QString path = dir + "/" + job->id + ".png";
+ if (img.width() > 256 || img.height() > 256)
+ img = img.scaled(256, 256, Qt::KeepAspectRatio, Qt::SmoothTransformation);
+ if (img.save(path, "PNG"))
+ emit iconReady(job->id, path);
+ }
+ delete job;
+}
diff --git a/src/iconfetcher.h b/src/iconfetcher.h
new file mode 100644
index 0000000..2db7432
--- /dev/null
+++ b/src/iconfetcher.h
@@ -0,0 +1,39 @@
+#pragma once
+
+#include <QImage>
+#include <QNetworkAccessManager>
+#include <QObject>
+#include <QUrl>
+
+// Hämtar en ikon för en webbapp direkt från webbplatsen och sparar den i
+// ~/.local/share/tv-launcher/icons/<id>.png.
+//
+// Läser <link rel="apple-touch-icon"/"icon"> från sidan och från
+// webbplatsens startsida, provar sedan /apple-touch-icon.png och
+// /favicon.ico, och behåller den största bilden.
+class IconFetcher : public QObject
+{
+ Q_OBJECT
+public:
+ explicit IconFetcher(QObject *parent = nullptr);
+
+public slots:
+ void fetch(const QString &id, const QString &url);
+
+signals:
+ void iconReady(const QString &id, const QString &path);
+
+private:
+ struct Job {
+ QString id;
+ QList<QUrl> pages;
+ QList<QUrl> candidates;
+ QImage best;
+ };
+
+ void nextPage(Job *job);
+ void nextCandidate(Job *job);
+ void finish(Job *job);
+
+ QNetworkAccessManager m_nam;
+};
diff --git a/src/iconprovider.cpp b/src/iconprovider.cpp
new file mode 100644
index 0000000..e1801a6
--- /dev/null
+++ b/src/iconprovider.cpp
@@ -0,0 +1,65 @@
+#include "iconprovider.h"
+
+#include <QDir>
+#include <QFile>
+#include <QIcon>
+#include <QStandardPaths>
+#include <QUrl>
+
+// Reserv när QIcon::fromTheme inte hittar ikonen (vanligt utan
+// skrivbordsmiljö): leta direkt i hicolor och pixmaps, största först.
+static QString findIconFile(const QString &name)
+{
+ QStringList bases;
+ for (const QString &d : QStandardPaths::standardLocations(QStandardPaths::GenericDataLocation))
+ bases << d + "/icons/hicolor";
+ bases << QDir::homePath() + "/.local/share/flatpak/exports/share/icons/hicolor"
+ << "/var/lib/flatpak/exports/share/icons/hicolor";
+
+ static const QStringList sizes{"scalable", "512x512", "256x256", "192x192", "128x128",
+ "96x96", "64x64", "48x48", "32x32"};
+ for (const QString &base : std::as_const(bases))
+ for (const QString &size : sizes)
+ for (const char *ext : {".svg", ".png"}) {
+ const QString p = base + "/" + size + "/apps/" + name + QLatin1String(ext);
+ if (QFile::exists(p))
+ return p;
+ }
+ for (const char *ext : {".svg", ".png", ".xpm"}) {
+ const QString p = "/usr/share/pixmaps/" + name + QLatin1String(ext);
+ if (QFile::exists(p))
+ return p;
+ }
+ return {};
+}
+
+QPixmap IconProvider::requestPixmap(const QString &rawId, QSize *size, const QSize &requestedSize)
+{
+ const QString id = QUrl::fromPercentEncoding(rawId.toUtf8());
+ const QSize want = requestedSize.isValid() ? requestedSize : QSize(256, 256);
+ QPixmap pm;
+
+ QIcon icon;
+ if (id.startsWith('/')) {
+ if (QFile::exists(id))
+ icon = QIcon(id);
+ } else if (!id.isEmpty()) {
+ icon = QIcon::fromTheme(id);
+ if (icon.isNull() || icon.availableSizes().isEmpty()) {
+ const QString file = findIconFile(id);
+ if (!file.isEmpty())
+ icon = QIcon(file);
+ }
+ }
+ if (!icon.isNull())
+ pm = icon.pixmap(want);
+
+ // Tom 1x1-bild i stället för fel, så att QML visar reservbokstaven utan varningar.
+ if (pm.isNull()) {
+ pm = QPixmap(1, 1);
+ pm.fill(Qt::transparent);
+ }
+ if (size)
+ *size = pm.size();
+ return pm;
+}
diff --git a/src/iconprovider.h b/src/iconprovider.h
new file mode 100644
index 0000000..b773cae
--- /dev/null
+++ b/src/iconprovider.h
@@ -0,0 +1,13 @@
+#pragma once
+
+#include <QQuickImageProvider>
+
+// image://icon/<namn eller sökväg>
+// Tar ett ikonnamn från ikontemat (t.ex. "retroarch") eller en absolut
+// sökväg till en bildfil.
+class IconProvider : public QQuickImageProvider
+{
+public:
+ IconProvider() : QQuickImageProvider(QQuickImageProvider::Pixmap) {}
+ QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requestedSize) override;
+};
diff --git a/src/inputmanager.cpp b/src/inputmanager.cpp
new file mode 100644
index 0000000..f732e21
--- /dev/null
+++ b/src/inputmanager.cpp
@@ -0,0 +1,459 @@
+#include "inputmanager.h"
+
+#include <QCoreApplication>
+#include <QKeyEvent>
+#include <QWindow>
+
+#include <SDL.h>
+#include <linux/input-event-codes.h>
+
+#include <cmath>
+
+static constexpr int kStickThreshold = 20000;
+static constexpr int kStickRelease = 12000;
+static constexpr int kRepeatDelay = 400;
+static constexpr int kRepeatInterval = 110;
+static constexpr int kHomeLongPress = 800;
+static constexpr double kDeadzone = 7000.0;
+static constexpr double kPointerSpeed = 1500.0; // px/s vid fullt utslag
+static constexpr double kScrollSpeed = 14.0; // hack/s vid fullt utslag
+static constexpr int kTriggerOn = 16000;
+static constexpr int kTriggerOff = 8000;
+
+InputManager::InputManager(bool enableGamepad, QObject *parent) : QObject(parent)
+{
+ if (!enableGamepad) {
+ qInfo("Handkontroller avstängda (testläge)");
+ } else {
+ SDL_SetHint(SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS, "1");
+ SDL_SetHint(SDL_HINT_NO_SIGNAL_HANDLERS, "1");
+ if (SDL_Init(SDL_INIT_GAMECONTROLLER) < 0) {
+ qWarning("SDL kunde inte starta handkontrollstöd: %s", SDL_GetError());
+ } else {
+ m_sdlOk = true;
+ connect(&m_pollTimer, &QTimer::timeout, this, &InputManager::poll);
+ m_pollTimer.start(8);
+ }
+ }
+
+ m_repeatTimer.setSingleShot(false);
+ connect(&m_repeatTimer, &QTimer::timeout, this, [this] {
+ m_repeatTimer.setInterval(kRepeatInterval);
+ if (m_held != None)
+ sendKey(keyFor(m_held), true, true);
+ });
+
+ m_emuTimer.setInterval(16);
+ connect(&m_emuTimer, &QTimer::timeout, this, &InputManager::emuTick);
+
+ // Försök skapa den virtuella enheten direkt (inte i testläge).
+ if (m_sdlOk && m_vi.open())
+ qInfo("Virtuell mus/tangentbord (uinput) redo");
+
+ m_homeTimer.setSingleShot(true);
+ m_homeTimer.setInterval(kHomeLongPress);
+ connect(&m_homeTimer, &QTimer::timeout, this, [this] {
+ m_homeLongFired = true;
+ emit homeLongPressed();
+ });
+}
+
+InputManager::~InputManager()
+{
+ for (auto *c : std::as_const(m_controllers))
+ SDL_GameControllerClose(c);
+ if (m_sdlOk)
+ SDL_Quit();
+}
+
+void InputManager::setSuspended(bool s)
+{
+ m_suspended = s;
+ if (s) {
+ m_dpad = m_stick = None;
+ updateHeld();
+ }
+ updateEmulation();
+}
+
+void InputManager::setWebMode(bool on)
+{
+ if (m_webMode == on)
+ return;
+ m_webMode = on;
+ emit webModeChanged();
+ updateEmulation();
+}
+
+void InputManager::setExternalMode(const QString &mode)
+{
+ const QString m = mode == "keyboard" ? "keyboard" : "gamepad";
+ if (m == m_externalMode)
+ return;
+ m_externalMode = m;
+ emit externalModeChanged();
+ updateEmulation();
+}
+
+void InputManager::setOskActive(bool on)
+{
+ if (on == m_oskActive)
+ return;
+ m_oskActive = on;
+ m_dpad = m_stick = None;
+ updateHeld();
+ emit oskActiveChanged();
+ updateEmulation();
+}
+
+void InputManager::setKeyWindow(QObject *window)
+{
+ m_keyWindow = qobject_cast<QWindow *>(window);
+}
+
+void InputManager::typeIntoFocus(const QString &text, bool enter)
+{
+ if (!m_window)
+ return;
+ for (const QChar c : text) {
+ int key = Qt::Key_unknown;
+ const QChar up = c.toUpper();
+ if (up >= 'A' && up <= 'Z') key = Qt::Key_A + (up.unicode() - 'A');
+ else if (c >= '0' && c <= '9') key = Qt::Key_0 + (c.unicode() - '0');
+ else if (c == ' ') key = Qt::Key_Space;
+ const Qt::KeyboardModifiers mods = c.isUpper() ? Qt::ShiftModifier : Qt::NoModifier;
+ QKeyEvent press(QEvent::KeyPress, key, mods, QString(c));
+ QKeyEvent release(QEvent::KeyRelease, key, mods, QString(c));
+ QCoreApplication::sendEvent(m_window, &press);
+ QCoreApplication::sendEvent(m_window, &release);
+ }
+ if (enter) {
+ QKeyEvent press(QEvent::KeyPress, Qt::Key_Return, Qt::NoModifier, QStringLiteral("\r"));
+ QKeyEvent release(QEvent::KeyRelease, Qt::Key_Return, Qt::NoModifier, QStringLiteral("\r"));
+ QCoreApplication::sendEvent(m_window, &press);
+ QCoreApplication::sendEvent(m_window, &release);
+ }
+}
+
+bool InputManager::typeExternal(const QString &text, bool enter)
+{
+ if (!m_vi.isOpen() && !m_vi.open()) {
+ emit virtualInputMissing();
+ return false;
+ }
+ m_vi.typeText(text);
+ if (enter) {
+ m_vi.key(KEY_ENTER, true);
+ m_vi.key(KEY_ENTER, false);
+ }
+ return true;
+}
+
+bool InputManager::wantsEmulation() const
+{
+ if (m_oskActive)
+ return false;
+ if (m_suspended)
+ return m_externalMode == "keyboard";
+ return m_webMode;
+}
+
+void InputManager::updateEmulation()
+{
+ bool on = m_sdlOk && wantsEmulation();
+ if (on && !m_vi.isOpen()) {
+ if (m_vi.open()) {
+ emit virtualInputChanged();
+ } else {
+ on = false;
+ if (!m_warnedMissing) {
+ m_warnedMissing = true;
+ emit virtualInputMissing();
+ }
+ }
+ }
+ if (on == m_emulating)
+ return;
+ m_emulating = on;
+ m_vi.releaseAll();
+ m_wheelAcc = m_moveAccX = m_moveAccY = 0;
+ m_ltDown = m_rtDown = false;
+ if (on) {
+ m_dpad = m_stick = None;
+ updateHeld();
+ m_emuClock.start();
+ m_emuTimer.start();
+ } else {
+ m_emuTimer.stop();
+ }
+}
+
+_SDL_GameController *InputManager::firstController() const
+{
+ return m_controllers.isEmpty() ? nullptr : *m_controllers.cbegin();
+}
+
+void InputManager::handleEmuButton(int button, bool down)
+{
+ switch (button) {
+ case SDL_CONTROLLER_BUTTON_DPAD_UP: m_vi.key(KEY_UP, down); break;
+ case SDL_CONTROLLER_BUTTON_DPAD_DOWN: m_vi.key(KEY_DOWN, down); break;
+ case SDL_CONTROLLER_BUTTON_DPAD_LEFT: m_vi.key(KEY_LEFT, down); break;
+ case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: m_vi.key(KEY_RIGHT, down); break;
+ case SDL_CONTROLLER_BUTTON_A: m_vi.key(BTN_LEFT, down); break;
+ case SDL_CONTROLLER_BUTTON_B:
+ if (m_webMode && !m_suspended) {
+ if (down) emit backPressed(); // launcherns egen tillbaka-logik
+ } else {
+ m_vi.key(KEY_LEFTALT, down); // Alt+Vänster = bakåt i webbläsare
+ m_vi.key(KEY_LEFT, down);
+ }
+ break;
+ case SDL_CONTROLLER_BUTTON_X: m_vi.key(KEY_ENTER, down); break;
+ case SDL_CONTROLLER_BUTTON_Y: m_vi.key(KEY_SPACE, down); break;
+ case SDL_CONTROLLER_BUTTON_LEFTSHOULDER:
+ m_vi.key(KEY_LEFTSHIFT, down);
+ m_vi.key(KEY_TAB, down);
+ break;
+ case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: m_vi.key(KEY_TAB, down); break;
+ case SDL_CONTROLLER_BUTTON_START: m_vi.key(KEY_ESC, down); break;
+ case SDL_CONTROLLER_BUTTON_BACK: if (down) emit oskRequested(); break;
+ case SDL_CONTROLLER_BUTTON_LEFTSTICK: m_vi.key(KEY_F, down); break;
+ case SDL_CONTROLLER_BUTTON_RIGHTSTICK: m_vi.key(BTN_RIGHT, down); break;
+ default: break;
+ }
+}
+
+static double shaped(int raw)
+{
+ const double a = std::abs(raw);
+ if (a < kDeadzone)
+ return 0;
+ const double n = std::min(1.0, (a - kDeadzone) / (32767.0 - kDeadzone));
+ return (raw < 0 ? -1 : 1) * n * n; // finare kontroll vid små utslag
+}
+
+void InputManager::emuTick()
+{
+ SDL_GameController *c = firstController();
+ const double dt = std::min(0.05, m_emuClock.restart() / 1000.0);
+ if (!c)
+ return;
+
+ // Muspekare: vänster spak
+ m_moveAccX += shaped(SDL_GameControllerGetAxis(c, SDL_CONTROLLER_AXIS_LEFTX)) * kPointerSpeed * dt;
+ m_moveAccY += shaped(SDL_GameControllerGetAxis(c, SDL_CONTROLLER_AXIS_LEFTY)) * kPointerSpeed * dt;
+ const int dx = int(m_moveAccX), dy = int(m_moveAccY);
+ m_moveAccX -= dx;
+ m_moveAccY -= dy;
+ m_vi.move(dx, dy);
+
+ // Scroll: höger spak (upp = scrolla upp)
+ m_wheelAcc += -shaped(SDL_GameControllerGetAxis(c, SDL_CONTROLLER_AXIS_RIGHTY)) * kScrollSpeed * dt;
+ const int steps = int(m_wheelAcc);
+ m_wheelAcc -= steps;
+ m_vi.wheel(steps);
+
+ // Avtryckare: Page Up/Down
+ const int lt = SDL_GameControllerGetAxis(c, SDL_CONTROLLER_AXIS_TRIGGERLEFT);
+ const int rt = SDL_GameControllerGetAxis(c, SDL_CONTROLLER_AXIS_TRIGGERRIGHT);
+ if (!m_ltDown && lt > kTriggerOn) { m_ltDown = true; m_vi.key(KEY_PAGEUP, true); }
+ else if (m_ltDown && lt < kTriggerOff) { m_ltDown = false; m_vi.key(KEY_PAGEUP, false); }
+ if (!m_rtDown && rt > kTriggerOn) { m_rtDown = true; m_vi.key(KEY_PAGEDOWN, true); }
+ else if (m_rtDown && rt < kTriggerOff) { m_rtDown = false; m_vi.key(KEY_PAGEDOWN, false); }
+}
+
+void InputManager::poll()
+{
+ SDL_Event e;
+ while (SDL_PollEvent(&e)) {
+ switch (e.type) {
+ case SDL_CONTROLLERDEVICEADDED: {
+ SDL_GameController *c = SDL_GameControllerOpen(e.cdevice.which);
+ if (!c)
+ break;
+ const int id = SDL_JoystickInstanceID(SDL_GameControllerGetJoystick(c));
+ if (m_controllers.contains(id)) {
+ SDL_GameControllerClose(c);
+ break;
+ }
+ m_controllers.insert(id, c);
+ m_name = QString::fromUtf8(SDL_GameControllerName(c));
+ qInfo("Handkontroll ansluten: %s", qPrintable(m_name));
+ emit connectedChanged();
+ updateEmulation();
+ break;
+ }
+ case SDL_CONTROLLERDEVICEREMOVED:
+ if (auto *c = m_controllers.take(e.cdevice.which)) {
+ SDL_GameControllerClose(c);
+ if (m_controllers.isEmpty())
+ m_name.clear();
+ emit connectedChanged();
+ }
+ break;
+ case SDL_CONTROLLERBUTTONDOWN:
+ case SDL_CONTROLLERBUTTONUP:
+ handleButton(e.cbutton.button, e.type == SDL_CONTROLLERBUTTONDOWN);
+ break;
+ case SDL_CONTROLLERAXISMOTION: {
+ if (m_emulating)
+ break; // spakarna läses i emuTick()
+ if (e.caxis.axis != SDL_CONTROLLER_AXIS_LEFTX && e.caxis.axis != SDL_CONTROLLER_AXIS_LEFTY)
+ break;
+ auto *c = m_controllers.value(e.caxis.which);
+ if (!c)
+ break;
+ const int x = SDL_GameControllerGetAxis(c, SDL_CONTROLLER_AXIS_LEFTX);
+ const int y = SDL_GameControllerGetAxis(c, SDL_CONTROLLER_AXIS_LEFTY);
+ Dir d = None;
+ const int ax = std::abs(x), ay = std::abs(y);
+ const int threshold = m_stick == None ? kStickThreshold : kStickRelease;
+ if (std::max(ax, ay) >= threshold)
+ d = ax > ay ? (x > 0 ? Right : Left) : (y > 0 ? Down : Up);
+ setDirection(d, true);
+ break;
+ }
+ default:
+ break;
+ }
+ }
+}
+
+void InputManager::handleButton(int button, bool down)
+{
+ if (button == SDL_CONTROLLER_BUTTON_GUIDE) {
+ if (down) {
+ m_homeLongFired = false;
+ m_homeTimer.start();
+ } else {
+ m_homeTimer.stop();
+ if (!m_homeLongFired && !m_suspended)
+ emit homePressed();
+ }
+ return;
+ }
+ if (m_emulating) {
+ handleEmuButton(button, down);
+ return;
+ }
+ if (m_suspended && !m_oskActive)
+ return;
+
+ switch (button) {
+ case SDL_CONTROLLER_BUTTON_DPAD_UP: setDirection(down ? Up : None, false); break;
+ case SDL_CONTROLLER_BUTTON_DPAD_DOWN: setDirection(down ? Down : None, false); break;
+ case SDL_CONTROLLER_BUTTON_DPAD_LEFT: setDirection(down ? Left : None, false); break;
+ case SDL_CONTROLLER_BUTTON_DPAD_RIGHT: setDirection(down ? Right : None, false); break;
+ case SDL_CONTROLLER_BUTTON_A:
+ sendKey(Qt::Key_Return, down);
+ break;
+ case SDL_CONTROLLER_BUTTON_B:
+ if (m_webMode) {
+ if (down)
+ emit backPressed();
+ } else {
+ sendKey(Qt::Key_Escape, down);
+ }
+ break;
+ case SDL_CONTROLLER_BUTTON_Y:
+ case SDL_CONTROLLER_BUTTON_START:
+ sendKey(Qt::Key_Menu, down);
+ break;
+ case SDL_CONTROLLER_BUTTON_X:
+ sendKey(Qt::Key_Backspace, down);
+ break;
+ case SDL_CONTROLLER_BUTTON_BACK:
+ if (down && !m_oskActive)
+ emit oskRequested();
+ break;
+ case SDL_CONTROLLER_BUTTON_LEFTSHOULDER:
+ sendKey(Qt::Key_PageUp, down);
+ break;
+ case SDL_CONTROLLER_BUTTON_RIGHTSHOULDER:
+ sendKey(Qt::Key_PageDown, down);
+ break;
+ default:
+ break;
+ }
+}
+
+void InputManager::setDirection(Dir d, bool fromStick)
+{
+ if (m_suspended && !m_oskActive)
+ d = None;
+ if (fromStick)
+ m_stick = d;
+ else
+ m_dpad = d;
+ updateHeld();
+}
+
+void InputManager::updateHeld()
+{
+ const Dir want = m_dpad != None ? m_dpad : m_stick;
+ if (want == m_held)
+ return;
+ if (m_held != None)
+ sendKey(keyFor(m_held), false);
+ m_held = want;
+ m_repeatTimer.stop();
+ if (m_held != None) {
+ sendKey(keyFor(m_held), true);
+ m_repeatTimer.start(kRepeatDelay);
+ }
+}
+
+int InputManager::keyFor(Dir d)
+{
+ switch (d) {
+ case Up: return Qt::Key_Up;
+ case Down: return Qt::Key_Down;
+ case Left: return Qt::Key_Left;
+ case Right: return Qt::Key_Right;
+ default: return 0;
+ }
+}
+
+void InputManager::sendKey(int key, bool press, bool autoRepeat)
+{
+ QWindow *target = m_keyWindow ? m_keyWindow.data() : m_window.data();
+ if (!target || !key || (m_suspended && !m_oskActive))
+ return;
+ QString text;
+ if (key == Qt::Key_Return)
+ text = QStringLiteral("\r");
+ else if (key == Qt::Key_Escape)
+ text = QStringLiteral("\x1b");
+ QKeyEvent ev(press ? QEvent::KeyPress : QEvent::KeyRelease, key, Qt::NoModifier, text, autoRepeat);
+ QCoreApplication::sendEvent(target, &ev);
+}
+
+// Tangentbord: i webbappar fångar vi Escape och Home innan sidan får dem,
+// så att man alltid kan ta sig tillbaka.
+bool InputManager::eventFilter(QObject *obj, QEvent *ev)
+{
+ // Ctrl+Mellanslag öppnar skärmtangentbordet (för tangentbord/fjärr).
+ if (ev->type() == QEvent::KeyPress && !m_oskActive && qobject_cast<QWindow *>(obj)) {
+ auto *ke = static_cast<QKeyEvent *>(ev);
+ if (ke->key() == Qt::Key_Space && (ke->modifiers() & Qt::ControlModifier)) {
+ emit oskRequested();
+ return true;
+ }
+ }
+ if (m_webMode && !m_oskActive && ev->type() == QEvent::KeyPress && obj == m_window) {
+ auto *ke = static_cast<QKeyEvent *>(ev);
+ const bool ctrl = ke->modifiers() & Qt::ControlModifier;
+ if (ke->key() == Qt::Key_HomePage || (ctrl && ke->key() == Qt::Key_Escape)) {
+ emit homePressed();
+ return true;
+ }
+ if (ke->key() == Qt::Key_Escape || ke->key() == Qt::Key_Back
+ || (ke->modifiers() & Qt::AltModifier && ke->key() == Qt::Key_Left)) {
+ if (!ke->isAutoRepeat())
+ emit backPressed();
+ return true;
+ }
+ }
+ return QObject::eventFilter(obj, ev);
+}
diff --git a/src/inputmanager.h b/src/inputmanager.h
new file mode 100644
index 0000000..dde9ffa
--- /dev/null
+++ b/src/inputmanager.h
@@ -0,0 +1,129 @@
+#pragma once
+
+#include <QHash>
+#include <QObject>
+#include <QPointer>
+#include <QTimer>
+
+struct _SDL_GameController;
+#include <QElapsedTimer>
+#include <QWindow>
+
+#include "virtualinput.h"
+
+// Läser handkontroller via SDL2 och översätter dem till tangenttryck i
+// launchern (piltangenter, Enter, Escape, Menu). SDL läser evdev direkt,
+// så Home-knappen fungerar även när ett annat program har fokus.
+//
+// D-pad / vänster spak -> piltangenter (med repetition)
+// A -> Enter
+// B -> Escape / tillbaka
+// X -> (ledig)
+// Y, Start -> Menu (snabbmeny för vald ruta)
+// Home kort -> till hemskärmen
+// Home långt (0,8 s) -> stäng programmet som körs
+//
+// I webbappar och i program med läget "keyboard" blir kontrollen i stället
+// en virtuell mus och tangentbord (uinput):
+// vänster spak -> muspekare höger spak -> scrolla
+// A -> klick B -> tillbaka X -> Enter Y -> mellanslag
+// LB/RB -> Shift+Tab/Tab LT/RT -> Page Up/Down
+// Start -> Escape Select -> skärmtangentbord
+// L3 -> F (helskärm) R3 -> högerklick
+// I läget "gamepad" (spel, RetroArch) lämnas kontrollen helt åt programmet.
+class InputManager : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(bool connected READ connected NOTIFY connectedChanged)
+ Q_PROPERTY(QString controllerName READ controllerName NOTIFY connectedChanged)
+ Q_PROPERTY(bool webMode READ webMode WRITE setWebMode NOTIFY webModeChanged)
+ // Hur kontrollen ska fungera i externa program: "keyboard" eller "gamepad"
+ Q_PROPERTY(QString externalMode READ externalMode WRITE setExternalMode NOTIFY externalModeChanged)
+ Q_PROPERTY(bool virtualInputAvailable READ virtualInputAvailable NOTIFY virtualInputChanged)
+ // När skärmtangentbordet är öppet styr kontrollen bara det.
+ Q_PROPERTY(bool oskActive READ oskActive WRITE setOskActive NOTIFY oskActiveChanged)
+
+public:
+ explicit InputManager(bool enableGamepad = true, QObject *parent = nullptr);
+ ~InputManager() override;
+
+ void setWindow(QWindow *w) { m_window = w; }
+ void setSuspended(bool s);
+
+ bool connected() const { return !m_controllers.isEmpty(); }
+ QString controllerName() const { return m_name; }
+ bool webMode() const { return m_webMode; }
+ void setWebMode(bool on);
+ QString externalMode() const { return m_externalMode; }
+ void setExternalMode(const QString &mode);
+ bool virtualInputAvailable() const { return m_vi.isOpen(); }
+ bool oskActive() const { return m_oskActive; }
+ void setOskActive(bool on);
+
+ // Fönster som kontrollens tangenttryck ska gå till (skärmtangentbordets
+ // eget fönster över ett externt program); null = launcherns fönster.
+ Q_INVOKABLE void setKeyWindow(QObject *window);
+ // Skriver text i det som har fokus i launchern (fält, inbyggd webbapp).
+ Q_INVOKABLE void typeIntoFocus(const QString &text, bool enter);
+ // Skriver text i externt program via den virtuella tangentbordsenheten.
+ Q_INVOKABLE bool typeExternal(const QString &text, bool enter);
+
+signals:
+ void connectedChanged();
+ void webModeChanged();
+ void backPressed();
+ void homePressed();
+ void homeLongPressed();
+ void externalModeChanged();
+ void virtualInputChanged();
+ // Kontrollen behövde mus/tangentbord men /dev/uinput gick inte att öppna.
+ void virtualInputMissing();
+ void oskActiveChanged();
+ // Select tryckt: öppna skärmtangentbordet.
+ void oskRequested();
+
+protected:
+ bool eventFilter(QObject *obj, QEvent *ev) override;
+
+private:
+ enum Dir { None, Up, Down, Left, Right };
+
+ void poll();
+ void handleButton(int button, bool down);
+ void setDirection(Dir d, bool fromStick);
+ void updateHeld();
+ void sendKey(int key, bool press, bool autoRepeat = false);
+ static int keyFor(Dir d);
+
+ bool wantsEmulation() const;
+ void updateEmulation();
+ void handleEmuButton(int button, bool down);
+ void emuTick();
+ _SDL_GameController *firstController() const;
+
+ QPointer<QWindow> m_window;
+ QPointer<QWindow> m_keyWindow;
+ bool m_oskActive = false;
+ QHash<int, _SDL_GameController *> m_controllers;
+ QString m_name;
+ QTimer m_pollTimer;
+ QTimer m_repeatTimer;
+ QTimer m_homeTimer;
+ bool m_homeLongFired = false;
+ bool m_suspended = false;
+ bool m_webMode = false;
+ bool m_sdlOk = false;
+ QString m_externalMode = "gamepad";
+
+ VirtualInput m_vi;
+ bool m_emulating = false;
+ bool m_warnedMissing = false;
+ QTimer m_emuTimer;
+ QElapsedTimer m_emuClock;
+ double m_wheelAcc = 0, m_moveAccX = 0, m_moveAccY = 0;
+ bool m_ltDown = false, m_rtDown = false;
+
+ Dir m_dpad = None;
+ Dir m_stick = None;
+ Dir m_held = None;
+};
diff --git a/src/main.cpp b/src/main.cpp
new file mode 100644
index 0000000..661d7e4
--- /dev/null
+++ b/src/main.cpp
@@ -0,0 +1,129 @@
+#include <QDir>
+#include <algorithm>
+#include <QKeyEvent>
+#include <QKeySequence>
+#include <QTimer>
+#include <QFile>
+#include <QGuiApplication>
+#include <QIcon>
+#include <QQmlApplicationEngine>
+#include <QQmlContext>
+#include <QQuickStyle>
+#include <QQuickWindow>
+#include <QtWebEngineQuick/qtwebenginequickglobal.h>
+
+#include "appstore.h"
+#include "chromiumapps.h"
+#include "desktopscanner.h"
+#include "iconfetcher.h"
+#include "iconprovider.h"
+#include "inputmanager.h"
+#include "prefs.h"
+#include "processlauncher.h"
+#include "shell.h"
+
+// Utan skrivbordsmiljö (cage) finns inget ikontema satt, så vi väljer ett som finns.
+static void pickIconTheme()
+{
+ if (!QIcon::themeName().isEmpty() && QIcon::themeName() != QLatin1String("hicolor"))
+ return;
+ const QStringList candidates{"breeze-dark", "breeze", "Papirus-Dark", "Papirus", "Adwaita", "hicolor"};
+ for (const QString &name : candidates) {
+ for (const QString &base : QIcon::themeSearchPaths()) {
+ if (QFile::exists(base + "/" + name + "/index.theme")) {
+ QIcon::setThemeName(name);
+ QIcon::setFallbackThemeName("hicolor");
+ return;
+ }
+ }
+ }
+}
+
+int main(int argc, char *argv[])
+{
+ QCoreApplication::setApplicationName("tv-launcher");
+ QtWebEngineQuick::initialize();
+
+ // Genomskinliga fönster (skärmtangentbordet över andra program).
+ QQuickWindow::setDefaultAlphaBuffer(true);
+ QGuiApplication app(argc, argv);
+ QQuickStyle::setStyle("Basic");
+ pickIconTheme();
+
+ const bool windowed = app.arguments().contains("--windowed");
+
+ AppStore store;
+ ProcessLauncher launcher;
+ // I testläget (--screenshot) ska en riktig handkontroll inte störa.
+ const QStringList args = app.arguments();
+ const bool shotMode = std::any_of(args.cbegin(), args.cend(),
+ [](const QString &a) { return a.startsWith("--screenshot="); });
+ InputManager input(!shotMode);
+ DesktopScanner scanner;
+ IconFetcher fetcher;
+ Shell shell;
+ Prefs prefs;
+
+ QObject::connect(&store, &AppStore::iconWanted, &fetcher, &IconFetcher::fetch);
+ QObject::connect(&fetcher, &IconFetcher::iconReady, &store, &AppStore::setIconIfEmpty);
+ store.fetchMissingIcons();
+ ChromiumApps chromiumApps(&store);
+ chromiumApps.scan();
+ // När ett externt program körs ska launchern inte reagera på handkontrollen.
+ QObject::connect(&launcher, &ProcessLauncher::runningChanged, &input,
+ [&] { input.setSuspended(launcher.running()); });
+
+ QQmlApplicationEngine engine;
+ engine.addImageProvider("icon", new IconProvider);
+ engine.rootContext()->setContextProperty("apps", &store);
+ engine.rootContext()->setContextProperty("launcher", &launcher);
+ engine.rootContext()->setContextProperty("input", &input);
+ engine.rootContext()->setContextProperty("scanner", &scanner);
+ engine.rootContext()->setContextProperty("shell", &shell);
+ engine.rootContext()->setContextProperty("prefs", &prefs);
+ engine.rootContext()->setContextProperty("chromiumApps", &chromiumApps);
+ engine.rootContext()->setContextProperty("windowedMode", windowed);
+
+ QObject::connect(&engine, &QQmlApplicationEngine::objectCreationFailed, &app,
+ [] { QCoreApplication::exit(1); }, Qt::QueuedConnection);
+ engine.loadFromModule("TvLauncher", "Main");
+ if (engine.rootObjects().isEmpty())
+ return 1;
+
+ auto *window = qobject_cast<QQuickWindow *>(engine.rootObjects().constFirst());
+ app.installEventFilter(&input);
+ input.setWindow(window);
+
+ // Utvecklarläge: --keys=Down,Right,Menu spelar upp tangenttryck och
+ // --screenshot=fil.png sparar en bild av fönstret och avslutar.
+ QString shotPath;
+ QStringList keys;
+ for (const QString &a : app.arguments()) {
+ if (a.startsWith("--screenshot="))
+ shotPath = a.mid(13);
+ else if (a.startsWith("--keys="))
+ keys = a.mid(7).split(',', Qt::SkipEmptyParts);
+ }
+ if (!shotPath.isEmpty()) {
+ int delay = 2500;
+ for (const QString &k : std::as_const(keys)) {
+ QTimer::singleShot(delay, window, [window, k] {
+ const int code = QKeySequence::fromString(k)[0].toCombined();
+ QKeyEvent press(QEvent::KeyPress, code & ~Qt::KeyboardModifierMask,
+ Qt::KeyboardModifiers(code & Qt::KeyboardModifierMask),
+ k.size() == 1 ? k : QString());
+ QKeyEvent release(QEvent::KeyRelease, code & ~Qt::KeyboardModifierMask,
+ Qt::KeyboardModifiers(code & Qt::KeyboardModifierMask));
+ QCoreApplication::sendEvent(window, &press);
+ QCoreApplication::sendEvent(window, &release);
+ });
+ delay += 400;
+ }
+ QTimer::singleShot(delay + 1000, window, [window, shotPath] {
+ window->grabWindow().save(shotPath);
+ QCoreApplication::quit();
+ });
+ }
+
+ return app.exec();
+}
diff --git a/src/prefs.cpp b/src/prefs.cpp
new file mode 100644
index 0000000..d74f17f
--- /dev/null
+++ b/src/prefs.cpp
@@ -0,0 +1,71 @@
+#include "prefs.h"
+
+#include <QDir>
+#include <QDirIterator>
+#include <QFileInfo>
+#include <QStandardPaths>
+
+Prefs::Prefs(QObject *parent)
+ : QObject(parent)
+ , m_settings(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation) + "/settings.ini",
+ QSettings::IniFormat)
+{
+}
+
+QString Prefs::wallpaper() const { return m_settings.value("wallpaper").toString(); }
+
+void Prefs::setWallpaper(const QString &path)
+{
+ if (path == wallpaper())
+ return;
+ m_settings.setValue("wallpaper", path);
+ emit changed();
+}
+
+qreal Prefs::dim() const { return m_settings.value("dim", 0.35).toReal(); }
+
+void Prefs::setDim(qreal d)
+{
+ d = qBound(0.0, d, 0.9);
+ if (qFuzzyCompare(d, dim()))
+ return;
+ m_settings.setValue("dim", d);
+ emit changed();
+}
+
+void Prefs::set(const QString &key, const QVariant &v)
+{
+ if (m_settings.value(key) == v)
+ return;
+ m_settings.setValue(key, v);
+ emit changed();
+}
+
+QString Prefs::homePath() const { return QDir::homePath(); }
+
+void Prefs::resetTheme()
+{
+ m_settings.remove("theme");
+ emit changed();
+}
+
+QStringList Prefs::findWallpapers() const
+{
+ const QString home = QDir::homePath();
+ const QStringList dirs{home + "/Bilder", home + "/Pictures", home + "/.local/share/wallpapers",
+ "/usr/share/wallpapers", "/usr/share/backgrounds"};
+ QStringList out;
+ for (const QString &dir : dirs) {
+ QDirIterator it(dir, {"*.jpg", "*.jpeg", "*.png", "*.webp"}, QDir::Files,
+ QDirIterator::Subdirectories | QDirIterator::FollowSymlinks);
+ while (it.hasNext() && out.size() < 300) {
+ const QString f = it.next();
+ // Hoppa över förhandsbilder i KDE-bakgrundspaket och små bilder.
+ if (f.contains("/contents/screenshot") || QFileInfo(f).size() < 60 * 1024)
+ continue;
+ out << f;
+ }
+ }
+ out.sort(Qt::CaseInsensitive);
+ return out;
+}
diff --git a/src/prefs.h b/src/prefs.h
new file mode 100644
index 0000000..a53d614
--- /dev/null
+++ b/src/prefs.h
@@ -0,0 +1,58 @@
+#pragma once
+
+#include <QObject>
+#include <QSettings>
+
+// Användarinställningar som inte hör till apparna
+// (~/.config/tv-launcher/settings.ini).
+class Prefs : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(QString wallpaper READ wallpaper WRITE setWallpaper NOTIFY changed)
+ Q_PROPERTY(qreal dim READ dim WRITE setDim NOTIFY changed)
+ // Tema
+ Q_PROPERTY(QString themePreset READ themePreset WRITE setThemePreset NOTIFY changed)
+ Q_PROPERTY(QString accent READ accent WRITE setAccent NOTIFY changed)
+ Q_PROPERTY(qreal tileScale READ tileScale WRITE setTileScale NOTIFY changed)
+ Q_PROPERTY(qreal radiusScale READ radiusScale WRITE setRadiusScale NOTIFY changed)
+ Q_PROPERTY(QString tileMode READ tileMode WRITE setTileMode NOTIFY changed)
+ Q_PROPERTY(qreal tileOpacity READ tileOpacity WRITE setTileOpacity NOTIFY changed)
+ Q_PROPERTY(QString homePath READ homePath CONSTANT)
+
+public:
+ explicit Prefs(QObject *parent = nullptr);
+
+ QString wallpaper() const;
+ void setWallpaper(const QString &path);
+ qreal dim() const;
+ void setDim(qreal d);
+
+ QString themePreset() const { return m_settings.value("theme/preset", "standard").toString(); }
+ void setThemePreset(const QString &v) { set("theme/preset", v); }
+ QString accent() const { return m_settings.value("theme/accent", "#3daee9").toString(); }
+ void setAccent(const QString &v) { set("theme/accent", v); }
+ qreal tileScale() const { return m_settings.value("theme/tileScale", 1.0).toReal(); }
+ void setTileScale(qreal v) { set("theme/tileScale", v); }
+ qreal radiusScale() const { return m_settings.value("theme/radiusScale", 1.0).toReal(); }
+ void setRadiusScale(qreal v) { set("theme/radiusScale", v); }
+
+ // "app" = egen färg per app, "theme" = temats kortfärg, "accent" = accentfärgen
+ QString tileMode() const { return m_settings.value("theme/tileMode", "app").toString(); }
+ void setTileMode(const QString &v) { set("theme/tileMode", v); }
+ qreal tileOpacity() const { return m_settings.value("theme/tileOpacity", 1.0).toReal(); }
+ void setTileOpacity(qreal v) { set("theme/tileOpacity", qBound(0.1, v, 1.0)); }
+ QString homePath() const;
+
+ Q_INVOKABLE void resetTheme();
+
+ // Bilder i ~/Bilder, ~/Pictures och systemets bakgrundsmappar.
+ Q_INVOKABLE QStringList findWallpapers() const;
+
+signals:
+ void changed();
+
+private:
+ void set(const QString &key, const QVariant &v);
+
+ QSettings m_settings;
+};
diff --git a/src/processlauncher.cpp b/src/processlauncher.cpp
new file mode 100644
index 0000000..9ae4521
--- /dev/null
+++ b/src/processlauncher.cpp
@@ -0,0 +1,142 @@
+#include "processlauncher.h"
+
+#include <QDir>
+#include <QFileInfo>
+#include <QStandardPaths>
+#include <QTimer>
+
+ProcessLauncher::ProcessLauncher(QObject *parent) : QObject(parent) {}
+
+ProcessLauncher::~ProcessLauncher()
+{
+ if (m_proc) {
+ m_proc->disconnect(this);
+ m_proc->terminate();
+ m_proc->waitForFinished(2000);
+ }
+}
+
+bool ProcessLauncher::commandExists(const QString &command) const
+{
+ const QStringList parts = QProcess::splitCommand(command);
+ if (parts.isEmpty())
+ return false;
+ // Hoppa över miljövariabler i början, t.ex. "FOO=1 mpv ...".
+ for (const QString &p : parts) {
+ if (p.contains('=') && !p.startsWith('/'))
+ continue;
+ return !QStandardPaths::findExecutable(p).isEmpty()
+ || (p.startsWith('/') && QFileInfo(p).isExecutable());
+ }
+ return false;
+}
+
+bool ProcessLauncher::launchCommand(const QString &name, const QString &command)
+{
+ if (!commandExists(command)) {
+ emit launchFailed(name, tr("Programmet hittades inte: %1").arg(command));
+ return false;
+ }
+ // Via sh så att miljövariabler och citattecken fungerar; exec gör att
+ // SIGTERM når själva programmet.
+ return start(name, "/bin/sh", {"-c", "exec " + command});
+}
+
+bool ProcessLauncher::launchChromium(const QString &name, const QString &id,
+ const QString &url, const QString &userAgent)
+{
+ QString bin;
+ for (const char *c : {"chromium", "chromium-browser", "google-chrome", "google-chrome-stable"}) {
+ bin = QStandardPaths::findExecutable(QString::fromLatin1(c));
+ if (!bin.isEmpty())
+ break;
+ }
+ if (bin.isEmpty()) {
+ emit launchFailed(name, tr("Chromium är inte installerat (sudo apt install chromium)"));
+ return false;
+ }
+ // Egen profil per webbapp så att inloggningar hålls isär och sparas.
+ const QString profile = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)
+ + "/chromium/" + id;
+ QDir().mkpath(profile);
+ QStringList args{"--ozone-platform=wayland",
+ "--kiosk",
+ "--app=" + url,
+ "--user-data-dir=" + profile,
+ "--no-first-run",
+ "--noerrdialogs",
+ "--disable-session-crashed-bubble",
+ "--enable-features=VaapiVideoDecodeLinuxGL"};
+ if (!userAgent.isEmpty())
+ args << "--user-agent=" + userAgent;
+ return start(name, bin, args);
+}
+
+bool ProcessLauncher::launchChromiumApp(const QString &name, const QString &bin,
+ const QString &profile, const QString &appId)
+{
+ QString program = bin;
+ if (program.isEmpty() || !QFileInfo(program).isExecutable())
+ program = QStandardPaths::findExecutable("chromium");
+ if (program.isEmpty()) {
+ emit launchFailed(name, tr("Chromium är inte installerat"));
+ return false;
+ }
+ return start(name, program, {"--profile-directory=" + (profile.isEmpty() ? QString("Default") : profile),
+ "--app-id=" + appId,
+ "--ozone-platform=wayland",
+ "--start-fullscreen"});
+}
+
+bool ProcessLauncher::start(const QString &name, const QString &program, const QStringList &args)
+{
+ if (m_proc)
+ stop();
+
+ auto *p = new QProcess(this);
+ p->setProcessChannelMode(QProcess::ForwardedChannels);
+ p->setProgram(program);
+ p->setArguments(args);
+
+ connect(p, &QProcess::errorOccurred, this, [this, p, name](QProcess::ProcessError e) {
+ if (e == QProcess::FailedToStart) {
+ emit launchFailed(name, p->errorString());
+ if (m_proc == p) {
+ m_proc = nullptr;
+ m_name.clear();
+ emit runningChanged();
+ }
+ p->deleteLater();
+ }
+ });
+ connect(p, &QProcess::finished, this, [this, p](int code, QProcess::ExitStatus) {
+ qInfo("%s avslutades (kod %d)", qPrintable(m_name), code);
+ if (m_proc == p) {
+ m_proc = nullptr;
+ m_name.clear();
+ emit runningChanged();
+ }
+ p->deleteLater();
+ });
+
+ m_proc = p;
+ m_name = name;
+ p->start();
+ emit runningChanged();
+ return true;
+}
+
+void ProcessLauncher::stop()
+{
+ if (!m_proc)
+ return;
+ QPointer<QProcess> p = m_proc;
+ p->terminate();
+ QTimer::singleShot(3000, this, [p] {
+ if (p && p->state() != QProcess::NotRunning)
+ p->kill();
+ });
+}
+
+void ProcessLauncher::powerOff() { QProcess::startDetached("systemctl", {"poweroff"}); }
+void ProcessLauncher::reboot() { QProcess::startDetached("systemctl", {"reboot"}); }
diff --git a/src/processlauncher.h b/src/processlauncher.h
new file mode 100644
index 0000000..f6971fd
--- /dev/null
+++ b/src/processlauncher.h
@@ -0,0 +1,42 @@
+#pragma once
+
+#include <QObject>
+#include <QPointer>
+#include <QProcess>
+
+// Startar externa program (RetroArch, mpv, Chromium-webbappar ...).
+// Ett program i taget: cage visar det överst i helskärm och när det
+// avslutas syns launchern igen.
+class ProcessLauncher : public QObject
+{
+ Q_OBJECT
+ Q_PROPERTY(bool running READ running NOTIFY runningChanged)
+ Q_PROPERTY(QString runningName READ runningName NOTIFY runningChanged)
+
+public:
+ explicit ProcessLauncher(QObject *parent = nullptr);
+ ~ProcessLauncher() override;
+
+ bool running() const { return m_proc != nullptr; }
+ QString runningName() const { return m_name; }
+
+ Q_INVOKABLE bool launchCommand(const QString &name, const QString &command);
+ Q_INVOKABLE bool launchChromium(const QString &name, const QString &id,
+ const QString &url, const QString &userAgent);
+ Q_INVOKABLE bool launchChromiumApp(const QString &name, const QString &bin,
+ const QString &profile, const QString &appId);
+ Q_INVOKABLE void stop();
+ Q_INVOKABLE void powerOff();
+ Q_INVOKABLE void reboot();
+ Q_INVOKABLE bool commandExists(const QString &command) const;
+
+signals:
+ void runningChanged();
+ void launchFailed(const QString &name, const QString &error);
+
+private:
+ bool start(const QString &name, const QString &program, const QStringList &args);
+
+ QPointer<QProcess> m_proc;
+ QString m_name;
+};
diff --git a/src/shell.cpp b/src/shell.cpp
new file mode 100644
index 0000000..e7d281c
--- /dev/null
+++ b/src/shell.cpp
@@ -0,0 +1,51 @@
+#include "shell.h"
+
+#include <QPointer>
+#include <memory>
+#include <QProcess>
+#include <QStandardPaths>
+#include <QTimer>
+
+bool Shell::has(const QString &program) const
+{
+ return !QStandardPaths::findExecutable(program).isEmpty();
+}
+
+void Shell::run(const QString &program, const QStringList &args, const QJSValue &callback, int timeoutMs)
+{
+ auto *p = new QProcess(this);
+ // Engelsk utdata så att den går att tolka oavsett systemspråk.
+ QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
+ env.insert("LC_ALL", "C.UTF-8");
+ p->setProcessEnvironment(env);
+
+ auto done = std::make_shared<bool>(false);
+ auto finish = [this, p, callback, done](int code, const QString &out, const QString &err) {
+ if (*done)
+ return;
+ *done = true;
+ if (callback.isCallable()) {
+ QJSValue cb = callback;
+ cb.call({QJSValue(code), QJSValue(out), QJSValue(err)});
+ }
+ p->deleteLater();
+ };
+
+ connect(p, &QProcess::finished, this, [p, finish](int code, QProcess::ExitStatus status) {
+ finish(status == QProcess::NormalExit ? code : -1,
+ QString::fromUtf8(p->readAllStandardOutput()),
+ QString::fromUtf8(p->readAllStandardError()));
+ });
+ connect(p, &QProcess::errorOccurred, this, [p, finish](QProcess::ProcessError e) {
+ if (e == QProcess::FailedToStart)
+ finish(-1, QString(), p->errorString());
+ });
+
+ QPointer<QProcess> guard(p);
+ QTimer::singleShot(timeoutMs, this, [guard] {
+ if (guard && guard->state() != QProcess::NotRunning)
+ guard->kill();
+ });
+
+ p->start(program, args);
+}
diff --git a/src/shell.h b/src/shell.h
new file mode 100644
index 0000000..117db71
--- /dev/null
+++ b/src/shell.h
@@ -0,0 +1,18 @@
+#pragma once
+
+#include <QJSValue>
+#include <QObject>
+
+// Kör systemkommandon asynkront åt inställningssidorna (wpctl, bluetoothctl,
+// nmcli ...). Resultatet skickas till en JS-funktion:
+// shell.run("wpctl", ["status"], (code, out, err) => { ... })
+class Shell : public QObject
+{
+ Q_OBJECT
+public:
+ using QObject::QObject;
+
+ Q_INVOKABLE bool has(const QString &program) const;
+ Q_INVOKABLE void run(const QString &program, const QStringList &args,
+ const QJSValue &callback = QJSValue(), int timeoutMs = 30000);
+};
diff --git a/src/virtualinput.cpp b/src/virtualinput.cpp
new file mode 100644
index 0000000..2f81381
--- /dev/null
+++ b/src/virtualinput.cpp
@@ -0,0 +1,163 @@
+#include "virtualinput.h"
+
+#include <QHash>
+#include <QtGlobal>
+
+#include <cstring>
+#include <fcntl.h>
+#include <linux/uinput.h>
+#include <sys/ioctl.h>
+#include <unistd.h>
+
+VirtualInput::~VirtualInput()
+{
+ if (m_fd >= 0) {
+ releaseAll();
+ ioctl(m_fd, UI_DEV_DESTROY);
+ ::close(m_fd);
+ }
+}
+
+bool VirtualInput::open()
+{
+ if (m_fd >= 0)
+ return true;
+ const int fd = ::open("/dev/uinput", O_WRONLY | O_NONBLOCK | O_CLOEXEC);
+ if (fd < 0)
+ return false;
+
+ ioctl(fd, UI_SET_EVBIT, EV_KEY);
+ // Alla vanliga tangenter (KEY_ESC..KEY_102ND) samt navigering och musknappar.
+ for (int code = KEY_ESC; code <= KEY_102ND; ++code)
+ ioctl(fd, UI_SET_KEYBIT, code);
+ for (int code : {KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_RIGHTALT, KEY_PAGEUP,
+ KEY_PAGEDOWN, KEY_HOME, KEY_END, KEY_DELETE, BTN_LEFT, BTN_RIGHT, BTN_MIDDLE})
+ ioctl(fd, UI_SET_KEYBIT, code);
+ ioctl(fd, UI_SET_EVBIT, EV_REL);
+ for (int code : {REL_X, REL_Y, REL_WHEEL, REL_HWHEEL})
+ ioctl(fd, UI_SET_RELBIT, code);
+
+ uinput_setup setup;
+ std::memset(&setup, 0, sizeof(setup));
+ setup.id.bustype = BUS_VIRTUAL;
+ setup.id.vendor = 0x1209;
+ setup.id.product = 0x7476;
+ std::strncpy(setup.name, "tv-launcher virtual input", UINPUT_MAX_NAME_SIZE - 1);
+ if (ioctl(fd, UI_DEV_SETUP, &setup) < 0 || ioctl(fd, UI_DEV_CREATE) < 0) {
+ ::close(fd);
+ return false;
+ }
+ m_fd = fd;
+ return true;
+}
+
+void VirtualInput::write(int type, int code, int value)
+{
+ input_event ev;
+ std::memset(&ev, 0, sizeof(ev));
+ ev.type = type;
+ ev.code = code;
+ ev.value = value;
+ if (::write(m_fd, &ev, sizeof(ev)) < 0) {
+ // Ignorera; nästa händelse försöker igen.
+ }
+}
+
+void VirtualInput::sync() { write(EV_SYN, SYN_REPORT, 0); }
+
+void VirtualInput::key(int code, bool down)
+{
+ if (m_fd < 0 || down == m_down.contains(code))
+ return;
+ if (down) m_down.insert(code); else m_down.remove(code);
+ write(EV_KEY, code, down ? 1 : 0);
+ sync();
+}
+
+void VirtualInput::move(int dx, int dy)
+{
+ if (m_fd < 0 || (dx == 0 && dy == 0))
+ return;
+ if (dx) write(EV_REL, REL_X, dx);
+ if (dy) write(EV_REL, REL_Y, dy);
+ sync();
+}
+
+void VirtualInput::wheel(int steps, bool horizontal)
+{
+ if (m_fd < 0 || steps == 0)
+ return;
+ write(EV_REL, horizontal ? REL_HWHEEL : REL_WHEEL, steps);
+ sync();
+}
+
+void VirtualInput::releaseAll()
+{
+ const auto down = m_down;
+ for (int code : down)
+ key(code, false);
+}
+
+namespace {
+struct KeyStroke { int code; bool shift; bool altgr; };
+
+// Svensk layout (xkb "se").
+const QHash<QChar, KeyStroke> &swedishMap()
+{
+ static const QHash<QChar, KeyStroke> map = [] {
+ QHash<QChar, KeyStroke> m;
+ auto row = [&m](const char *chars, int first) {
+ for (int i = 0; chars[i]; ++i) {
+ m.insert(QChar(chars[i]), {first + i, false, false});
+ m.insert(QChar(chars[i]).toUpper(), {first + i, true, false});
+ }
+ };
+ row("qwertyuiop", KEY_Q);
+ row("asdfghjkl", KEY_A);
+ row("zxcvbnm", KEY_Z);
+ const char *digits = "1234567890";
+ const char *shifted = "!\"#\0%&/()="; // ¤ på 4 hoppas över
+ for (int i = 0; i < 10; ++i) {
+ m.insert(QChar(digits[i]), {KEY_1 + i, false, false});
+ if (shifted[i]) m.insert(QChar(shifted[i]), {KEY_1 + i, true, false});
+ }
+ auto add = [&m](QChar c, int code, bool shift = false, bool altgr = false) {
+ m.insert(c, {code, shift, altgr});
+ };
+ add(QChar(0xe5), KEY_LEFTBRACE); add(QChar(0xc5), KEY_LEFTBRACE, true); // å Å
+ add(QChar(0xe4), KEY_APOSTROPHE); add(QChar(0xc4), KEY_APOSTROPHE, true); // ä Ä
+ add(QChar(0xf6), KEY_SEMICOLON); add(QChar(0xd6), KEY_SEMICOLON, true); // ö Ö
+ add('+', KEY_MINUS); add('?', KEY_MINUS, true); add('\\', KEY_MINUS, false, true);
+ add('\'', KEY_BACKSLASH); add('*', KEY_BACKSLASH, true);
+ add(',', KEY_COMMA); add(';', KEY_COMMA, true);
+ add('.', KEY_DOT); add(':', KEY_DOT, true);
+ add('-', KEY_SLASH); add('_', KEY_SLASH, true);
+ add('<', KEY_102ND); add('>', KEY_102ND, true); add('|', KEY_102ND, false, true);
+ add('@', KEY_2, false, true); add(QChar(0xa3), KEY_3, false, true); // @ £
+ add('$', KEY_4, false, true); add(QChar(0x20ac), KEY_E, false, true); // $ €
+ add('{', KEY_7, false, true); add('[', KEY_8, false, true);
+ add(']', KEY_9, false, true); add('}', KEY_0, false, true);
+ add(' ', KEY_SPACE); add('\n', KEY_ENTER); add('\t', KEY_TAB);
+ return m;
+ }();
+ return map;
+}
+} // namespace
+
+void VirtualInput::typeText(const QString &text)
+{
+ if (m_fd < 0)
+ return;
+ const auto &map = swedishMap();
+ for (const QChar c : text) {
+ const auto it = map.constFind(c);
+ if (it == map.cend())
+ continue;
+ if (it->shift) key(KEY_LEFTSHIFT, true);
+ if (it->altgr) key(KEY_RIGHTALT, true);
+ key(it->code, true);
+ key(it->code, false);
+ if (it->altgr) key(KEY_RIGHTALT, false);
+ if (it->shift) key(KEY_LEFTSHIFT, false);
+ }
+}
diff --git a/src/virtualinput.h b/src/virtualinput.h
new file mode 100644
index 0000000..e2aceab
--- /dev/null
+++ b/src/virtualinput.h
@@ -0,0 +1,34 @@
+#pragma once
+
+#include <QSet>
+#include <QString>
+
+// Virtuell mus och tangentbord via /dev/uinput. Kompositorn (cage) ser den
+// som en vanlig enhet, så tryck och musrörelser går till det program som
+// har fokus: webbappar, Chromium, andra program.
+//
+// Kräver skrivrätt till /dev/uinput (se scripts/setup-uinput.sh).
+class VirtualInput
+{
+public:
+ ~VirtualInput();
+
+ bool open(); // skapar enheten; false om behörighet saknas
+ bool isOpen() const { return m_fd >= 0; }
+
+ void key(int code, bool down);
+ void move(int dx, int dy);
+ void wheel(int steps, bool horizontal = false);
+ void releaseAll();
+
+ // Skriver text tecken för tecken. Utgår från svensk layout (se), som
+ // tv-session.sh ställer in för cage. Tecken som saknas hoppas över.
+ void typeText(const QString &text);
+
+private:
+ void write(int type, int code, int value);
+ void sync();
+
+ int m_fd = -1;
+ QSet<int> m_down;
+};