From 8fa73ff6f9be0d3e8d1d4c3e20ea7ca92336d719 Mon Sep 17 00:00:00 2001 From: Michatec Date: Wed, 29 Jul 2026 19:45:08 +0200 Subject: [PATCH 1/8] feat: add web remote control with translations - Implement embedded Ktor remote control server (port 8080) - Add REST API endpoints for play/pause/next/prev/status - Add web UI with localization support - Add remote control preference toggle and settings integration - Translate remote control strings to all supported languages --- README.md | 1 + SECURITY.md | 6 +- app/build.gradle.kts | 15 + app/src/main/assets/web/favicon.png | Bin 0 -> 4685 bytes app/src/main/assets/web/index.html | 169 +++++++++ app/src/main/assets/web/script.js | 280 +++++++++++++++ app/src/main/assets/web/style.css | 340 ++++++++++++++++++ app/src/main/assets/web/translations.json | 202 +++++++++++ app/src/main/java/com/michatec/radio/Keys.kt | 2 + .../java/com/michatec/radio/MainActivity.kt | 35 ++ .../java/com/michatec/radio/PlayerService.kt | 55 +++ .../com/michatec/radio/SettingsFragment.kt | 44 ++- .../michatec/radio/helpers/NetworkHelper.kt | 15 + .../radio/helpers/PreferencesHelper.kt | 12 + .../radio/helpers/RemoteControlServer.kt | 274 ++++++++++++++ app/src/main/res/values-da/strings.xml | 6 + app/src/main/res/values-de/strings.xml | 6 + app/src/main/res/values-el/strings.xml | 6 + app/src/main/res/values-fr/strings.xml | 6 + app/src/main/res/values-ja/strings.xml | 8 +- app/src/main/res/values-nl/strings.xml | 6 + app/src/main/res/values-pl/strings.xml | 5 + app/src/main/res/values-ru/strings.xml | 6 + app/src/main/res/values-uk/strings.xml | 6 + app/src/main/res/values/strings.xml | 6 + gradle/libs.versions.toml | 8 + 26 files changed, 1511 insertions(+), 8 deletions(-) create mode 100644 app/src/main/assets/web/favicon.png create mode 100644 app/src/main/assets/web/index.html create mode 100644 app/src/main/assets/web/script.js create mode 100644 app/src/main/assets/web/style.css create mode 100644 app/src/main/assets/web/translations.json create mode 100644 app/src/main/java/com/michatec/radio/helpers/RemoteControlServer.kt diff --git a/README.md b/README.md index 832f9aa..c1858e1 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ **Radio is an application with a minimalist approach to listening to radio over the Internet.**
**Radio only offers a very basic search option, and it imports audio streaming links when you tap them in a web browser.**
**Radio now also supports Android TV and Cast to Devices (Beta) with the Version 14.5 and above.**
+**New Feature Update: Web Control with API for devs.**
**Pull request are welcome at any time.**
**Radio is free software. It is released under the [GPLv3 open source license](https://opensource.org/licenses/GPL-3.0).** diff --git a/SECURITY.md b/SECURITY.md index 71b80b8..54e95ca 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -18,9 +18,9 @@ We appreciate responsible disclosure and will credit researchers who report vali ## Supported Versions | Version | Supported | -| ------- | ------------------ | -| > 14.5 | :white_check_mark: | -| < 14.5 | :x: | +|---------| ------------------ | +| > 15 | :white_check_mark: | +| < 15 | :x: | Only the latest stable release receives security updates. Users on older versions are encouraged to update. diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 2f31802..79332dd 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -1,5 +1,6 @@ plugins { alias(libs.plugins.android.application) + alias(libs.plugins.kotlin.serialization) id("kotlin-parcelize") } @@ -52,6 +53,13 @@ android { version = "3.22.1" } } + + packaging { + resources { + excludes += "/META-INF/INDEX.LIST" + excludes += "/META-INF/io.netty.versions.properties" + } + } } dependencies { @@ -78,6 +86,13 @@ dependencies { implementation(libs.freedroidwarn) + // Ktor // + implementation(libs.ktor.server.core) + implementation(libs.ktor.server.netty) + implementation(libs.ktor.server.content.negotiation) + implementation(libs.ktor.serialization.kotlinx.json) + implementation(libs.ktor.serialization.gson) + // Volley HTTP request // implementation(libs.volley) implementation(libs.material3) diff --git a/app/src/main/assets/web/favicon.png b/app/src/main/assets/web/favicon.png new file mode 100644 index 0000000000000000000000000000000000000000..ade7dcd3cb3b1b794f5cb1198ba4120586d25bed GIT binary patch literal 4685 zcmb_gXHe74xBexe2n3Mcq!*DEA}SzV0YR!tM- z0tKnPKlz9f02rCI)zyqp)@vD5zD6UUC`#duQ2`THbBKD!ceerR3pmlb3sh~i%nV{i zWFND$vm$g7wL3E3lC2>tVu~v5%G_FC%z%rPrrZzQ)*c`DSZEOT&o}yXG6S5xb6xEY zt|6lP0z^6kWqds6iPKj222U{PMYibwp~MLfN*eADJlD`rsAaP*SBOcaQ3POSnTtOe zr+$j-+=DaAU-2)KR*x+y$db4whn{F4uhH>0;F|~2V`*wtYBewVugWzGWJe^v`F%Px zr5E@~5;mXmt7!*R7&IRec4U1aw3eVM6!&>q^7)Pxzuj!-ibr z?7q3IM%;xX_vaZ=g{7OEWX<;XL2__USGk^IdTo(S##*(U7mv>b6j`_4r8r#IW?&}ThWjOJ7dqMG>p9jzOK{LXq@PtSt27QA zCRJLtL2>DRJHBs!2x^IwpfxOkdHm72D-$e@zJxZ-WRwPflFuR|r~ou*ru($WLjmm@ zeE>AmYwH%O_W|e`bMC<=N1F3hKxje^;Qk!#H0_)14H6^0 zSYY=h8J5W&Pyj+XfJAC`!0s9pfOAq{*l8iEu_Oe|7T{uzE%0nm8o;^y2c}iQu_+r$ zwjA2zhttc%4PPu!jleHE-Fsjvo{1{8xHSGim~Op5M4OB_+)f~V%l)R`Q*)Dfk7yta z#lpv{8`Ms>44)qMuMmV`Ro65_=?Wr1iMtelV3s?Ykr_})acBW>;h+u)D25S& z5QSpyYeEwG;J`c<9b9_Xk21|yMZGog(BfvUPQM9oqi2@%CNTll{x(h&s-0t?!xM4B@9_T7XXd6t z0pV;B7)MUnDy;=*czTQ$#ZzlrUZVSW;y0Y|yR_QXIdbKbFcg#M3E2z|jA~RcyWCe@ z?c;nFhY92jL!=zGiw|y~B^rrFhCL5o@$CHKs~-8vm6sySO0t1LHtQC|ak*=>cDG!2 zS47eZQl1n^-4lp(NI%H63Lh&o;ao?BD3_2u^U?fOO~x~CPbr&vpI zivwvtAr~i&FIy(K!H3~y?R;G5y4kp(l>-A$kBYFWqvNwWb)9^ZkokQI_>zFJv+l^Z zt|pJk(Tm16E<-WFM2EyLV)VblXzv>xjl2udicWt%zo!|qf z&b+i%Pdbw>A`>J*>_`AmnPk&l3PEQ}B)6%H?je8riU8BWVxpOW)pr$%F3FXsjs9qH z+}c6DHyDx-LNZ7_(r!ODuHuVT3A!0Jp}>Oiq->>`F8uoD`suOir^6)0K736pAY{{c z0c*^W{ve*bR&Cs#u2Qt2I^hp_hfU=tu{HDH^dD7X@!$#U5 zP#H)i@5I#;%dkcttxdR;0BQMJ-GeCiLN(vAIq~4g0ID@ zrepbEy8MCt5bqRGYZf<1$x=EW0+{UH0ijlEUgR$XfmUS(y4`Xp5g!zHn#!7nuAai) z7cn;_Vmrp85wN*o2;c>$9nPMKsOP@?y@W^IrrNvx(LVT{1RFGXrV;<0>Q%d^`$XL*vpw*v~o*g*VWl z1p+ycgUH}&_P!!TUf>~Q;Qb2ue97}^^6#Gqw?FqtM7JT>B@?VgxJjY11HxwH?2%3i zy}9@GX0wS_&)j0aj&QXJ(tt%4CnV5M38V+Q2ECl4C>;9Hy+l?7!r zu&MRlSO=NQ^IN^#u;_ir-(^7NsYT^wi|`$jr-cNLprca?NY-2$fG~0Ni=u29&yU-B zW_?5DJ0MC5D4^;j)jx3F0YA@X8~b+*iyP&UUuqWDRawJ#RAu+8g)P2Wq3jHxV+rw{Lqy zOLlx{Q2UY=?M?AUMfUng+ZmmsF7y)WV^?jff;GBKktfZ?>w(nSxS2F?w~+=wDInc( zzE6M{eCaFUSC)bi8yhqhT*m1oPvJOj!rpIB*d1Qt)aA%~rZ3A_kj@&RJ>@4cUlsD3 zl;aleKf@&r0zx+_ydu*6;Ds$CjQpcZ&B<2|2A3B%rWwW$k(LgEb#&ik8;{j}8#1_T z(-BI80ZrVYr@6oEc;lyh#&rsLOa6Vt+JAw^XLMhfzx7EBVRNdGsNR9B_atalwNrF| zF!gw@V*m7t)tP+XOKE+PlveBMc&YfX!d{2FLlV5Dmp%_PIm=ddpp@hS5Jh=wMhlNnmgQ!p5uxWZ=oepl%wBk)Cp2pj z03*=NBrPr2d6_%-vR(6kR=oYcmEo2taMuFw3}{{53IU>M(?)fa_qmnrTXf9_h$Q7& zUAQ`bXXJKb2bw5(L6mvop8L`m>%3|JivH6&7DX(!j1-FhcT^)_k9; z^P{9y4riT`J=*-&#h1ZexA+VPZYyVNb0!4a{#hZZXdYV*%o}tdp)7+}vv(Yjeay8g6XzdR0|nZdRnK-95NS&5(HUj`uBYpL2h>OUM!hYIW{)xk1!|0KU6= zfd2JUjwezB1&OQafrOHRi%;UssN#y5`K3zx&hNBIer6TSwK}k0DuQ>}LypDz1MQ)h zTj`=pBUKw&;oIJa37z7jS)JdpPwhd-ko;l;{7?eBvF~g4geC{U`jNbTtlFjp&L@*v zwO=*MhNxO%-9qTki%<2QI?L;Cy3;{@$(SFZqdJ-014Ap{oUiw=bD8amp1DGhT!MGI zbxt=g|ggNL$E*7PlF9Cs6e_(U~>JYDTzqM)S_cf~Wizly*|f z0x5nUx;101jD$6N8}C7t>|0xgZoig*T`{nYrHXHM&twOFA$=pkskEGze>)vR?X9X65Xdm3U8ukgb7y+GS56F zih$yQPzekTEAodFnma9dgi>4cLatWdBEI3IA}o(ZLP0psMUS{@?tT)_ubHUiGj&B? zW(-TSNmdVv7cIfcT%PTT*JeRcWkysf2JTm})QBLiKNwA(#e7zcyHv&8aaXTzIrQo+ z=?OXrzj+r8gXeB0xJ0zS;w`UrM4qC|0k45*x&`MT4;cDTS|*7bYh=R5mv(KUf*)$$ z(BH8OG`T`k}q5FE;!SX(j5N{+^De9&LlST zh`|u9>-Ztj1rLbn^|YLy&XS|Rc(2T@P|vWubhT17M=I~2>~4-G!HHyHr`z|KHU8J) cXHBGR&+ns25(`%*rHKG-4Sn_ETZoAN0zNpRng9R* literal 0 HcmV?d00001 diff --git a/app/src/main/assets/web/index.html b/app/src/main/assets/web/index.html new file mode 100644 index 0000000..a71c476 --- /dev/null +++ b/app/src/main/assets/web/index.html @@ -0,0 +1,169 @@ + + + + + Radio Remote + + + + + + +
+
+

Radio Remote

+ +
+ +
+
+
+
+
Loading...
+ +
+ Station +
+
Loading...
+
+ + + +
+
+ +
+

Station Collection

+
+
+
+ +
+
+
+ +

API Documentation

+
+
+

The Radio app provides a REST API to control playback and query information.

+ +

API Reference

+ +
+

GET /api/status

+

Returns current playback status.

+
Response Example:
+
+{
+  "isPlaying": true,
+  "currentStationUuid": "fc080549-...",
+  "metadata": "Artist - Title"
+}                   
+
+ +
+

GET /api/stations

+

Returns all stations in collection.

+
Response Example:
+
+[
+  {
+    "uuid": "fc080549-...",
+    "name": "Station Name",
+    "hasImage": true
+  }
+]                   
+
+ +
+

GET /api/image/{uuid}

+

Returns the image for a specific station.

+
Response: Image (binary data, JPEG)
+
+ +
+

GET /api/config

+

Returns the app version.

+
Response Example:
+
{ "version": "15.1" }
+
+ +
+

POST /api/play/{uuid}

+

Starts playback of a specific station.

+
Response Example:
+
{ "status": "ok" }
+
+ +
+

POST /api/pause

+

Pauses current playback.

+
Response Example:
+
{ "status": "ok" }
+
+ +
+

POST /api/resume

+

Resumes current playback.

+
Response Example:
+
{ "status": "ok" }
+
+ +
+

POST /api/next

+

Plays the next station.

+
Response Example:
+
{ "status": "ok" }
+
+ +
+

POST /api/prev

+

Plays the previous station.

+
Response Example:
+
{ "status": "ok" }
+
+
+
+
+ + +
+ + + diff --git a/app/src/main/assets/web/script.js b/app/src/main/assets/web/script.js new file mode 100644 index 0000000..3557f5a --- /dev/null +++ b/app/src/main/assets/web/script.js @@ -0,0 +1,280 @@ +let currentLang = 'en'; +let translations = {}; +let allStations = []; +let isUpdating = false; +const STATE_IDLE = 1; +const STATE_BUFFERING = 2; +const STATE_READY = 3; +const STATE_ENDED = 4; + +function t(key) { + return (translations[currentLang] && translations[currentLang][key]) || + (translations['en'] && translations['en'][key]) || key; +} + +function updateUILanguage() { + document.querySelectorAll('[data-t]').forEach(el => { + const key = el.getAttribute('data-t'); + const text = t(key); + if (el.tagName === 'INPUT' && el.placeholder) { + el.placeholder = text; + } else { + el.innerText = text; + } + }); +} + +async function loadTranslations() { + try { + const res = await fetch('/translations.json'); + translations = await res.json(); + updateUILanguage(); + } catch (e) { + console.error("Failed to load translations", e); + } +} + +async function updateStatus() { + if (isUpdating) return; + const statusEl = document.getElementById('status'); + const playPauseIcon = document.getElementById('playPauseIcon'); + const currentNameEl = document.getElementById('currentName'); + const currentMetadataEl = document.getElementById('currentMetadata'); + const currentImageEl = document.getElementById('currentImage'); + + try { + const response = await fetch('/api/status'); + if (!response.ok) return; + + const data = await response.json(); + if (data.error) { + statusEl.innerText = t('status_error') + ': ' + data.error; + } else { + let statusText = data.isPlaying ? t('status_playing') : t('status_paused'); + if (data.playbackState === STATE_BUFFERING) { + statusText = "Buffering..."; + } + statusEl.innerText = statusText; + playPauseIcon.innerText = data.isPlaying ? 'pause' : 'play_arrow'; + + const stationUuid = data.currentStationUuid; + updateActiveStation(stationUuid); + + const station = allStations.find(s => s.uuid === stationUuid); + if (station) { + currentNameEl.innerText = station.name; + currentMetadataEl.innerText = data.metadata || ""; + currentImageEl.src = station.hasImage ? '/api/image/' + station.uuid : 'favicon.png'; + } else { + currentNameEl.innerText = data.isPlaying ? 'Unknown Station' : 'No Station Selected'; + currentMetadataEl.innerText = ""; + currentImageEl.src = 'favicon.png'; + } + + if (themeSelect.value === 'auto_browser') { + applyThemeUI(getBrowserTheme()); + } + + if (langSelect.value === 'auto_browser') { + const browserLang = navigator.language.split('-')[0]; + const targetLang = translations[browserLang] ? browserLang : 'en'; + if (targetLang !== currentLang) { + currentLang = targetLang; + updateUILanguage(); + } + } + } + } catch (e) { + console.error("Status fetch failed", e); + } +} + +async function loadStations() { + const list = document.getElementById('stationList'); + try { + const response = await fetch('/api/stations'); + if (!response.ok) return; + allStations = await response.json(); + list.innerHTML = ''; + if (allStations.length === 0) { + list.innerText = t('stations_empty'); + return; + } + allStations.forEach(station => { + const div = document.createElement('div'); + div.className = 'station-item'; + div.id = 'station-' + station.uuid; + + const img = document.createElement('img'); + img.className = 'station-img'; + if (station.hasImage) { + img.src = '/api/image/' + station.uuid; + } else { + img.src = 'favicon.png'; + } + div.appendChild(img); + + const name = document.createElement('div'); + name.className = 'station-name'; + name.innerText = station.name || 'Unnamed Station'; + div.appendChild(name); + + div.onclick = () => playStation(station.uuid); + list.appendChild(div); + }); + updateStatus(); + } catch (e) { + console.error("Load stations failed", e); + } +} + +function updateActiveStation(uuid) { + document.querySelectorAll('.station-item').forEach(el => el.classList.remove('active')); + if (!uuid) return; + const active = document.getElementById('station-' + uuid); + if (active) active.classList.add('active'); +} + +async function playStation(uuid) { + updateActiveStation(uuid); + document.getElementById('status').innerText = "Starting..."; + document.getElementById('playPauseIcon').innerText = 'pause'; + + const station = allStations.find(s => s.uuid === uuid); + if (station) { + document.getElementById('currentName').innerText = station.name; + document.getElementById('currentMetadata').innerText = ""; + document.getElementById('currentImage').src = station.hasImage ? '/api/image/' + station.uuid : 'favicon.png'; + } + + try { + await fetch('/api/play/' + uuid, { method: 'POST' }); + setTimeout(updateStatus, 300); + } catch (e) { console.error(e); } +} + +document.getElementById('playPauseBtn').onclick = async () => { + const icon = document.getElementById('playPauseIcon'); + const isPlaying = icon.innerText === 'pause'; + + icon.innerText = isPlaying ? 'play_arrow' : 'pause'; + document.getElementById('status').innerText = isPlaying ? t('status_paused') : t('status_playing'); + + try { + if (isPlaying) { + await fetch('/api/pause', { method: 'POST' }); + } else { + await fetch('/api/resume', { method: 'POST' }); + } + setTimeout(updateStatus, 300); + } catch (e) { console.error(e); } +}; + +document.getElementById('prevBtn').onclick = () => { + fetch('/api/prev', { method: 'POST' }).then(() => setTimeout(updateStatus, 300)); +}; +document.getElementById('nextBtn').onclick = () => { + fetch('/api/next', { method: 'POST' }).then(() => setTimeout(updateStatus, 300)); +}; + +function applyThemeUI(theme) { + document.body.className = theme + '-theme'; +} + +function getBrowserTheme() { + return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; +} + +window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => { + if (themeSelect.value === 'auto_browser') { + applyThemeUI(e.matches ? 'dark' : 'light'); + } +}); + +const themeSelect = document.getElementById('themeSelect'); +themeSelect.onchange = () => { + const val = themeSelect.value; + localStorage.setItem('radio-remote-theme', val); + if (val === 'auto_browser') { + applyThemeUI(getBrowserTheme()); + } else { + applyThemeUI(val); + } + updateStatus(); +}; + +const langSelect = document.getElementById('langSelect'); +langSelect.onchange = () => { + const val = langSelect.value; + localStorage.setItem('radio-remote-lang', val); + if (val === 'auto_browser') { + const browserLang = navigator.language.split('-')[0]; + currentLang = translations[browserLang] ? browserLang : 'en'; + } else { + currentLang = val; + } + updateUILanguage(); + updateStatus(); +}; + +const menuBtn = document.getElementById('menuBtn'); +const closeMenuBtn = document.getElementById('closeMenuBtn'); +const settingsPanel = document.getElementById('settingsPanel'); +const showApiDocsBtn = document.getElementById('showApiDocsBtn'); +const backToDashboard = document.getElementById('backToDashboard'); +const mainDashboard = document.getElementById('mainDashboard'); +const apiDocsView = document.getElementById('apiDocsView'); + +function toggleMenu(e) { + if (e) e.stopPropagation(); + settingsPanel.classList.toggle('hidden'); +} + +menuBtn.onclick = toggleMenu; +closeMenuBtn.onclick = () => settingsPanel.classList.add('hidden'); + +showApiDocsBtn.onclick = () => { + mainDashboard.classList.add('hidden'); + apiDocsView.classList.remove('hidden'); + settingsPanel.classList.add('hidden'); +}; + +backToDashboard.onclick = () => { + apiDocsView.classList.add('hidden'); + mainDashboard.classList.remove('hidden'); +}; + +document.addEventListener('click', (e) => { + if (!settingsPanel.classList.contains('hidden') && + !settingsPanel.contains(e.target) && + !menuBtn.contains(e.target)) { + settingsPanel.classList.add('hidden'); + } +}); + +async function init() { + await loadTranslations(); + + const savedTheme = localStorage.getItem('radio-remote-theme') || 'auto_browser'; + themeSelect.value = savedTheme; + if (savedTheme === 'auto_browser') { + applyThemeUI(getBrowserTheme()); + } else { + applyThemeUI(savedTheme); + } + + const savedLang = localStorage.getItem('radio-remote-lang') || 'auto_browser'; + langSelect.value = savedLang; + if (savedLang === 'auto_browser') { + const browserLang = navigator.language.split('-')[0]; + currentLang = translations[browserLang] ? browserLang : 'en'; + } else { + currentLang = savedLang; + } + + updateUILanguage(); + await loadStations(); + setInterval(updateStatus, 1000); +} + +init(); diff --git a/app/src/main/assets/web/style.css b/app/src/main/assets/web/style.css new file mode 100644 index 0000000..af1a7ec --- /dev/null +++ b/app/src/main/assets/web/style.css @@ -0,0 +1,340 @@ +:root { + --bg-color: #000000; + --card-bg: rgba(25, 25, 25, 0.6); + --text-color: #ffffff; + --accent-color: #0084ff; + --accent-glow: 0 0 15px rgba(0, 132, 255, 0.6); + --glass-blur: blur(20px); + --transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1); +} + +body.light-theme { + --bg-color: #f1f5f9; + --card-bg: rgba(255, 255, 255, 0.95); + --text-color: #1e293b; + --accent-color: #3b82f6; + --accent-glow: 0 4px 20px rgba(59, 130, 246, 0.2); + --glass-blur: blur(8px); +} + +* { box-sizing: border-box; -webkit-tap-highlight-color: transparent; } + +body { + margin: 0; + font-family: 'Inter', -apple-system, system-ui, sans-serif; + background: var(--bg-color); + color: var(--text-color); + transition: background 0.4s ease; + overflow-x: hidden; +} + +.dashboard { + max-width: 1000px; + margin: 0 auto; + padding: 20px; + min-height: 100vh; +} + +header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 30px; + animation: slideDown 0.6s ease-out; + position: relative; + z-index: 101; +} + +h1 { font-size: 1.6rem; font-weight: 800; margin: 0; letter-spacing: -0.5px; } + +.glass { + background: var(--card-bg); + backdrop-filter: var(--glass-blur); + -webkit-backdrop-filter: var(--glass-blur); + border: 1px solid rgba(255, 255, 255, 0.05); + border-radius: 24px; +} + +body.light-theme .glass { + border: 1px solid rgba(255, 255, 255, 0.5); + box-shadow: 0 8px 32px rgba(31, 38, 135, 0.07); +} + +.now-playing { + padding: 30px 40px; + text-align: center; + margin-bottom: 30px; + box-shadow: var(--accent-glow); + animation: fadeIn 0.8s ease-out; +} + +.current-station-info { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 25px; + padding-bottom: 20px; + border-bottom: 1px solid rgba(255,255,255,0.05); +} + +body.light-theme .current-station-info { + border-bottom: 1px solid rgba(0,0,0,0.05); +} + +.current-text-info { + flex: 1; + text-align: left; + overflow: hidden; + margin-right: 20px; +} + +.current-name { + font-size: 1.4rem; + font-weight: 800; + color: var(--accent-color); + text-shadow: var(--accent-glow); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + margin-bottom: 4px; +} + +.current-metadata { + font-size: 0.95rem; + font-weight: 500; + opacity: 0.6; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--text-color); +} + +.current-img { + width: 64px; + height: 64px; + border-radius: 12px; + object-fit: cover; + box-shadow: var(--accent-glow); +} + +.status-badge { + display: inline-block; + padding: 6px 14px; + background: var(--accent-color); + color: white; + border-radius: 12px; + font-size: 0.85rem; + font-weight: 700; + margin-bottom: 25px; + box-shadow: var(--accent-glow); + text-transform: uppercase; +} + +.controls { + display: flex; + justify-content: center; + align-items: center; + gap: 30px; +} + +.icon-btn { + background: none; + border: none; + color: var(--text-color); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + border-radius: 50%; + transition: var(--transition); + padding: 12px; +} + +.icon-btn:hover { background: rgba(128,128,128,0.1); transform: scale(1.1); } +.icon-btn:active { transform: scale(0.9); } + +.icon-btn.large .material-icons { font-size: 42px; } +.icon-btn.x-large { + background: rgba(128,128,128,0.05); + border: 2px solid var(--accent-color); +} +.icon-btn.x-large .material-icons { font-size: 56px; color: var(--accent-color); } +.icon-btn.x-large:hover { box-shadow: var(--accent-glow); } + +.station-section h2 { margin-bottom: 20px; font-weight: 700; opacity: 0.9; font-size: 1.2rem; } + +.station-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(160px, 1fr)); + gap: 16px; +} + +.station-item { + padding: 16px; + background: var(--card-bg); + border-radius: 20px; + text-align: center; + cursor: pointer; + transition: var(--transition); + border: 1px solid rgba(255,255,255,0.03); + display: flex; + flex-direction: column; + align-items: center; + gap: 12px; +} + +body.light-theme .station-item { + border: 1px solid rgba(0,0,0,0.02); + box-shadow: 0 4px 6px rgba(0,0,0,0.02); +} + +.station-item:hover { + transform: translateY(-8px); + background: rgba(128,128,128,0.08); + border-color: var(--accent-color); +} + +.station-item.active { + background: var(--accent-color); + color: white; + box-shadow: var(--accent-glow); + font-weight: 700; +} + +.station-img { + width: 80px; + height: 80px; + border-radius: 12px; + object-fit: cover; + background: rgba(128,128,128,0.05); + border: 1px solid rgba(128,128,128,0.1); +} + +.station-name { + font-size: 0.95rem; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + width: 100%; +} + +.hidden { display: none !important; } + +/* API Documentation */ +.api-container { padding: 30px; margin-top: 20px; } +.api-content pre { + background: #0a0a0a; + padding: 20px; + border-radius: 12px; + color: #00d4ff; + border: 1px solid #222; + font-size: 0.9rem; + overflow-x: auto; +} + +body.light-theme .api-content pre { + background: #f8f9fa; + color: #0066cc; + border: 1px solid #e2e8f0; +} + +.code-example { color: #888; margin-top: 10px; font-size: 0.8rem; } + +/* Settings Panel with Animation */ +.settings-panel { + position: fixed; + top: 0; + right: 0; + height: 100%; + width: 320px; + z-index: 1000; + padding: 30px; + transform: translateX(0); + transition: transform 0.5s cubic-bezier(0.19, 1, 0.22, 1); + box-shadow: -10px 0 30px rgba(0,0,0,0.5); +} + +body.light-theme .settings-panel { + box-shadow: -10px 0 30px rgba(0,0,0,0.05); +} + +.settings-panel.hidden { + transform: translateX(105%); +} + +.settings-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 40px; +} + +.setting-item { + display: flex; + flex-direction: column; + gap: 8px; + margin-bottom: 25px; +} + +.setting-item span { font-size: 0.85rem; font-weight: 600; opacity: 0.7; text-transform: uppercase; } + +select { + background: #111111; + color: #ffffff; + border: 1px solid rgba(255, 255, 255, 0.1); + padding: 12px; + border-radius: 12px; + outline: none; + cursor: pointer; + font-size: 1rem; + width: 100%; +} + +option { + background: #111111; + color: #ffffff; +} + +body.light-theme select { + background: #ffffff; + color: #1a202c; + border: 1px solid #e2e8f0; +} + +body.light-theme option { + background: #ffffff; + color: #1a202c; +} + +.settings-footer { + position: absolute; + bottom: 30px; + left: 30px; + right: 30px; + padding-top: 20px; + border-top: 1px solid rgba(128,128,128,0.1); +} + +.link-btn { + background: none; + border: none; + color: var(--accent-color); + cursor: pointer; + font-weight: 600; + padding: 0; + text-decoration: none; +} + +.method { font-weight: bold; padding: 2px 8px; border-radius: 4px; font-size: 0.8rem; margin-right: 10px; } +.get { background: #007bff; color: white; } +.post { background: #28a745; color: white; } + +/* Keyframes */ +@keyframes fadeIn { from { opacity: 0; transform: scale(0.98); } to { opacity: 1; transform: scale(1); } } +@keyframes slideDown { from { opacity: 0; transform: translateY(-30px); } to { opacity: 1; transform: translateY(0); } } + +@media (max-width: 600px) { + .dashboard { padding: 15px; } + .station-grid { grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); } + .settings-panel { width: 85%; } +} diff --git a/app/src/main/assets/web/translations.json b/app/src/main/assets/web/translations.json new file mode 100644 index 0000000..8dd3e4b --- /dev/null +++ b/app/src/main/assets/web/translations.json @@ -0,0 +1,202 @@ +{ + "en": { + "title": "Radio Remote", + "status_loading": "Loading...", + "status_playing": "Playing", + "status_paused": "Paused", + "status_error": "Error", + "status_connection_error": "Connection Error", + "controls_prev": "Previous", + "controls_next": "Next", + "controls_play_pause": "Play/Pause", + "stations_title": "Station Collection", + "stations_empty": "No stations found in collection.", + "menu_theme": "Theme", + "menu_language": "Language", + "theme_light": "Light", + "theme_dark": "Dark", + "theme_follow_browser": "Follow Browser", + "lang_auto_browser": "Auto (Browser)", + "api_docs": "API Documentation" + }, + "de": { + "title": "Radio Fernbedienung", + "status_loading": "Lädt...", + "status_playing": "Wiedergabe", + "status_paused": "Pause", + "status_error": "Fehler", + "status_connection_error": "Verbindungsfehler", + "controls_prev": "Zurück", + "controls_next": "Weiter", + "controls_play_pause": "Play/Pause", + "stations_title": "Sender-Sammlung", + "stations_empty": "Keine Sender in der Sammlung gefunden.", + "menu_theme": "Design", + "menu_language": "Sprache", + "theme_light": "Hell", + "theme_dark": "Dunkel", + "theme_follow_browser": "Browser folgen", + "lang_auto_browser": "Auto (Browser)", + "api_docs": "API Dokumentation" + }, + "fr": { + "title": "Télécommande Radio", + "status_loading": "Chargement...", + "status_playing": "Lecture", + "status_paused": "Pause", + "status_error": "Erreur", + "status_connection_error": "Erreur de connexion", + "controls_prev": "Précédent", + "controls_next": "Suivant", + "controls_play_pause": "Lecture/Pause", + "stations_title": "Collection de Stations", + "stations_empty": "Aucune station trouvée.", + "menu_theme": "Thème", + "menu_language": "Langue", + "theme_light": "Clair", + "theme_dark": "Sombre", + "theme_follow_browser": "Suivre le Navigateur", + "lang_auto_browser": "Auto (Navigateur)", + "api_docs": "Documentation API" + }, + "ru": { + "title": "Пульт Радио", + "status_loading": "Загрузка...", + "status_playing": "Воспроизведение", + "status_paused": "Пауза", + "status_error": "Ошибка", + "status_connection_error": "Ошибка соединения", + "controls_prev": "Назад", + "controls_next": "Вперед", + "controls_play_pause": "Пуск/Пауза", + "stations_title": "Коллекция станций", + "stations_empty": "Станции не найдены.", + "menu_theme": "Тема", + "menu_language": "Язык", + "theme_light": "Светлая", + "theme_dark": "Темная", + "theme_follow_browser": "Как in браузере", + "lang_auto_browser": "Авто (Браузер)", + "api_docs": "Документация API" + }, + "nl": { + "title": "Radio Afstandsbediening", + "status_loading": "Laden...", + "status_playing": "Afspelen", + "status_paused": "Gepauzeerd", + "status_error": "Fout", + "status_connection_error": "Verbindingsfout", + "controls_prev": "Vorige", + "controls_next": "Volgende", + "controls_play_pause": "Afspelen/Pauze", + "stations_title": "Zendercollectie", + "stations_empty": "Geen zenders gefunden.", + "menu_theme": "Thema", + "menu_language": "Taal", + "theme_light": "Licht", + "theme_dark": "Donker", + "theme_follow_browser": "Browser volgen", + "lang_auto_browser": "Auto (Browser)", + "api_docs": "API Documentatie" + }, + "pl": { + "title": "Pilot Radio", + "status_loading": "Ładowanie...", + "status_playing": "Odtwarzanie", + "status_paused": "Pauza", + "status_error": "Błąd", + "status_connection_error": "Błąd połączenia", + "controls_prev": "Poprzedni", + "controls_next": "Następny", + "controls_play_pause": "Odtwarzaj/Pauza", + "stations_title": "Kolekcja stacji", + "stations_empty": "Nie znaleziono stacji.", + "menu_theme": "Motyw", + "menu_language": "Język", + "theme_light": "Jasny", + "theme_dark": "Ciemny", + "theme_follow_browser": "Podążaj za przeglądarką", + "lang_auto_browser": "Auto (Przeglądarka)", + "api_docs": "Dokumentacja API" + }, + "ja": { + "title": "ラジオ リモコン", + "status_loading": "読み込み中...", + "status_playing": "再生中", + "status_paused": "一時停止", + "status_error": "エラー", + "status_connection_error": "接続エラー", + "controls_prev": "前へ", + "controls_next": "次へ", + "controls_play_pause": "再生/一時停止", + "stations_title": "ステーション一覧", + "stations_empty": "ステーションが見つかりませんでした。", + "menu_theme": "テーマ", + "menu_language": "言語", + "theme_light": "ライト", + "theme_dark": "ダーク", + "theme_follow_browser": "ブラウザに従う", + "lang_auto_browser": "自動 (ブラウザ)", + "api_docs": "API ドキュメント" + }, + "uk": { + "title": "Пульт Радіо", + "status_loading": "Завантаження...", + "status_playing": "Відтворення", + "status_paused": "Пауза", + "status_error": "Помилка", + "status_connection_error": "Помилка з'єднання", + "controls_prev": "Назад", + "controls_next": "Вперед", + "controls_play_pause": "Пуск/Пауза", + "stations_title": "Колекція станцій", + "stations_empty": "Станцій не знайдено.", + "menu_theme": "Тема", + "menu_language": "Мова", + "theme_light": "Світла", + "theme_dark": "Темная", + "theme_follow_browser": "Як у браузері", + "lang_auto_browser": "Авто (Браузер)", + "api_docs": "Документация API" + }, + "el": { + "title": "Ραδιοφωνικό Χειριστήριο", + "status_loading": "Φόρτωση...", + "status_playing": "Αναπαραγωγή", + "status_paused": "Παύση", + "status_error": "Σφάλμα", + "status_connection_error": "Σφάλμα σύνδεσης", + "controls_prev": "Προηγούμενο", + "controls_next": "Επόμενο", + "controls_play_pause": "Αναπαραγωγή/Παύση", + "stations_title": "Συλλογή Σταθμών", + "stations_empty": "Δεν βρέθηκαν σταθμοί.", + "menu_theme": "Θέμα", + "menu_language": "Γλώσσα", + "theme_light": "Φωτεινό", + "theme_dark": "Σκοτεινό", + "theme_follow_browser": "Ακολουθήστε το πρόγραμμα περιήγησης", + "lang_auto_browser": "Αυτόματο (Browser)", + "api_docs": "Τεκμηρίωση API" + }, + "da": { + "title": "Radio Fjernbetjening", + "status_loading": "Indlæser...", + "status_playing": "Afspiller", + "status_paused": "Pause", + "status_error": "Fejl", + "status_connection_error": "Forbindelsesfejl", + "controls_prev": "Forrige", + "controls_next": "Næste", + "controls_play_pause": "Afspil/Pause", + "stations_title": "Stationssamling", + "stations_empty": "Ingen stationer fundet.", + "menu_theme": "Tema", + "menu_language": "Sprog", + "theme_light": "Lyst", + "theme_dark": "Mørkt", + "theme_follow_browser": "Følg browser", + "lang_auto_browser": "Auto (Browser)", + "api_docs": "API Dokumentation" + } +} diff --git a/app/src/main/java/com/michatec/radio/Keys.kt b/app/src/main/java/com/michatec/radio/Keys.kt index 890d33a..e37736f 100644 --- a/app/src/main/java/com/michatec/radio/Keys.kt +++ b/app/src/main/java/com/michatec/radio/Keys.kt @@ -20,6 +20,7 @@ object Keys { const val ACTION_COLLECTION_CHANGED: String = "com.michatec.radio.action.COLLECTION_CHANGED" const val ACTION_THEME_CHANGED: String = "com.michatec.radio.action.THEME_CHANGED" const val ACTION_START: String = "com.michatec.radio.action.START" + const val ACTION_REMOTE_SERVER_ERROR: String = "com.michatec.radio.action.REMOTE_SERVER_ERROR" // intent extras const val EXTRA_COLLECTION_MODIFICATION_DATE: String = "COLLECTION_MODIFICATION_DATE" @@ -97,6 +98,7 @@ object Keys { const val PREF_CUSTOM_THEME_ENABLED: String = "CUSTOM_THEME_ENABLED" const val PREF_CUSTOM_THEME_INDEX: String = "CUSTOM_THEME_INDEX" const val PREF_ARGUMENTS: String = "ARGUMENTS" + const val PREF_REMOTE_CONTROL_ENABLED: String = "REMOTE_CONTROL_ENABLED" // default const values const val DEFAULT_SIZE_OF_METADATA_HISTORY: Int = 25 diff --git a/app/src/main/java/com/michatec/radio/MainActivity.kt b/app/src/main/java/com/michatec/radio/MainActivity.kt index 2acea20..d365a91 100644 --- a/app/src/main/java/com/michatec/radio/MainActivity.kt +++ b/app/src/main/java/com/michatec/radio/MainActivity.kt @@ -20,10 +20,12 @@ import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.core.app.ActivityCompat import androidx.core.view.isVisible +import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.NavigationUI import androidx.navigation.ui.navigateUp +import android.content.* import com.google.android.material.snackbar.Snackbar import com.michatec.radio.helpers.AppThemeHelper import com.michatec.radio.helpers.FileHelper @@ -132,6 +134,21 @@ class MainActivity : AppCompatActivity() { } } + override fun onStart() { + super.onStart() + // register remote server error receiver + LocalBroadcastManager.getInstance(this).registerReceiver( + remoteServerErrorReceiver, + IntentFilter(Keys.ACTION_REMOTE_SERVER_ERROR) + ) + } + + override fun onStop() { + super.onStop() + // unregister remote server error receiver + LocalBroadcastManager.getInstance(this).unregisterReceiver(remoteServerErrorReceiver) + } + /* Hides the loading/splash overlay */ private fun hideLoadingOverlay() { findViewById(R.id.loading_layout)?.let { overlay -> @@ -220,6 +237,24 @@ class MainActivity : AppCompatActivity() { } } } + + + /* + * Receiver for remote server error + */ + private val remoteServerErrorReceiver: BroadcastReceiver = object : BroadcastReceiver() { + override fun onReceive(context: Context, intent: Intent) { + if (intent.action == Keys.ACTION_REMOTE_SERVER_ERROR) { + val snackbar = Snackbar.make( + findViewById(R.id.main_root), + R.string.error_webserver, + Snackbar.LENGTH_LONG + ) + snackbar.anchorView = findViewById(R.id.bottom_sheet) + snackbar.show() + } + } + } /* * End of declaration */ diff --git a/app/src/main/java/com/michatec/radio/PlayerService.kt b/app/src/main/java/com/michatec/radio/PlayerService.kt index b4631ca..f6429b1 100644 --- a/app/src/main/java/com/michatec/radio/PlayerService.kt +++ b/app/src/main/java/com/michatec/radio/PlayerService.kt @@ -60,6 +60,33 @@ class PlayerService : MediaLibraryService(), SharedPreferences.OnSharedPreferenc private var playLastStation: Boolean = false private var manuallyCancelledSleepTimer = false + private val remoteControlServer: RemoteControlServer by lazy { + RemoteControlServer(this).apply { + onPlayStation = { uuid -> + playStation(uuid) + } + onPause = { + player.pause() + } + onResume = { + player.play() + } + onNext = { + playNextStation() + } + onPrev = { + playPreviousStation() + } + + onError = { error -> + Log.e(TAG, "RemoteControlServer error: $error") + PreferencesHelper.saveRemoteControlEnabled(false) + val intent = Intent(Keys.ACTION_REMOTE_SERVER_ERROR) + LocalBroadcastManager.getInstance(this@PlayerService).sendBroadcast(intent) + } + } + } + // Native Audio Processor instance private val nativeAudioProcessor = NativeAudioProcessor() @@ -77,6 +104,13 @@ class PlayerService : MediaLibraryService(), SharedPreferences.OnSharedPreferenc // initialize player and session initializePlayer() initializeSession() + + // start remote control server if enabled + if (PreferencesHelper.loadRemoteControlEnabled()) { + remoteControlServer.setPlayer(player) + remoteControlServer.start() + } + val notificationProvider: DefaultMediaNotificationProvider = CustomNotificationProvider() notificationProvider.setSmallIcon(R.drawable.ic_notification_app_icon_white_24dp) setMediaNotificationProvider(notificationProvider) @@ -105,6 +139,12 @@ class PlayerService : MediaLibraryService(), SharedPreferences.OnSharedPreferenc } + /* Overrides onStartCommand from Service */ + override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + super.onStartCommand(intent, flags, startId) + return START_STICKY + } + /* Overrides onTaskRemoved from Service */ override fun onTaskRemoved(rootIntent: Intent?) { if (!player.playWhenReady) { @@ -369,6 +409,14 @@ class PlayerService : MediaLibraryService(), SharedPreferences.OnSharedPreferenc castPlayer.volume = 1f } } + Keys.PREF_REMOTE_CONTROL_ENABLED -> { + if (PreferencesHelper.loadRemoteControlEnabled()) { + remoteControlServer.setPlayer(player) + remoteControlServer.start() + } else { + remoteControlServer.stop() + } + } } } @@ -394,6 +442,13 @@ class PlayerService : MediaLibraryService(), SharedPreferences.OnSharedPreferenc } } + /* Starts playback of a radio station by UUID (centralized logic) */ + fun playStation(uuid: String) { + val station = CollectionHelper.getStation(collection, uuid) + if (station.isValid()) { + playStation(station) + } + } /* Starts playback of a radio station */ private fun playStation(station: Station) { diff --git a/app/src/main/java/com/michatec/radio/SettingsFragment.kt b/app/src/main/java/com/michatec/radio/SettingsFragment.kt index 7ba40f6..dd9fc52 100644 --- a/app/src/main/java/com/michatec/radio/SettingsFragment.kt +++ b/app/src/main/java/com/michatec/radio/SettingsFragment.kt @@ -5,6 +5,7 @@ import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.Intent +import android.content.pm.PackageManager import android.net.Uri import android.os.Bundle import android.util.Log @@ -13,21 +14,31 @@ import androidx.activity.result.ActivityResult import androidx.activity.result.contract.ActivityResultContracts.StartActivityForResult import androidx.appcompat.app.AppCompatActivity import androidx.core.net.toUri +import androidx.media3.common.util.UnstableApi import androidx.navigation.fragment.findNavController -import androidx.preference.* +import androidx.preference.EditTextPreference +import androidx.preference.Preference +import androidx.preference.PreferenceCategory +import androidx.preference.PreferenceFragmentCompat import com.google.android.material.snackbar.Snackbar import com.michatec.radio.dialogs.ErrorDialog import com.michatec.radio.dialogs.LanguageSelectionDialog import com.michatec.radio.dialogs.PresetSelectionDialog import com.michatec.radio.dialogs.ThemeSelectionDialog import com.michatec.radio.dialogs.YesNoDialog -import com.michatec.radio.helpers.* -import android.content.pm.PackageManager +import com.michatec.radio.helpers.AppThemeHelper +import com.michatec.radio.helpers.BackupHelper +import com.michatec.radio.helpers.FileHelper +import com.michatec.radio.helpers.LanguageHelper +import com.michatec.radio.helpers.MarqueeSwitchPreference +import com.michatec.radio.helpers.NetworkHelper +import com.michatec.radio.helpers.PreferencesHelper import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.launch import java.text.SimpleDateFormat -import java.util.* +import java.util.Date +import java.util.Locale /* @@ -59,6 +70,7 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList } /* Overrides onCreatePreferences from PreferenceFragmentCompat */ + @UnstableApi override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { val context = preferenceManager.context @@ -182,6 +194,29 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList PreferencesHelper.loadEditStreamUrisEnabled(context) } + // set up "Remote Control" preference + val preferenceRemoteControl = MarqueeSwitchPreference(context) + preferenceRemoteControl.title = getString(R.string.pref_remote_control_title) + preferenceRemoteControl.setIcon(R.drawable.ic_network_check_24dp) + preferenceRemoteControl.key = Keys.PREF_REMOTE_CONTROL_ENABLED + val localIp = NetworkHelper.getLocalIpAddress(context) + preferenceRemoteControl.summary = if (localIp != null) { + getString(R.string.pref_remote_control_url, localIp) + } else { + getString(R.string.pref_remote_control_summary) + } + preferenceRemoteControl.setDefaultValue(PreferencesHelper.loadRemoteControlEnabled()) + preferenceRemoteControl.setOnPreferenceChangeListener { _, newValue -> + val enabled = newValue as Boolean + if (enabled) { + val intent = Intent(activity, PlayerService::class.java).apply { + action = Keys.ACTION_START + } + activity?.startService(intent) + } + return@setOnPreferenceChangeListener true + } + // set up "Arguments" preference val preferenceArguments = EditTextPreference(context) preferenceArguments.title = getString(R.string.pref_arguments_title) @@ -501,6 +536,7 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList preferenceCategoryAdvanced.addPreference(preferenceBufferSize) preferenceCategoryAdvanced.addPreference(preferenceEnableEditingGeneral) preferenceCategoryAdvanced.addPreference(preferenceEnableEditingStreamUri) + preferenceCategoryAdvanced.addPreference(preferenceRemoteControl) preferenceCategoryAdvanced.addPreference(preferenceArguments) screen.addPreference(preferenceCategoryLinks) diff --git a/app/src/main/java/com/michatec/radio/helpers/NetworkHelper.kt b/app/src/main/java/com/michatec/radio/helpers/NetworkHelper.kt index 6f89225..7e5aeac 100644 --- a/app/src/main/java/com/michatec/radio/helpers/NetworkHelper.kt +++ b/app/src/main/java/com/michatec/radio/helpers/NetworkHelper.kt @@ -34,6 +34,21 @@ object NetworkHelper { } + /* Gets the IP address of the device on the local network */ + fun getLocalIpAddress(context: Context): String? { + val connMgr = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager + val activeNetwork: Network = connMgr.activeNetwork ?: return null + val linkProperties = connMgr.getLinkProperties(activeNetwork) ?: return null + for (linkAddress in linkProperties.linkAddresses) { + val address = linkAddress.address + if (!address.isLoopbackAddress && address is InetAddress && address.hostAddress?.contains(":") == false) { + return address.hostAddress + } + } + return null + } + + /* Detects content type (mime type) from given URL string - async using coroutine - use only on separate threat */ fun detectContentType(urlString: String): ContentType { Log.v(TAG, "Determining content type - Thread: ${Thread.currentThread().name}") diff --git a/app/src/main/java/com/michatec/radio/helpers/PreferencesHelper.kt b/app/src/main/java/com/michatec/radio/helpers/PreferencesHelper.kt index b5bc60e..80053a1 100644 --- a/app/src/main/java/com/michatec/radio/helpers/PreferencesHelper.kt +++ b/app/src/main/java/com/michatec/radio/helpers/PreferencesHelper.kt @@ -406,6 +406,18 @@ object PreferencesHelper { return arguments.any { it.lowercase().sha256() == targetHash } } + /* Loads whether remote control is enabled */ + fun loadRemoteControlEnabled(): Boolean { + return sharedPreferences.getBoolean(Keys.PREF_REMOTE_CONTROL_ENABLED, false) + } + + /* Saves whether remote control is enabled */ + fun saveRemoteControlEnabled(enabled: Boolean) { + sharedPreferences.edit { + putBoolean(Keys.PREF_REMOTE_CONTROL_ENABLED, enabled) + } + } + /* SHA-256 helper */ private fun String.sha256(): String { return try { diff --git a/app/src/main/java/com/michatec/radio/helpers/RemoteControlServer.kt b/app/src/main/java/com/michatec/radio/helpers/RemoteControlServer.kt new file mode 100644 index 0000000..1274b00 --- /dev/null +++ b/app/src/main/java/com/michatec/radio/helpers/RemoteControlServer.kt @@ -0,0 +1,274 @@ +package com.michatec.radio.helpers + +import android.content.Context +import android.util.Log +import androidx.media3.common.Player +import com.michatec.radio.BuildConfig +import io.ktor.http.* +import io.ktor.serialization.gson.* +import io.ktor.server.application.* +import io.ktor.server.engine.* +import io.ktor.server.netty.* +import io.ktor.server.plugins.contentnegotiation.* +import io.ktor.server.response.* +import io.ktor.server.routing.* +import kotlinx.coroutines.* +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import java.io.File +import java.net.BindException +import kotlin.time.Duration.Companion.milliseconds + +class RemoteControlServer(private val context: Context) { + + private var server: EmbeddedServer? = null + private var player: Player? = null + private val serverScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) + private val lifecycleMutex = Mutex() + var onPlayStation: ((String) -> Unit)? = null + var onPause: (() -> Unit)? = null + var onResume: (() -> Unit)? = null + var onNext: (() -> Unit)? = null + var onPrev: (() -> Unit)? = null + var onError: ((String) -> Unit)? = null + + fun setPlayer(player: Player?) { + this.player = player + } + + private fun safeReadAsset(path: String): ByteArray? { + return try { + context.assets.open(path).use { it.readBytes() } + } catch (e: Exception) { + Log.e("RemoteControlServer", "Failed to read asset: $path", e) + null + } + } + + fun start() { + serverScope.launch { + lifecycleMutex.withLock { + if (server != null) { + Log.d("RemoteControlServer", "Server is already running.") + return@withLock + } + + var attempt = 1 + val maxAttempts = 5 + + while (attempt <= maxAttempts) { + try { + Log.i("RemoteControlServer", "Starting server (attempt $attempt)...") + val newServer = embeddedServer(Netty, port = 8080, host = "0.0.0.0") { + install(ContentNegotiation) { + gson() + } + routing { + get("/") { + val content = safeReadAsset("web/index.html") + if (content != null) { + call.response.header(HttpHeaders.CacheControl, "no-cache, no-store, must-revalidate") + call.respondBytes(content, ContentType.Text.Html) + } else { + call.respond(HttpStatusCode.NotFound) + } + } + get("/style.css") { + val content = safeReadAsset("web/style.css") + if (content != null) { + call.respondBytes(content, ContentType.Text.CSS) + } else { + call.respond(HttpStatusCode.NotFound) + } + } + get("/script.js") { + val content = safeReadAsset("web/script.js") + if (content != null) { + call.response.header(HttpHeaders.CacheControl, "no-cache, no-store, must-revalidate") + call.respondBytes(content, ContentType.Application.JavaScript) + } else { + call.respond(HttpStatusCode.NotFound) + } + } + get("/translations.json") { + val content = safeReadAsset("web/translations.json") + if (content != null) { + call.respondBytes(content, ContentType.Application.Json) + } else { + call.respond(HttpStatusCode.NotFound) + } + } + get("/favicon.png") { + val content = safeReadAsset("web/favicon.png") + if (content != null) { + call.respondBytes(content, ContentType.Image.PNG) + } else { + call.respond(HttpStatusCode.NotFound) + } + } + + get("/api/config") { + try { + call.respond(mapOf("version" to BuildConfig.VERSION_NAME)) + } catch (e: Exception) { + call.respond(HttpStatusCode.InternalServerError, mapOf("error" to e.message)) + } + } + + get("/api/status") { + val p = player + if (p == null) { + call.respond(HttpStatusCode.ServiceUnavailable, mapOf("error" to "Player not available")) + } else { + try { + val status = withContext(Dispatchers.Main) { + val metadataHistory = PreferencesHelper.loadMetadataHistory() + val currentTrack = if (metadataHistory.isNotEmpty()) metadataHistory.last() else "" + val mediaId = p.currentMediaItem?.mediaId ?: PreferencesHelper.loadLastPlayedStationUuid() + + mapOf( + "isPlaying" to p.isPlaying, + "playbackState" to p.playbackState, + "currentStationUuid" to mediaId, + "metadata" to currentTrack + ) + } + call.respond(status) + } catch (e: Exception) { + call.respond(HttpStatusCode.InternalServerError, mapOf("error" to e.message)) + } + } + } + + get("/api/stations") { + try { + val collection = withContext(Dispatchers.IO) { + FileHelper.readCollection(context) + } + val simplifiedStations = collection.stations.map { + mapOf( + "uuid" to it.uuid, + "name" to it.name, + "hasImage" to it.smallImage.isNotEmpty() + ) + } + call.respond(simplifiedStations) + } catch (e: Exception) { + call.respond(HttpStatusCode.InternalServerError, mapOf("error" to e.message)) + } + } + + get("/api/image/{uuid}") { + val uuid = call.parameters["uuid"] + if (uuid != null) { + try { + val collection = withContext(Dispatchers.IO) { + FileHelper.readCollection(context) + } + val station = CollectionHelper.getStation(collection, uuid) + if (station.smallImage.isNotEmpty()) { + val imageFile = File(context.getExternalFilesDir(""), FileHelper.determineDestinationFolderPath(com.michatec.radio.Keys.FILE_TYPE_IMAGE, uuid) + "/" + com.michatec.radio.Keys.STATION_IMAGE_FILE) + if (imageFile.exists()) { + call.respondBytes(imageFile.readBytes(), ContentType.Image.JPEG) + } else { + call.respond(HttpStatusCode.NotFound) + } + } else { + call.respond(HttpStatusCode.NotFound) + } + } catch (_: Exception) { + call.respond(HttpStatusCode.InternalServerError) + } + } else { + call.respond(HttpStatusCode.BadRequest) + } + } + + post("/api/play/{uuid}") { + val uuid = call.parameters["uuid"] + if (uuid != null) { + Log.i("RemoteControlServer", "Play request for: $uuid") + withContext(Dispatchers.Main) { + onPlayStation?.invoke(uuid) + } + call.respond(mapOf("status" to "ok")) + } + } + + post("/api/pause") { + Log.i("RemoteControlServer", "Pause request") + withContext(Dispatchers.Main) { + onPause?.invoke() + } + call.respond(mapOf("status" to "ok")) + } + + post("/api/resume") { + Log.i("RemoteControlServer", "Resume request") + withContext(Dispatchers.Main) { + onResume?.invoke() + } + call.respond(mapOf("status" to "ok")) + } + + post("/api/next") { + Log.i("RemoteControlServer", "Next request") + withContext(Dispatchers.Main) { + onNext?.invoke() + } + call.respond(mapOf("status" to "ok")) + } + + post("/api/prev") { + Log.i("RemoteControlServer", "Prev request") + withContext(Dispatchers.Main) { + onPrev?.invoke() + } + call.respond(mapOf("status" to "ok")) + } + } + } + server = newServer + newServer.start(wait = false) + Log.i("RemoteControlServer", "Server successfully started on port 8080") + return@withLock + } catch (e: Exception) { + if (e is BindException || e.cause is BindException) { + Log.w("RemoteControlServer", "Port 8080 busy, retrying in 1s...") + delay(1000.milliseconds) + attempt++ + } else { + Log.e("RemoteControlServer", "Critical server error", e) + onError?.invoke(e.localizedMessage ?: "Critical error") + break + } + } + } + Log.e("RemoteControlServer", "Failed to start after $maxAttempts attempts") + onError?.invoke("Port 8080 is blocked by another process.") + } + } + } + + fun stop() { + serverScope.launch { + lifecycleMutex.withLock { + stopInternal() + } + } + } + + private fun stopInternal() { + val s = server + server = null + if (s != null) { + try { + Log.i("RemoteControlServer", "Stopping server...") + s.stop(50, 100) + Log.i("RemoteControlServer", "Server stopped") + } catch (e: Exception) { + Log.e("RemoteControlServer", "Error stopping server", e) + } + } + } +} diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index 4c39cc2..d59605f 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -185,4 +185,10 @@ Favoritter Ingen favoritter tilføjet endnu. Viser en liste over dine yndlingsstationer for hurtig adgang. + + + Fjernbetjening + Betjen radioen fra din webbrowser + Betjen radioen fra http://%1$s:8080 + Web fjernbetjeningsserver crashet/stoppede. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 4313611..9b79a9e 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -187,4 +187,10 @@ Favoriten Noch keine Favoriten hinzugefügt. Zeigt eine Liste deiner Favoriten-Sender für den Schnellzugriff. + + + Fernbedienung + Steuere das Radio über deinen Webbrowser + Steuere das Radio über http://%1$s:8080 + Web-Fernbedienungsserver abgestürzt/gestoppt. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 99a6273..2c63348 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -187,4 +187,10 @@ Αγαπημένα Δεν έχουν προστεθεί ακόμα αγαπημένα. Εμφανίζει μια λίστα με τους αγαπημένους σας σταθμούς για γρήγορη πρόσβαση. + + + Τηλεχειριστήριο + Ελέγξτε το ραδιόφωνο από το πρόγραμμα περιήγησής σας + Ελέγξτε το ραδιόφωνο από το http://%1$s:8080 + Ο διακομιστής τηλεχειριστηρίου ιστού κατέρρευσε/σταμάτησε. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 2690963..e633859 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -185,4 +185,10 @@ Favoris Aucun favori ajouté pour le moment. Affiche une liste de vos stations préférées pour un accès rapide. + + + Télécommande + Contrôlez la radio depuis votre navigateur web + Contrôlez la radio depuis http://%1$s:8080 + Serveur de télécommande Web planté/arrêté. diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index adac38d..9781420 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -130,9 +130,9 @@ 更新 オーディオエフェクト バスブースト + 低音を増強します。 セキュリティ このアプリケーションのセキュリティについて詳しく知る - 低音を増強します。 リバーブ リバーブミスを調整します。 ダイナミックレンジ圧縮 @@ -186,4 +186,10 @@ お気に入り お気に入りはまだ追加されていません。 お気に入りのステーションを一覧表示し、素早くアクセスできます。 + + + リモコン + ウェブブラウザからラジオを操作 + http://%1$s:8080 からラジオを操作 + Webリモートサーバーがクラッシュ/停止しました。 diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 968bd05..d925932 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -187,4 +187,10 @@ Favorieten Nog geen favorieten toegevoegd. Toont een lijst met je favoriete zenders voor snelle toegang. + + + Afstandsbediening + Bedien de radio vanuit je webbrowser + Bedien de radio via http://%1$s:8080 + De webserver voor de afstandsbediening is gecrasht of gestopt. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 83dc00e..2967024 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -187,4 +187,9 @@ Ulubione Nie dodano jeszcze żadnych ulubionych. Wyświetla listę ulubionych stacji, zapewniając szybki dostęp. + + Pilot + Steruj radiem z przeglądarki internetowej + Steruj radiem przez http://%1$s:8080 + Serwer zdalnego sterowania uległ awarii/zatrzymaniu. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index c98b423..e69a691 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -187,4 +187,10 @@ Избранное Избранное пока не добавлено. Показывает список ваших любимых станций для быстрого доступа. + + + Удалённое управление + Управляйте радио из вашего веб-браузера + Управляйте радио через http://%1$s:8080 + Веб-сервер удалённого управления упал/остановлен. diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index e929ca4..4f52ee6 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -187,4 +187,10 @@ Обране Ще не додано жодної станції до обраного. Показує список ваших улюблених станцій для швидкого доступу. + + + Дистанційне керування + Керуйте радіо з вашого веб-браузера + Керуйте радіо через http://%1$s:8080 + Веб-сервер дистанційного керування аварійно зупинився/зупинено. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 6c39671..e980e5e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -222,4 +222,10 @@ Favorites No favorites added yet. Shows a list of your favorite stations for quick access. + + + Remote Control + Control radio from your web browser + Control radio from http://%1$s:8080 + Web Remote server crashed / stopped. diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 7208418..d469f48 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -6,6 +6,7 @@ freedroidwarn = "V1.13" gson = "2.14.0" kotlin = "2.4.10" leanback = "1.2.0" +ktor = "3.5.1" material = "1.14.0" material3 = "1.4.0" media = "1.8.0" @@ -39,7 +40,14 @@ volley = { group = "com.android.volley", name = "volley", version.ref = "volley" work-runtime-ktx = { group = "androidx.work", name = "work-runtime-ktx", version.ref = "workRuntimeKtx" } play-services-cast-framework = { group = "com.google.android.gms", name = "play-services-cast-framework", version.ref = "playServicesCastFramework" } +ktor-server-core = { group = "io.ktor", name = "ktor-server-core", version.ref = "ktor" } +ktor-server-netty = { group = "io.ktor", name = "ktor-server-netty", version.ref = "ktor" } +ktor-server-content-negotiation = { group = "io.ktor", name = "ktor-server-content-negotiation", version.ref = "ktor" } +ktor-serialization-kotlinx-json = { group = "io.ktor", name = "ktor-serialization-kotlinx-json", version.ref = "ktor" } +ktor-serialization-gson = { group = "io.ktor", name = "ktor-serialization-gson", version.ref = "ktor" } + [plugins] android-application = { id = "com.android.application", version.ref = "agp" } android-library = { id = "com.android.library", version.ref = "agp" } jetbrains-kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" } +kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } From 228c98c1f394b4cbdf9f7ab7073ae92cfa483050 Mon Sep 17 00:00:00 2001 From: Michatec Date: Wed, 29 Jul 2026 20:14:05 +0200 Subject: [PATCH 2/8] update: disable release minification --- app/build.gradle.kts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 79332dd..f1ebd27 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -37,7 +37,7 @@ android { } release { - isMinifyEnabled = true + isMinifyEnabled = false isShrinkResources = true isCrunchPngs = true proguardFiles.addAll(listOf(getDefaultProguardFile("proguard-android-optimize.txt"), file("proguard-rules.pro"))) From 75dafd94603ace1a3bc029443fdac716020d2edd Mon Sep 17 00:00:00 2001 From: Michatec Date: Wed, 29 Jul 2026 20:16:43 +0200 Subject: [PATCH 3/8] update: disable release shrink ressources --- app/build.gradle.kts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index f1ebd27..17193be 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -38,7 +38,7 @@ android { release { isMinifyEnabled = false - isShrinkResources = true + isShrinkResources = false isCrunchPngs = true proguardFiles.addAll(listOf(getDefaultProguardFile("proguard-android-optimize.txt"), file("proguard-rules.pro"))) buildConfigField("boolean", "IS_DEBUG_ENABLED", "false") From 1d13948370519f56fa1a6a96b6ccf128b447e095 Mon Sep 17 00:00:00 2001 From: Michatec Date: Wed, 29 Jul 2026 20:23:58 +0200 Subject: [PATCH 4/8] update: remove unused comment --- app/build.gradle.kts | 1 - 1 file changed, 1 deletion(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 17193be..f8092d7 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -28,7 +28,6 @@ android { buildTypes { debug { isMinifyEnabled = false - //noinspection NotShrinkingResources isShrinkResources = false isCrunchPngs = false proguardFiles.addAll(listOf(getDefaultProguardFile("proguard-android-optimize.txt"), file("proguard-rules.pro"))) From cb1ca8ef8066541fb12bfbfa3864a23abfa9f0e5 Mon Sep 17 00:00:00 2001 From: Michatec Date: Wed, 29 Jul 2026 20:28:51 +0200 Subject: [PATCH 5/8] update: replacing remote control in SettingsFragment.kt --- app/src/main/java/com/michatec/radio/SettingsFragment.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/src/main/java/com/michatec/radio/SettingsFragment.kt b/app/src/main/java/com/michatec/radio/SettingsFragment.kt index dd9fc52..42224a7 100644 --- a/app/src/main/java/com/michatec/radio/SettingsFragment.kt +++ b/app/src/main/java/com/michatec/radio/SettingsFragment.kt @@ -509,6 +509,7 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList preferenceCategoryGeneral.addPreference(preferenceLanguageSelection) preferenceCategoryGeneral.addPreference(preferenceCustomThemeEnabled) preferenceCategoryGeneral.addPreference(preferenceCustomTheme) + preferenceCategoryGeneral.addPreference(preferenceRemoteControl) if (!isAndroidTV && isPermissionGranted(activity as Context, android.Manifest.permission.POST_NOTIFICATIONS)) { preferenceCategoryGeneral.addPreference(preferenceTestNotification) @@ -536,7 +537,6 @@ class SettingsFragment : PreferenceFragmentCompat(), YesNoDialog.YesNoDialogList preferenceCategoryAdvanced.addPreference(preferenceBufferSize) preferenceCategoryAdvanced.addPreference(preferenceEnableEditingGeneral) preferenceCategoryAdvanced.addPreference(preferenceEnableEditingStreamUri) - preferenceCategoryAdvanced.addPreference(preferenceRemoteControl) preferenceCategoryAdvanced.addPreference(preferenceArguments) screen.addPreference(preferenceCategoryLinks) From ba404c04d359909b36e9dda5831bfe5c4e0388a2 Mon Sep 17 00:00:00 2001 From: Michatec Date: Wed, 5 Aug 2026 19:02:53 +0200 Subject: [PATCH 6/8] feat(collection): add search and favorite filtering Implemented a search bar and favorites filter for the station list. Added a search button to the station collection card, updated the adapter to handle filtered datasets, and integrated the search UI into both mobile and Android TV layouts. Includes localized strings for multiple languages. --- .../java/com/michatec/radio/PlayerFragment.kt | 47 ++++++++++- .../radio/collection/CollectionAdapter.kt | 69 ++++++++++++---- .../com/michatec/radio/ui/LayoutHolder.kt | 30 +++++++ app/src/main/res/drawable/ic_search_24dp.xml | 9 +++ .../res/layout-television/fragment_player.xml | 50 +++++++++++- .../main/res/layout/card_add_new_station.xml | 18 +++++ app/src/main/res/layout/fragment_player.xml | 80 ++++++++++++++++--- app/src/main/res/values-da/strings.xml | 4 + app/src/main/res/values-de/strings.xml | 4 + app/src/main/res/values-el/strings.xml | 5 ++ app/src/main/res/values-fr/strings.xml | 5 ++ app/src/main/res/values-ja/strings.xml | 4 + app/src/main/res/values-nl/strings.xml | 4 + app/src/main/res/values-pl/strings.xml | 4 + app/src/main/res/values-ru/strings.xml | 4 + app/src/main/res/values-uk/strings.xml | 4 + app/src/main/res/values/strings.xml | 4 + 17 files changed, 318 insertions(+), 27 deletions(-) create mode 100644 app/src/main/res/drawable/ic_search_24dp.xml diff --git a/app/src/main/java/com/michatec/radio/PlayerFragment.kt b/app/src/main/java/com/michatec/radio/PlayerFragment.kt index 12ff130..fe401a0 100644 --- a/app/src/main/java/com/michatec/radio/PlayerFragment.kt +++ b/app/src/main/java/com/michatec/radio/PlayerFragment.kt @@ -10,10 +10,13 @@ import android.content.pm.PackageManager import android.media.AudioManager import android.net.Uri import android.os.* +import android.text.Editable +import android.text.TextWatcher import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup +import android.view.inputmethod.InputMethodManager import android.widget.Toast import androidx.activity.OnBackPressedCallback import androidx.activity.result.ActivityResultLauncher @@ -97,6 +100,7 @@ class PlayerFragment : Fragment(), private var tempStationUuid: String = String() private var itemTouchHelper: ItemTouchHelper? = null private var shaderEffectView: ShaderEffectView? = null + private var isSearchActive: Boolean = false // Check if the device running the app is an Android TV instance private val isAndroidTV: Boolean by lazy { @@ -181,6 +185,7 @@ class PlayerFragment : Fragment(), // find views and set them up val rootView: View = inflater.inflate(R.layout.fragment_player, container, false) layout = LayoutHolder(rootView) + isSearchActive = false shaderEffectView = rootView.findViewById(R.id.player_shader_effect) initializeViews() @@ -381,6 +386,20 @@ class PlayerFragment : Fragment(), pickImage() } + /* Overrides onSearchButtonTapped from CollectionAdapterListener */ + override fun onSearchButtonTapped() { + isSearchActive = !isSearchActive + layout.toggleSearchLayout(isSearchActive) + if (!isSearchActive) { + collectionAdapter.filter("", false) + } else if (isAndroidTV) { + // TV: focus search field and show keyboard + layout.searchInputEditText?.requestFocus() + val imm = context?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager + imm?.showSoftInput(layout.searchInputEditText, 0) + } + } + /* Overrides onYesNoDialog from YesNoDialogListener */ override fun onYesNoDialog( @@ -518,7 +537,7 @@ class PlayerFragment : Fragment(), Snackbar.LENGTH_SHORT ) if (!isAndroidTV) { - snackbar.setAnchorView(layout.bottomSheet) + snackbar.anchorView = layout.bottomSheet } snackbar.show() } @@ -532,6 +551,20 @@ class PlayerFragment : Fragment(), togglePeriodicSleepTimerUpdateRequest() } + // set up search input + layout.searchInputEditText?.addTextChangedListener(object : TextWatcher { + override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} + override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} + override fun afterTextChanged(s: Editable?) { + performSearch() + } + }) + + // set up favorites filter + layout.searchFilterFavoritesSwitch?.setOnCheckedChangeListener { _, _ -> + performSearch() + } + // set up TV station navigation layout.playerPrevButtonView?.setOnClickListener { val currentPosition = CollectionHelper.getStationPosition(collection, playerState.stationUuid) @@ -607,6 +640,14 @@ class PlayerFragment : Fragment(), pickSingleMediaLauncher.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly)) } + /* Performs search and updates list */ + private fun performSearch() { + val query = layout.searchInputEditText?.text?.toString() ?: "" + val onlyFavorites = layout.searchFilterFavoritesSwitch?.isChecked ?: false + collectionAdapter.filter(query, onlyFavorites) + layout.toggleSearchNoResults(collectionAdapter.itemCount == 1 && (query.isNotEmpty() || onlyFavorites)) + } + /* Handles this activity's start intent */ private fun handleStartIntent() { val intent = (activity as Activity).intent @@ -724,9 +765,9 @@ class PlayerFragment : Fragment(), // handle navigation arguments handleNavigationArguments() } - collectionViewModel.collectionSizeLiveData.observe(this) { + collectionViewModel.collectionSizeLiveData.observe(this) { size -> // size of collection changed - layout.toggleOnboarding(activity as Context, collection.stations.size) + layout.toggleOnboarding(activity as Context, size) updatePlayerViews() CollectionHelper.exportCollectionM3u(activity as Context, collection) CollectionHelper.exportCollectionPls(activity as Context, collection) diff --git a/app/src/main/java/com/michatec/radio/collection/CollectionAdapter.kt b/app/src/main/java/com/michatec/radio/collection/CollectionAdapter.kt index 5d4cb49..fee7b26 100644 --- a/app/src/main/java/com/michatec/radio/collection/CollectionAdapter.kt +++ b/app/src/main/java/com/michatec/radio/collection/CollectionAdapter.kt @@ -50,12 +50,15 @@ class CollectionAdapter( /* Main class variables */ private lateinit var collectionViewModel: CollectionViewModel private var collection: Collection = Collection() + private var filteredStations: MutableList = mutableListOf() private var editStationsEnabled: Boolean = PreferencesHelper.loadEditStationsEnabled(context) private var editStationStreamsEnabled: Boolean = PreferencesHelper.loadEditStreamUrisEnabled(context) private var expandedStationUuid: String = PreferencesHelper.loadStationListStreamUuid() private var expandedStationPosition: Int = -1 var isExpandedForEdit: Boolean = false private var reorderStationUuid: String = "" + private var currentSearchQuery: String = "" + private var currentOnlyFavorites: Boolean = false /* Listener Interface */ @@ -63,6 +66,7 @@ class CollectionAdapter( fun onPlayButtonTapped(stationUuid: String) fun onAddNewButtonTapped() fun onChangeImageButtonTapped(stationUuid: String) + fun onSearchButtonTapped() } @@ -108,8 +112,7 @@ class CollectionAdapter( /* Implement the method to handle item move */ fun onItemMove(fromPosition: Int, toPosition: Int) { - // Do nothing if in "edit" mode - if (isExpandedForEdit) { + if (isExpandedForEdit || filteredStations.size != collection.stations.size) { return } @@ -141,8 +144,12 @@ class CollectionAdapter( /* Implement the method to handle item dismissal */ fun onItemDismiss(position: Int) { - // Remove the item at the given position from your data collection - collection.stations.removeAt(position) + val station = filteredStations[position] + val originalPosition = collection.stations.indexOfFirst { it.uuid == station.uuid } + if (originalPosition != -1) { + collection.stations.removeAt(originalPosition) + } + filteredStations.removeAt(position) notifyItemRemoved(position) } @@ -154,6 +161,27 @@ class CollectionAdapter( } + /* Filters the station list based on query and favorite status */ + fun filter(query: String, onlyFavorites: Boolean) { + currentSearchQuery = query + currentOnlyFavorites = onlyFavorites + applyFilter() + } + + @SuppressLint("NotifyDataSetChanged") + private fun applyFilter() { + filteredStations = if (currentSearchQuery.isEmpty() && !currentOnlyFavorites) { + collection.stations.toMutableList() + } else { + collection.stations.filter { station -> + val matchesQuery = station.name.contains(currentSearchQuery, ignoreCase = true) + val matchesFavorite = !currentOnlyFavorites || station.starred + matchesQuery && matchesFavorite + }.toMutableList() + } + notifyDataSetChanged() + } + /* Overrides onBindViewHolder */ override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { when (holder) { @@ -171,11 +199,15 @@ class CollectionAdapter( addNewViewHolder.visualizerButtonView.setOnClickListener { it.findNavController().navigate(R.id.visualizer_destination) } + addNewViewHolder.playerSearchButtonView.setOnClickListener { + collectionAdapterListener.onSearchButtonTapped() + } + addNewViewHolder.playerSearchButtonView.isVisible = collection.stations.isNotEmpty() } // CASE STATION CARD is StationViewHolder -> { // get station from position - val station: Station = collection.stations[position] + val station: Station = filteredStations[position] // get reference to StationViewHolder val stationViewHolder: StationViewHolder = holder @@ -583,7 +615,7 @@ class CollectionAdapter( } else if (holder is StationViewHolder) { // get station from position - val station: Station = collection.stations[holder.bindingAdapterPosition] + val station: Station = filteredStations[holder.bindingAdapterPosition] for (data in payloads) { when (data as Int) { @@ -621,19 +653,24 @@ class CollectionAdapter( /* Overrides getItemCount */ override fun getItemCount(): Int { // +1 ==> the add station card - return collection.stations.size + 1 + return filteredStations.size + 1 } /* Removes a station from collection */ fun removeStation(context: Context, position: Int) { + val station = filteredStations[position] + val originalPosition = collection.stations.indexOfFirst { it.uuid == station.uuid } + if (originalPosition == -1) return + val newCollection = collection.deepCopy() // delete images assets - CollectionHelper.deleteStationImages(context, newCollection.stations[position]) + CollectionHelper.deleteStationImages(context, newCollection.stations[originalPosition]) // remove station from collection - newCollection.stations.removeAt(position) + newCollection.stations.removeAt(originalPosition) collection = newCollection // update list + filteredStations.removeAt(position) notifyItemRemoved(position) // save collection and broadcast changes CollectionHelper.saveCollection(context, newCollection) @@ -642,15 +679,16 @@ class CollectionAdapter( /* Toggles starred status of a station */ fun toggleStarredStation(context: Context, position: Int) { + val station = filteredStations[position] + val originalPosition = collection.stations.indexOfFirst { it.uuid == station.uuid } + if (originalPosition == -1) return + // update view (reset "swipe" state of station card) notifyItemChanged(position) // mark starred - val stationUuid: String = collection.stations[position].uuid - collection.stations[position].apply { starred = !starred } + collection.stations[originalPosition].apply { starred = !starred } // sort collection collection = CollectionHelper.sortCollection(collection) - // update list - notifyItemMoved(position, CollectionHelper.getStationPosition(collection, stationUuid)) // save collection and broadcast changes CollectionHelper.saveCollection(context, collection) } @@ -690,7 +728,7 @@ class CollectionAdapter( /* Determines if position is last */ private fun isPositionFooter(position: Int): Boolean { - return position == collection.stations.size + return position == filteredStations.size } @@ -698,6 +736,7 @@ class CollectionAdapter( @SuppressLint("NotifyDataSetChanged") private fun updateRecyclerView(oldCollection: Collection, newCollection: Collection) { collection = newCollection + applyFilter() if (oldCollection.stations.isEmpty() && newCollection.stations.isNotEmpty()) { // data set has been initialized - redraw the whole list notifyDataSetChanged() @@ -757,6 +796,8 @@ class CollectionAdapter( listItemAddNewLayout.findViewById(R.id.card_settings) val visualizerButtonView: ExtendedFloatingActionButton = listItemAddNewLayout.findViewById(R.id.card_visualizer) + val playerSearchButtonView: ExtendedFloatingActionButton = + listItemAddNewLayout.findViewById(R.id.player_search_button) } /* * End of inner class diff --git a/app/src/main/java/com/michatec/radio/ui/LayoutHolder.kt b/app/src/main/java/com/michatec/radio/ui/LayoutHolder.kt index 89d001a..0f37cfd 100644 --- a/app/src/main/java/com/michatec/radio/ui/LayoutHolder.kt +++ b/app/src/main/java/com/michatec/radio/ui/LayoutHolder.kt @@ -6,7 +6,10 @@ import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.graphics.drawable.AnimatedVectorDrawable +import android.transition.ChangeBounds +import android.transition.TransitionManager import android.view.View +import android.view.ViewGroup import android.view.animation.Animation import android.view.animation.AnimationUtils import android.widget.ImageButton @@ -23,7 +26,9 @@ import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.gms.cast.framework.CastButtonFactory import com.google.android.material.bottomsheet.BottomSheetBehavior +import com.google.android.material.materialswitch.MaterialSwitch import com.google.android.material.snackbar.Snackbar +import com.google.android.material.textfield.TextInputEditText import com.michatec.radio.Keys import com.michatec.radio.R import com.michatec.radio.core.Station @@ -56,6 +61,10 @@ data class LayoutHolder(var rootView: View) { var playerPrevButtonView: ImageButton? = rootView.findViewById(R.id.player_prev_button) var playerNextButtonView: ImageButton? = rootView.findViewById(R.id.player_next_button) private var bufferingIndicator: ProgressBar = rootView.findViewById(R.id.player_buffering_indicator) + private var searchLayout: View? = rootView.findViewById(R.id.search_layout) + var searchInputEditText: TextInputEditText? = rootView.findViewById(R.id.search_input_edit_text) + var searchFilterFavoritesSwitch: MaterialSwitch? = rootView.findViewById(R.id.search_filter_favorites_switch) + private var searchNoResultsView: View? = rootView.findViewById(R.id.search_no_results_view) private var sheetStreamingLinkHeadline: TextView? = rootView.findViewById(R.id.sheet_streaming_link_headline) private var sheetStreamingLinkView: TextView? = rootView.findViewById(R.id.sheet_streaming_link) private var sheetMetadataHistoryHeadline: TextView? = rootView.findViewById(R.id.sheet_metadata_headline) @@ -362,6 +371,27 @@ data class LayoutHolder(var rootView: View) { } } + /* Toggles visibility of the search layout */ + fun toggleSearchLayout(visible: Boolean) { + val parent = searchLayout?.parent as? ViewGroup + if (parent != null) { + val transition = ChangeBounds() + transition.duration = 300 + TransitionManager.beginDelayedTransition(parent, transition) + } + searchLayout?.isVisible = visible + if (!visible) { + searchInputEditText?.text?.clear() + searchFilterFavoritesSwitch?.isChecked = false + searchNoResultsView?.isGone = true + } + } + + /* Shows/hides no results message */ + fun toggleSearchNoResults(show: Boolean) { + searchNoResultsView?.isVisible = show + } + /* Toggles visibility of the onboarding screen */ fun toggleOnboarding(context: Context, collectionSize: Int): Boolean { diff --git a/app/src/main/res/drawable/ic_search_24dp.xml b/app/src/main/res/drawable/ic_search_24dp.xml new file mode 100644 index 0000000..ab3ba3f --- /dev/null +++ b/app/src/main/res/drawable/ic_search_24dp.xml @@ -0,0 +1,9 @@ + + + \ No newline at end of file diff --git a/app/src/main/res/layout-television/fragment_player.xml b/app/src/main/res/layout-television/fragment_player.xml index a017772..0a2bb33 100644 --- a/app/src/main/res/layout-television/fragment_player.xml +++ b/app/src/main/res/layout-television/fragment_player.xml @@ -12,6 +12,54 @@ android:layout_height="match_parent" android:layout_weight="1"> + + + + + + + + + + + + + + + + + app:layout_constraintTop_toBottomOf="@+id/search_layout" /> + + - - + android:orientation="vertical"> - - + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/src/main/res/values-da/strings.xml b/app/src/main/res/values-da/strings.xml index d59605f..a2d3b83 100644 --- a/app/src/main/res/values-da/strings.xml +++ b/app/src/main/res/values-da/strings.xml @@ -191,4 +191,8 @@ Betjen radioen fra din webbrowser Betjen radioen fra http://%1$s:8080 Web fjernbetjeningsserver crashet/stoppede. + Søg stationer… + Kun favoritter + Ingen stationer fundet. + Søg stationer diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 9b79a9e..9022005 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -15,6 +15,7 @@ Schlaf-Timer starten Start/Pause Senderbild + Sender suchen Station hinzufügen Sendername @@ -193,4 +194,7 @@ Steuere das Radio über deinen Webbrowser Steuere das Radio über http://%1$s:8080 Web-Fernbedienungsserver abgestürzt/gestoppt. + Sender suchen… + Nur Favoriten + Keine Sender gefunden. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 2c63348..9e620b1 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -193,4 +193,9 @@ Ελέγξτε το ραδιόφωνο από το πρόγραμμα περιήγησής σας Ελέγξτε το ραδιόφωνο από το http://%1$s:8080 Ο διακομιστής τηλεχειριστηρίου ιστού κατέρρευσε/σταμάτησε. + + Αναζήτηση σταθμών + Αναζήτηση σταθμών… + Μόνο αγαπημένα + Δεν βρέθηκαν σταθμοί. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index e633859..fc44dd5 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -191,4 +191,9 @@ Contrôlez la radio depuis votre navigateur web Contrôlez la radio depuis http://%1$s:8080 Serveur de télécommande Web planté/arrêté. + + Rechercher des stations + Rechercher des stations… + Favoris uniquement + Aucune station trouvée. diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xml index 9781420..ce5a2bb 100644 --- a/app/src/main/res/values-ja/strings.xml +++ b/app/src/main/res/values-ja/strings.xml @@ -192,4 +192,8 @@ ウェブブラウザからラジオを操作 http://%1$s:8080 からラジオを操作 Webリモートサーバーがクラッシュ/停止しました。 + 局を検索… + お気に入りのみ + 局が見つかりません。 + 局を検索 diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index d925932..d454c4a 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -193,4 +193,8 @@ Bedien de radio vanuit je webbrowser Bedien de radio via http://%1$s:8080 De webserver voor de afstandsbediening is gecrasht of gestopt. + Zenders zoeken… + Alleen favorieten + Geen zenders gevonden. + Zenders zoeken diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 2967024..29f9f7a 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -192,4 +192,8 @@ Steruj radiem z przeglądarki internetowej Steruj radiem przez http://%1$s:8080 Serwer zdalnego sterowania uległ awarii/zatrzymaniu. + Szukaj stacji… + Tylko ulubione + Nie znaleziono stacji. + Szukaj stacji diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index e69a691..84971d1 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -193,4 +193,8 @@ Управляйте радио из вашего веб-браузера Управляйте радио через http://%1$s:8080 Веб-сервер удалённого управления упал/остановлен. + Поиск станций… + Только избранное + Станции не найдены. + Поиск станций diff --git a/app/src/main/res/values-uk/strings.xml b/app/src/main/res/values-uk/strings.xml index 4f52ee6..7cb400c 100644 --- a/app/src/main/res/values-uk/strings.xml +++ b/app/src/main/res/values-uk/strings.xml @@ -193,4 +193,8 @@ Керуйте радіо з вашого веб-браузера Керуйте радіо через http://%1$s:8080 Веб-сервер дистанційного керування аварійно зупинився/зупинено. + Пошук станцій… + Тільки улюблені + Станцій не знайдено. + Пошук станцій diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index e980e5e..aff2601 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -18,6 +18,7 @@ Start sleep timer Play/pause Station image + Search stations Add Station @@ -228,4 +229,7 @@ Control radio from your web browser Control radio from http://%1$s:8080 Web Remote server crashed / stopped. + Search stations… + Only favorites + No stations found. From 79e79b3811d1fdb0973f05a41398b95198db1ea4 Mon Sep 17 00:00:00 2001 From: Michatec Date: Wed, 5 Aug 2026 20:08:17 +0200 Subject: [PATCH 7/8] feat(adapter): replace notifyDataSetChanged with DiffUtil and enhance remote control Improved UI performance by implementing DiffUtil in CollectionAdapter and SearchResultAdapter. Updated the web remote control to display starred status and provide more accurate playback state reporting. - Replaced manual notify calls with DiffUtil for efficient list updates. - Added starred status to the web UI and remote control API. - Fixed station reordering and expansion logic in CollectionAdapter. - Improved playback resume logic in PlayerService to handle idle states. - Prevented potential memory leaks by properly managing TextWatchers in ViewHolders. --- README.md | 1 - app/src/main/assets/web/index.html | 13 +- app/src/main/assets/web/script.js | 24 +- app/src/main/assets/web/style.css | 31 +- .../com/michatec/radio/AddStationFragment.kt | 9 +- app/src/main/java/com/michatec/radio/Keys.kt | 1 + .../java/com/michatec/radio/PlayerService.kt | 11 +- .../radio/collection/CollectionAdapter.kt | 270 ++++++++++-------- .../radio/dialogs/FindStationDialog.kt | 10 +- .../radio/helpers/RemoteControlServer.kt | 16 +- .../radio/search/SearchResultAdapter.kt | 48 +++- 11 files changed, 271 insertions(+), 163 deletions(-) diff --git a/README.md b/README.md index c1858e1..b46474c 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,6 @@ You can help out the radio-browser.info community by [adding the missing station When **Edit Stations** is enabled: - Press **← (Left)** on the remote to open the detailed station editing area -- Press **3** or **Back** to close the editing area **General TV** Controls: - Press **0** or **DEL** to remove the selected radio station diff --git a/app/src/main/assets/web/index.html b/app/src/main/assets/web/index.html index a71c476..443b5be 100644 --- a/app/src/main/assets/web/index.html +++ b/app/src/main/assets/web/index.html @@ -19,7 +19,10 @@
-
Loading...
+
+
Loading...
+ +
Station @@ -56,8 +59,11 @@
 {
   "isPlaying": true,
+  "playWhenReady": true,
+  "playbackState": 3,
   "currentStationUuid": "fc080549-...",
-  "metadata": "Artist - Title"
+  "metadata": "Artist - Title",
+  "starred": true
 }                   
@@ -70,7 +76,8 @@ { "uuid": "fc080549-...", "name": "Station Name", - "hasImage": true + "hasImage": true, + "starred": true } ] diff --git a/app/src/main/assets/web/script.js b/app/src/main/assets/web/script.js index 3557f5a..81f2127 100644 --- a/app/src/main/assets/web/script.js +++ b/app/src/main/assets/web/script.js @@ -39,6 +39,7 @@ async function updateStatus() { const statusEl = document.getElementById('status'); const playPauseIcon = document.getElementById('playPauseIcon'); const currentNameEl = document.getElementById('currentName'); + const currentStarEl = document.getElementById('currentStar'); const currentMetadataEl = document.getElementById('currentMetadata'); const currentImageEl = document.getElementById('currentImage'); @@ -51,11 +52,14 @@ async function updateStatus() { statusEl.innerText = t('status_error') + ': ' + data.error; } else { let statusText = data.isPlaying ? t('status_playing') : t('status_paused'); + if (data.playWhenReady && !data.isPlaying) { + statusText = "Buffering..."; + } if (data.playbackState === STATE_BUFFERING) { statusText = "Buffering..."; } statusEl.innerText = statusText; - playPauseIcon.innerText = data.isPlaying ? 'pause' : 'play_arrow'; + playPauseIcon.innerText = (data.isPlaying || data.playWhenReady) ? 'pause' : 'play_arrow'; const stationUuid = data.currentStationUuid; updateActiveStation(stationUuid); @@ -63,10 +67,12 @@ async function updateStatus() { const station = allStations.find(s => s.uuid === stationUuid); if (station) { currentNameEl.innerText = station.name; + currentStarEl.classList.toggle('hidden', !data.starred); currentMetadataEl.innerText = data.metadata || ""; currentImageEl.src = station.hasImage ? '/api/image/' + station.uuid : 'favicon.png'; } else { currentNameEl.innerText = data.isPlaying ? 'Unknown Station' : 'No Station Selected'; + currentStarEl.classList.add('hidden'); currentMetadataEl.innerText = ""; currentImageEl.src = 'favicon.png'; } @@ -105,6 +111,9 @@ async function loadStations() { div.className = 'station-item'; div.id = 'station-' + station.uuid; + const content = document.createElement('div'); + content.className = 'station-item-content'; + const img = document.createElement('img'); img.className = 'station-img'; if (station.hasImage) { @@ -112,13 +121,21 @@ async function loadStations() { } else { img.src = 'favicon.png'; } - div.appendChild(img); + content.appendChild(img); const name = document.createElement('div'); name.className = 'station-name'; name.innerText = station.name || 'Unnamed Station'; - div.appendChild(name); + content.appendChild(name); + if (station.starred) { + const star = document.createElement('span'); + star.className = 'material-icons starred-icon'; + star.innerText = 'star'; + content.appendChild(star); + } + + div.appendChild(content); div.onclick = () => playStation(station.uuid); list.appendChild(div); }); @@ -143,6 +160,7 @@ async function playStation(uuid) { const station = allStations.find(s => s.uuid === uuid); if (station) { document.getElementById('currentName').innerText = station.name; + document.getElementById('currentStar').classList.toggle('hidden', !station.starred); document.getElementById('currentMetadata').innerText = ""; document.getElementById('currentImage').src = station.hasImage ? '/api/image/' + station.uuid : 'favicon.png'; } diff --git a/app/src/main/assets/web/style.css b/app/src/main/assets/web/style.css index af1a7ec..242aa52 100644 --- a/app/src/main/assets/web/style.css +++ b/app/src/main/assets/web/style.css @@ -88,6 +88,13 @@ body.light-theme .current-station-info { margin-right: 20px; } +.current-title-row { + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 4px; +} + .current-name { font-size: 1.4rem; font-weight: 800; @@ -96,7 +103,6 @@ body.light-theme .current-station-info { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; - margin-bottom: 4px; } .current-metadata { @@ -194,6 +200,29 @@ body.light-theme .station-item { border-color: var(--accent-color); } +.station-item-content { + position: relative; + width: 100%; + display: flex; + flex-direction: column; + align-items: center; + gap: 12px; +} + +.starred-icon { + color: #ffca28; + text-shadow: 0 0 10px rgba(255, 202, 40, 0.4); +} + +.station-item .starred-icon { + position: absolute; + top: -8px; + right: -8px; + font-size: 24px; + background: var(--bg-color); + border-radius: 50%; +} + .station-item.active { background: var(--accent-color); color: white; diff --git a/app/src/main/java/com/michatec/radio/AddStationFragment.kt b/app/src/main/java/com/michatec/radio/AddStationFragment.kt index 13a7ebe..e57696a 100644 --- a/app/src/main/java/com/michatec/radio/AddStationFragment.kt +++ b/app/src/main/java/com/michatec/radio/AddStationFragment.kt @@ -1,6 +1,5 @@ package com.michatec.radio -import android.annotation.SuppressLint import android.content.Context import android.os.Bundle import android.view.LayoutInflater @@ -173,22 +172,18 @@ class AddStationFragment : Fragment(), positiveButton.isEnabled = false } - @SuppressLint("NotifyDataSetChanged") override fun onRadioBrowserSearchResults(results: Array) { if (results.isNotEmpty()) { - searchResultAdapter.searchResults = results.map { it.toStation() } - searchResultAdapter.notifyDataSetChanged() + searchResultAdapter.updateSearchResults(results.map { it.toStation() }) resetLayout(false) } else { showNoResultsError() } } - @SuppressLint("NotifyDataSetChanged") override fun onDirectInputCheck(stationList: MutableList) { if (stationList.isNotEmpty()) { - searchResultAdapter.searchResults = stationList - searchResultAdapter.notifyDataSetChanged() + searchResultAdapter.updateSearchResults(stationList) resetLayout(false) } else { showNoResultsError() diff --git a/app/src/main/java/com/michatec/radio/Keys.kt b/app/src/main/java/com/michatec/radio/Keys.kt index e37736f..14bc11d 100644 --- a/app/src/main/java/com/michatec/radio/Keys.kt +++ b/app/src/main/java/com/michatec/radio/Keys.kt @@ -117,6 +117,7 @@ object Keys { const val HOLDER_UPDATE_PLAYBACK_STATE: Int = 2 const val HOLDER_UPDATE_DOWNLOAD_STATE: Int = 3 const val HOLDER_UPDATE_PLAYBACK_PROGRESS: Int = 4 + const val HOLDER_UPDATE_EXPANSION: Int = 5 // dialog types const val DIALOG_UPDATE_COLLECTION: Int = 1 diff --git a/app/src/main/java/com/michatec/radio/PlayerService.kt b/app/src/main/java/com/michatec/radio/PlayerService.kt index f6429b1..532697f 100644 --- a/app/src/main/java/com/michatec/radio/PlayerService.kt +++ b/app/src/main/java/com/michatec/radio/PlayerService.kt @@ -65,11 +65,19 @@ class PlayerService : MediaLibraryService(), SharedPreferences.OnSharedPreferenc onPlayStation = { uuid -> playStation(uuid) } + onGetCollection = { + collection + } onPause = { player.pause() } onResume = { - player.play() + if (player.playbackState == Player.STATE_IDLE) { + val mediaId = player.currentMediaItem?.mediaId ?: PreferencesHelper.loadLastPlayedStationUuid() + playStation(mediaId) + } else { + player.play() + } } onNext = { playNextStation() @@ -444,6 +452,7 @@ class PlayerService : MediaLibraryService(), SharedPreferences.OnSharedPreferenc /* Starts playback of a radio station by UUID (centralized logic) */ fun playStation(uuid: String) { + Log.i(TAG, "playStation called for UUID: $uuid") val station = CollectionHelper.getStation(collection, uuid) if (station.isValid()) { playStation(station) diff --git a/app/src/main/java/com/michatec/radio/collection/CollectionAdapter.kt b/app/src/main/java/com/michatec/radio/collection/CollectionAdapter.kt index fee7b26..eabac24 100644 --- a/app/src/main/java/com/michatec/radio/collection/CollectionAdapter.kt +++ b/app/src/main/java/com/michatec/radio/collection/CollectionAdapter.kt @@ -1,6 +1,5 @@ package com.michatec.radio.collection -import android.annotation.SuppressLint import android.content.Context import android.content.SharedPreferences import android.text.Editable @@ -116,26 +115,30 @@ class CollectionAdapter( return } - val stationList = collection.stations - val stationCount = stationList.size + val stationCount = filteredStations.size if (fromPosition !in 0 until stationCount || toPosition !in 0 until stationCount) { return } - val fromStation = stationList[fromPosition] - val toStation = stationList[toPosition] + val fromStation = filteredStations[fromPosition] + val toStation = filteredStations[toPosition] if (fromStation.starred != toStation.starred) { // Prevent moving a starred item into non-starred area or vice versa return } - // Move within the same group (either starred or non-starred) - Collections.swap(stationList, fromPosition, toPosition) + // Move within both lists to keep them in sync + Collections.swap(collection.stations, fromPosition, toPosition) + Collections.swap(filteredStations, fromPosition, toPosition) // Update the value of expandedStationPosition if necessary - expandedStationPosition = if (fromPosition == expandedStationPosition) toPosition else expandedStationPosition + if (expandedStationUuid == fromStation.uuid) { + expandedStationPosition = toPosition + } else if (expandedStationUuid == toStation.uuid) { + expandedStationPosition = fromPosition + } // Notify the adapter about the item move notifyItemMoved(fromPosition, toPosition) @@ -168,8 +171,8 @@ class CollectionAdapter( applyFilter() } - @SuppressLint("NotifyDataSetChanged") private fun applyFilter() { + val oldStations = filteredStations.toList() filteredStations = if (currentSearchQuery.isEmpty() && !currentOnlyFavorites) { collection.stations.toMutableList() } else { @@ -179,7 +182,8 @@ class CollectionAdapter( matchesQuery && matchesFavorite }.toMutableList() } - notifyDataSetChanged() + val diffResult = DiffUtil.calculateDiff(CollectionDiffCallback(oldStations, filteredStations)) + diffResult.dispatchUpdatesTo(this) } /* Overrides onBindViewHolder */ @@ -228,37 +232,7 @@ class CollectionAdapter( stationViewHolder.reorderCheckbox.isChecked = false } - // show / hide edit views - when (expandedStationPosition) { - // show edit views - position -> { - stationViewHolder.stationNameView.isVisible = false - stationViewHolder.playButtonView.isGone = true - stationViewHolder.stationStarredView.isGone = true - stationViewHolder.editViews.isVisible = true - if (editStationStreamsEnabled) { - stationViewHolder.stationUriEditView.isVisible = true - stationViewHolder.stationUriEditView.imeOptions = - EditorInfo.IME_ACTION_DONE - } else { - stationViewHolder.stationUriEditView.isGone = true - stationViewHolder.stationNameEditView.imeOptions = - EditorInfo.IME_ACTION_DONE - } - // Allow internal focus - stationViewHolder.stationCardView.descendantFocusability = ViewGroup.FOCUS_AFTER_DESCENDANTS - } - // hide edit views - else -> { - stationViewHolder.stationNameView.isVisible = true - //stationViewHolder.playButtonView.isVisible = true - stationViewHolder.stationStarredView.isVisible = station.starred - stationViewHolder.editViews.isGone = true - stationViewHolder.stationUriEditView.isGone = true - // Block internal focus - stationViewHolder.stationCardView.descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS - } - } + updateVisibility(stationViewHolder, station) } } } @@ -270,13 +244,8 @@ class CollectionAdapter( positionPriorUpdate: Int, positionAfterUpdate: Int ) { - // check if position has changed after update and move stations around if necessary - if (positionPriorUpdate != positionAfterUpdate && positionPriorUpdate != -1 && positionAfterUpdate != -1) { - notifyItemMoved(positionPriorUpdate, positionAfterUpdate) - notifyItemChanged(positionPriorUpdate) - } - // update station (e.g. name) - notifyItemChanged(positionAfterUpdate) + this.collection = collection + applyFilter() } @@ -315,14 +284,23 @@ class CollectionAdapter( station.getStreamUri(), TextView.BufferType.EDITABLE ) - stationViewHolder.stationUriEditView.addTextChangedListener(object : TextWatcher { + + // Remove existing TextWatcher to prevent leaks and redundant updates + stationViewHolder.textWatcher?.let { + stationViewHolder.stationUriEditView.removeTextChangedListener(it) + } + + val newTextWatcher = object : TextWatcher { override fun afterTextChanged(s: Editable?) { handleStationUriInput(stationViewHolder, s, station.getStreamUri()) } override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} - }) + } + stationViewHolder.textWatcher = newTextWatcher + stationViewHolder.stationUriEditView.addTextChangedListener(newTextWatcher) + stationViewHolder.cancelButton.setOnClickListener { val position: Int = stationViewHolder.bindingAdapterPosition toggleEditViews(position, station.uuid) @@ -333,7 +311,6 @@ class CollectionAdapter( toggleEditViews(position, station.uuid) saveStation( station, - position, stationViewHolder.stationNameEditView.text.toString(), stationViewHolder.stationUriEditView.text.toString() ) @@ -371,37 +348,64 @@ class CollectionAdapter( /* Shows / hides the edit view for a station */ - /* TODO: Remove @SuppressLint("NotifyDataSetChanged"), remove NotifyDataSetChanged */ - @SuppressLint("NotifyDataSetChanged") private fun toggleEditViews(position: Int, stationUuid: String) { - when (stationUuid) { - // CASE: this station's edit view is already expanded - expandedStationUuid -> { - isExpandedForEdit = false - // reset currently expanded info (both uuid and position) - saveStationListExpandedState() - // update station view - notifyItemChanged(position) + if (expandedStationUuid == stationUuid) { + // CASE: this station's edit view is already expanded -> collapse it + isExpandedForEdit = false + saveStationListExpandedState() + notifyItemChanged(position, Keys.HOLDER_UPDATE_EXPANSION) + } else { + // CASE: this station's edit view is not yet expanded -> expand it + isExpandedForEdit = true + + // Collapse previously expanded station if it exists and is visible + val previousUuid = expandedStationUuid + if (previousUuid.isNotEmpty()) { + val previousPosition = filteredStations.indexOfFirst { it.uuid == previousUuid } + if (previousPosition != -1) { + notifyItemChanged(previousPosition, Keys.HOLDER_UPDATE_EXPANSION) + } } - // CASE: this station's edit view is not yet expanded - else -> { - isExpandedForEdit = true - // remember previously expanded position - val previousExpandedStationPosition: Int = expandedStationPosition - // if station was expanded - collapse it - if (previousExpandedStationPosition > -1 && previousExpandedStationPosition < collection.stations.size) - notifyItemChanged(previousExpandedStationPosition) - // store current station as the expanded one - saveStationListExpandedState(position, stationUuid) - // update station view - notifyDataSetChanged() + + // Store current station as the expanded one + saveStationListExpandedState(position, stationUuid) + // Update the newly expanded station + notifyItemChanged(position, Keys.HOLDER_UPDATE_EXPANSION) + } + } + + + /* Updates the visibility of a station's views based on its expanded state */ + private fun updateVisibility(stationViewHolder: StationViewHolder, station: Station) { + val isExpanded = expandedStationUuid == station.uuid + if (isExpanded) { + stationViewHolder.stationNameView.isVisible = false + stationViewHolder.playButtonView.isGone = true + stationViewHolder.stationStarredView.isGone = true + stationViewHolder.editViews.isVisible = true + if (editStationStreamsEnabled) { + stationViewHolder.stationUriEditView.isVisible = true + stationViewHolder.stationUriEditView.imeOptions = EditorInfo.IME_ACTION_DONE + } else { + stationViewHolder.stationUriEditView.isGone = true + stationViewHolder.stationNameEditView.imeOptions = EditorInfo.IME_ACTION_DONE } + // Allow internal focus + stationViewHolder.stationCardView.descendantFocusability = ViewGroup.FOCUS_AFTER_DESCENDANTS + } else { + stationViewHolder.stationNameView.isVisible = true + stationViewHolder.stationStarredView.isVisible = station.starred + stationViewHolder.editViews.isGone = true + stationViewHolder.stationUriEditView.isGone = true + // Block internal focus + stationViewHolder.stationCardView.descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS } } /* Toggles the starred icon */ private fun setStarredIcon(stationViewHolder: StationViewHolder, station: Station) { + val isExpanded = expandedStationUuid == station.uuid when (station.starred) { true -> { if (station.imageColor != -1) { @@ -409,7 +413,7 @@ class CollectionAdapter( } else { stationViewHolder.stationStarredView.clearColorFilter() } - stationViewHolder.stationStarredView.isVisible = true + stationViewHolder.stationStarredView.isVisible = !isExpanded } false -> { stationViewHolder.stationStarredView.clearColorFilter() @@ -496,13 +500,6 @@ class CollectionAdapter( return@setOnKeyListener true } } - KeyEvent.KEYCODE_NUMPAD_3, KeyEvent.KEYCODE_3, KeyEvent.KEYCODE_BACK -> { - if (expandedStationPosition == stationViewHolder.bindingAdapterPosition) { - val position: Int = stationViewHolder.bindingAdapterPosition - toggleEditViews(position, station.uuid) - return@setOnKeyListener true - } - } KeyEvent.KEYCODE_NUMPAD_0, KeyEvent.KEYCODE_0, KeyEvent.KEYCODE_DEL -> { removeStation(context, stationViewHolder.bindingAdapterPosition) return@setOnKeyListener true @@ -570,13 +567,16 @@ class CollectionAdapter( if (input == streamUri) { // enable save button stationViewHolder.saveButton.isEnabled = true + stationViewHolder.validationJob?.cancel() } else { // 1. disable save button stationViewHolder.saveButton.isEnabled = false // 2. check for valid station uri - and re-enable button - if (input.startsWith("http")) { + if (input.length > 10 && input.startsWith("http")) { + // cancel previous validation job + stationViewHolder.validationJob?.cancel() // detect content type on background thread - CoroutineScope(IO).launch { + stationViewHolder.validationJob = CoroutineScope(IO).launch { val deferred: Deferred = async(Dispatchers.Default) { NetworkHelper.detectContentTypeSuspended(input) @@ -635,6 +635,10 @@ class CollectionAdapter( Keys.HOLDER_UPDATE_DOWNLOAD_STATE -> { setDownloadProgress(holder, station) } + Keys.HOLDER_UPDATE_EXPANSION -> { + setEditViews(holder, station) + updateVisibility(holder, station) + } } } } @@ -680,16 +684,24 @@ class CollectionAdapter( /* Toggles starred status of a station */ fun toggleStarredStation(context: Context, position: Int) { val station = filteredStations[position] - val originalPosition = collection.stations.indexOfFirst { it.uuid == station.uuid } - if (originalPosition == -1) return + val originalIndex = collection.stations.indexOfFirst { it.uuid == station.uuid } + if (originalIndex == -1) return - // update view (reset "swipe" state of station card) - notifyItemChanged(position) - // mark starred - collection.stations[originalPosition].apply { starred = !starred } - // sort collection + // Create a copy of the station with toggled starred status + val updatedStation = collection.stations[originalIndex].deepCopy().apply { + starred = !starred + } + + // Update master list with the new instance + collection.stations[originalIndex] = updatedStation + + // Sort collection collection = CollectionHelper.sortCollection(collection) - // save collection and broadcast changes + + // Trigger immediate UI update via DiffUtil + applyFilter() + + // Save collection and broadcast changes CollectionHelper.saveCollection(context, collection) } @@ -697,30 +709,30 @@ class CollectionAdapter( /* Saves edited station */ private fun saveStation( station: Station, - position: Int, stationName: String, streamUri: String ) { - // update station name and stream uri - collection.stations.forEach { - if (it.uuid == station.uuid) { + // update station name and stream uri in master list + val originalIndex = collection.stations.indexOfFirst { it.uuid == station.uuid } + if (originalIndex != -1) { + val updatedStation = collection.stations[originalIndex].deepCopy().apply { if (stationName.isNotEmpty()) { - it.name = stationName - it.nameManuallySet = true + name = stationName + nameManuallySet = true } if (streamUri.isNotEmpty()) { - it.streamUris[0] = streamUri + streamUris[0] = streamUri } } + collection.stations[originalIndex] = updatedStation } + // sort and save collection collection = CollectionHelper.sortCollection(collection) - // update list - val newPosition: Int = CollectionHelper.getStationPosition(collection, station.uuid) - if (position != newPosition && newPosition != -1) { - notifyItemMoved(position, newPosition) - notifyItemChanged(position) - } + + // Trigger immediate UI update + applyFilter() + // save collection and broadcast changes CollectionHelper.saveCollection(context, collection) } @@ -733,19 +745,9 @@ class CollectionAdapter( /* Updates the station list - redraws the views with changed content */ - @SuppressLint("NotifyDataSetChanged") - private fun updateRecyclerView(oldCollection: Collection, newCollection: Collection) { + private fun updateRecyclerView(newCollection: Collection) { collection = newCollection applyFilter() - if (oldCollection.stations.isEmpty() && newCollection.stations.isNotEmpty()) { - // data set has been initialized - redraw the whole list - notifyDataSetChanged() - } else { - // calculate differences between current collection and new collection - and inform this adapter about the changes - val diffResult = - DiffUtil.calculateDiff(CollectionDiffCallback(oldCollection, newCollection), true) - diffResult.dispatchUpdatesTo(this@CollectionAdapter) - } } @@ -763,7 +765,7 @@ class CollectionAdapter( /* Observe view model of station collection*/ private fun observeCollectionViewModel(owner: LifecycleOwner) { collectionViewModel.collectionLiveData.observe(owner) { newCollection -> - updateRecyclerView(collection, newCollection) + updateRecyclerView(newCollection) } } @@ -829,6 +831,9 @@ class CollectionAdapter( stationCardLayout.findViewById(R.id.place_on_home_screen_button) val cancelButton: MaterialButton = stationCardLayout.findViewById(R.id.cancel_button) val saveButton: MaterialButton = stationCardLayout.findViewById(R.id.save_button) + + var textWatcher: TextWatcher? = null + var validationJob: Job? = null } /* * End of inner class @@ -839,27 +844,44 @@ class CollectionAdapter( * Inner class: DiffUtil.Callback that determines changes in data - improves list performance */ private inner class CollectionDiffCallback( - val oldCollection: Collection, - val newCollection: Collection + private val oldStations: List, + private val newStations: List ) : DiffUtil.Callback() { override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { - val oldStation: Station = oldCollection.stations[oldItemPosition] - val newStation: Station = newCollection.stations[newItemPosition] + val isOldFooter = oldItemPosition == oldStations.size + val isNewFooter = newItemPosition == newStations.size + + if (isOldFooter && isNewFooter) return true + if (isOldFooter || isNewFooter) return false + + val oldStation: Station = oldStations[oldItemPosition] + val newStation: Station = newStations[newItemPosition] return oldStation.uuid == newStation.uuid } override fun getOldListSize(): Int { - return oldCollection.stations.size + return oldStations.size + 1 } override fun getNewListSize(): Int { - return newCollection.stations.size + return newStations.size + 1 } override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { - val oldStation: Station = oldCollection.stations[oldItemPosition] - val newStation: Station = newCollection.stations[newItemPosition] + val isOldFooter = oldItemPosition == oldStations.size + val isNewFooter = newItemPosition == newStations.size + + if (isOldFooter && isNewFooter) return true + if (isOldFooter || isNewFooter) return false + + val oldStation: Station = oldStations[oldItemPosition] + val newStation: Station = newStations[newItemPosition] + + // Compare expanded state using UUID + val wasExpanded = oldStation.uuid == expandedStationUuid + val isExpanded = newStation.uuid == expandedStationUuid + if (wasExpanded != isExpanded) return false // compare relevant contents of a station if (oldStation.isPlaying != newStation.isPlaying) return false diff --git a/app/src/main/java/com/michatec/radio/dialogs/FindStationDialog.kt b/app/src/main/java/com/michatec/radio/dialogs/FindStationDialog.kt index 271f3ee..00f7624 100644 --- a/app/src/main/java/com/michatec/radio/dialogs/FindStationDialog.kt +++ b/app/src/main/java/com/michatec/radio/dialogs/FindStationDialog.kt @@ -1,6 +1,5 @@ package com.michatec.radio.dialogs -import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.os.Handler @@ -73,13 +72,10 @@ class FindStationDialog ( /* Overrides onRadioBrowserSearchResults from RadioBrowserSearchListener */ - /* TODO: Remove @SuppressLint("NotifyDataSetChanged"), remove NotifyDataSetChanged */ - @SuppressLint("NotifyDataSetChanged") override fun onRadioBrowserSearchResults(results: Array) { if (results.isNotEmpty()) { val stationList: List = results.map {it.toStation()} - searchResultAdapter.searchResults = stationList - searchResultAdapter.notifyDataSetChanged() + searchResultAdapter.updateSearchResults(stationList) resetLayout(clearAdapter = false) } else { showNoResultsError() @@ -90,9 +86,7 @@ class FindStationDialog ( /* Overrides onDirectInputCheck from DirectInputCheck */ override fun onDirectInputCheck(stationList: MutableList) { if (stationList.isNotEmpty()) { - val startPosition = searchResultAdapter.searchResults.size - searchResultAdapter.searchResults = stationList - searchResultAdapter.notifyItemRangeInserted(startPosition, stationList.size) + searchResultAdapter.updateSearchResults(stationList) resetLayout(clearAdapter = false) } else { showNoResultsError() diff --git a/app/src/main/java/com/michatec/radio/helpers/RemoteControlServer.kt b/app/src/main/java/com/michatec/radio/helpers/RemoteControlServer.kt index 1274b00..c5dedf0 100644 --- a/app/src/main/java/com/michatec/radio/helpers/RemoteControlServer.kt +++ b/app/src/main/java/com/michatec/radio/helpers/RemoteControlServer.kt @@ -26,6 +26,7 @@ class RemoteControlServer(private val context: Context) { private val serverScope = CoroutineScope(Dispatchers.IO + SupervisorJob()) private val lifecycleMutex = Mutex() var onPlayStation: ((String) -> Unit)? = null + var onGetCollection: (() -> com.michatec.radio.core.Collection)? = null var onPause: (() -> Unit)? = null var onResume: (() -> Unit)? = null var onNext: (() -> Unit)? = null @@ -121,16 +122,24 @@ class RemoteControlServer(private val context: Context) { call.respond(HttpStatusCode.ServiceUnavailable, mapOf("error" to "Player not available")) } else { try { + val collection = onGetCollection?.invoke() ?: withContext(Dispatchers.IO) { + FileHelper.readCollection(context) + } + val status = withContext(Dispatchers.Main) { val metadataHistory = PreferencesHelper.loadMetadataHistory() val currentTrack = if (metadataHistory.isNotEmpty()) metadataHistory.last() else "" val mediaId = p.currentMediaItem?.mediaId ?: PreferencesHelper.loadLastPlayedStationUuid() + val station = CollectionHelper.getStation(collection, mediaId) + mapOf( "isPlaying" to p.isPlaying, + "playWhenReady" to p.playWhenReady, "playbackState" to p.playbackState, "currentStationUuid" to mediaId, - "metadata" to currentTrack + "metadata" to currentTrack, + "starred" to station.starred ) } call.respond(status) @@ -142,14 +151,15 @@ class RemoteControlServer(private val context: Context) { get("/api/stations") { try { - val collection = withContext(Dispatchers.IO) { + val collection = onGetCollection?.invoke() ?: withContext(Dispatchers.IO) { FileHelper.readCollection(context) } val simplifiedStations = collection.stations.map { mapOf( "uuid" to it.uuid, "name" to it.name, - "hasImage" to it.smallImage.isNotEmpty() + "hasImage" to it.smallImage.isNotEmpty(), + "starred" to it.starred ) } call.respond(simplifiedStations) diff --git a/app/src/main/java/com/michatec/radio/search/SearchResultAdapter.kt b/app/src/main/java/com/michatec/radio/search/SearchResultAdapter.kt index bfd6e69..8e05aed 100644 --- a/app/src/main/java/com/michatec/radio/search/SearchResultAdapter.kt +++ b/app/src/main/java/com/michatec/radio/search/SearchResultAdapter.kt @@ -18,6 +18,7 @@ import androidx.media3.exoplayer.DefaultRenderersFactory import androidx.media3.exoplayer.ExoPlayer import androidx.media3.exoplayer.audio.AudioSink import androidx.media3.exoplayer.audio.DefaultAudioSink +import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import com.google.android.material.textview.MaterialTextView import com.michatec.radio.R @@ -48,11 +49,6 @@ class SearchResultAdapter( } - init { - setHasStableIds(true) - } - - /* Overrides onCreateViewHolder from RecyclerView.Adapter */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val v = LayoutInflater.from(parent.context) @@ -67,10 +63,6 @@ class SearchResultAdapter( } - /* Overrides getItemCount from RecyclerView.Adapter */ - override fun getItemId(position: Int): Long = position.toLong() - - /* Overrides onBindViewHolder from RecyclerView.Adapter */ override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { // get reference to ViewHolder @@ -247,9 +239,7 @@ class SearchResultAdapter( val currentlySelected: Int = selectedPosition selectedPosition = RecyclerView.NO_POSITION if (clearAdapter) { - val previousItemCount = itemCount - searchResults = emptyList() - notifyItemRangeRemoved(0, previousItemCount) + updateSearchResults(emptyList()) } else { notifyItemChanged(currentlySelected) stopPrePlayback() @@ -257,6 +247,40 @@ class SearchResultAdapter( } + /* Updates the search results using DiffUtil */ + fun updateSearchResults(newList: List) { + val diffResult = DiffUtil.calculateDiff(SearchResultDiffCallback(searchResults, newList)) + searchResults = newList + diffResult.dispatchUpdatesTo(this) + } + + + /* + * Inner class: DiffUtil.Callback for search results + */ + private class SearchResultDiffCallback( + private val oldList: List, + private val newList: List + ) : DiffUtil.Callback() { + + override fun getOldListSize(): Int = oldList.size + override fun getNewListSize(): Int = newList.size + + override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { + return oldList[oldItemPosition].uuid == newList[newItemPosition].uuid + } + + override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { + val oldItem = oldList[oldItemPosition] + val newItem = newList[newItemPosition] + return oldItem.name == newItem.name && + oldItem.getStreamUri() == newItem.getStreamUri() && + oldItem.codec == newItem.codec && + oldItem.bitrate == newItem.bitrate + } + } + + /* * Inner class: ViewHolder for a radio station search result */ From 41d46de4b8926edae00b7dd6c7e8afe3085c679b Mon Sep 17 00:00:00 2001 From: Michatec Date: Wed, 5 Aug 2026 21:47:27 +0200 Subject: [PATCH 8/8] feat(binding): implement view binding across multiple fragments and dialogs --- app/build.gradle.kts | 1 + .../com/michatec/radio/AddStationFragment.kt | 63 ++--- .../com/michatec/radio/CustomThemeFragment.kt | 104 ++++---- .../java/com/michatec/radio/MainActivity.kt | 36 +-- .../java/com/michatec/radio/PlayerFragment.kt | 22 +- .../radio/collection/CollectionAdapter.kt | 233 +++++++++--------- .../radio/dialogs/AddStationDialog.kt | 37 ++- .../com/michatec/radio/dialogs/ErrorDialog.kt | 28 +-- .../radio/dialogs/FindStationDialog.kt | 77 +++--- .../radio/dialogs/LanguageSelectionDialog.kt | 24 +- .../radio/dialogs/PresetSelectionDialog.kt | 29 +-- .../radio/dialogs/ThemeSelectionDialog.kt | 21 +- .../radio/search/SearchResultAdapter.kt | 46 ++-- .../com/michatec/radio/ui/LayoutHolder.kt | 74 +++--- app/src/main/res/layout/fragment_player.xml | 4 +- 15 files changed, 373 insertions(+), 426 deletions(-) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index f8092d7..69a735e 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -23,6 +23,7 @@ android { buildFeatures { buildConfig = true + viewBinding = true } buildTypes { diff --git a/app/src/main/java/com/michatec/radio/AddStationFragment.kt b/app/src/main/java/com/michatec/radio/AddStationFragment.kt index e57696a..d5990e9 100644 --- a/app/src/main/java/com/michatec/radio/AddStationFragment.kt +++ b/app/src/main/java/com/michatec/radio/AddStationFragment.kt @@ -6,9 +6,7 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager -import android.widget.Button import android.widget.EditText -import android.widget.ProgressBar import androidx.appcompat.widget.SearchView import androidx.core.view.isGone import androidx.core.view.isVisible @@ -17,10 +15,9 @@ import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager -import androidx.recyclerview.widget.RecyclerView -import com.google.android.material.textview.MaterialTextView import com.michatec.radio.collection.CollectionViewModel import com.michatec.radio.core.Station +import com.michatec.radio.databinding.DialogFindStationBinding import com.michatec.radio.helpers.CollectionHelper import com.michatec.radio.helpers.NetworkHelper import com.michatec.radio.search.DirectInputCheck @@ -38,13 +35,9 @@ class AddStationFragment : Fragment(), RadioBrowserSearch.RadioBrowserSearchListener, DirectInputCheck.DirectInputCheckListener { + private var _binding: DialogFindStationBinding? = null + private val binding get() = _binding!! private lateinit var collectionViewModel: CollectionViewModel - private lateinit var stationSearchBoxView: SearchView - private lateinit var searchRequestProgressIndicator: ProgressBar - private lateinit var noSearchResultsTextView: MaterialTextView - private lateinit var stationSearchResultList: RecyclerView - private lateinit var positiveButton: Button - private lateinit var negativeButton: Button private lateinit var searchResultAdapter: SearchResultAdapter private lateinit var radioBrowserSearch: RadioBrowserSearch private lateinit var directInputCheck: DirectInputCheck @@ -56,32 +49,25 @@ class AddStationFragment : Fragment(), savedInstanceState: Bundle? ): View { // We reuse the dialog layout as it's already optimized for TV in layout-television - val view = inflater.inflate(R.layout.dialog_find_station, container, false) + _binding = DialogFindStationBinding.inflate(inflater, container, false) collectionViewModel = ViewModelProvider(requireActivity())[CollectionViewModel::class.java] radioBrowserSearch = RadioBrowserSearch(this) directInputCheck = DirectInputCheck(this) - stationSearchBoxView = view.findViewById(R.id.station_search_box_view) - searchRequestProgressIndicator = view.findViewById(R.id.search_request_progress_indicator) - stationSearchResultList = view.findViewById(R.id.station_search_result_list) - noSearchResultsTextView = view.findViewById(R.id.no_results_text_view) - positiveButton = view.findViewById(R.id.dialog_positive_button) - negativeButton = view.findViewById(R.id.dialog_negative_button) - setupRecyclerView() setupSearchView() - positiveButton.setOnClickListener { + binding.dialogPositiveButton?.setOnClickListener { addStationAndExit() } - negativeButton.setOnClickListener { + binding.dialogNegativeButton?.setOnClickListener { searchResultAdapter.stopPrePlayback() findNavController().navigateUp() } - stationSearchBoxView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { + binding.stationSearchBoxView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextChange(query: String): Boolean { handleSearch(query) return true @@ -92,7 +78,12 @@ class AddStationFragment : Fragment(), } }) - return view + return binding.root + } + + override fun onDestroyView() { + super.onDestroyView() + _binding = null } override fun onDestroy() { @@ -105,14 +96,14 @@ class AddStationFragment : Fragment(), private fun setupRecyclerView() { searchResultAdapter = SearchResultAdapter(this, listOf()) - stationSearchResultList.adapter = searchResultAdapter - stationSearchResultList.layoutManager = LinearLayoutManager(context) - stationSearchResultList.itemAnimator = DefaultItemAnimator() + binding.stationSearchResultList.adapter = searchResultAdapter + binding.stationSearchResultList.layoutManager = LinearLayoutManager(context) + binding.stationSearchResultList.itemAnimator = DefaultItemAnimator() } private fun setupSearchView() { // TV specific: ensure keyboard opens when search view gets focus - stationSearchBoxView.setOnQueryTextFocusChangeListener { v, hasFocus -> + binding.stationSearchBoxView.setOnQueryTextFocusChangeListener { v, hasFocus -> if (hasFocus) { // Find the internal EditText of the SearchView val searchEditText = v.findViewById(androidx.appcompat.R.id.search_src_text) @@ -125,7 +116,7 @@ class AddStationFragment : Fragment(), } // Make the SearchView always expanded and ready for input - stationSearchBoxView.isIconified = false + binding.stationSearchBoxView.isIconified = false } private fun handleSearch(query: String) { @@ -165,11 +156,11 @@ class AddStationFragment : Fragment(), } override fun activateAddButton() { - positiveButton.isEnabled = true + binding.dialogPositiveButton?.isEnabled = true } override fun deactivateAddButton() { - positiveButton.isEnabled = false + binding.dialogPositiveButton?.isEnabled = false } override fun onRadioBrowserSearchResults(results: Array) { @@ -191,19 +182,19 @@ class AddStationFragment : Fragment(), } private fun resetLayout(clear: Boolean) { - positiveButton.isEnabled = false - searchRequestProgressIndicator.isGone = true - noSearchResultsTextView.isGone = true + binding.dialogPositiveButton?.isEnabled = false + binding.searchRequestProgressIndicator.isGone = true + binding.noResultsTextView.isGone = true if (clear) searchResultAdapter.resetSelection(true) } private fun showProgressIndicator() { - searchRequestProgressIndicator.isVisible = true - noSearchResultsTextView.isGone = true + binding.searchRequestProgressIndicator.isVisible = true + binding.noResultsTextView.isGone = true } private fun showNoResultsError() { - searchRequestProgressIndicator.isGone = true - noSearchResultsTextView.isVisible = true + binding.searchRequestProgressIndicator.isGone = true + binding.noResultsTextView.isVisible = true } } diff --git a/app/src/main/java/com/michatec/radio/CustomThemeFragment.kt b/app/src/main/java/com/michatec/radio/CustomThemeFragment.kt index 48bc09a..c905c68 100644 --- a/app/src/main/java/com/michatec/radio/CustomThemeFragment.kt +++ b/app/src/main/java/com/michatec/radio/CustomThemeFragment.kt @@ -1,6 +1,5 @@ package com.michatec.radio -import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.content.pm.PackageManager @@ -19,18 +18,15 @@ import androidx.core.graphics.toColorInt import androidx.fragment.app.Fragment import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView -import com.google.android.material.textfield.TextInputEditText +import com.michatec.radio.databinding.ElementColorCircleBinding +import com.michatec.radio.databinding.FragmentCustomThemeBinding import com.michatec.radio.helpers.PreferencesHelper import com.michatec.radio.helpers.ThemeHelper class CustomThemeFragment : Fragment() { - private lateinit var colorPreview: View - private lateinit var hexCode: TextInputEditText - private lateinit var seekRed: SeekBar - private lateinit var seekGreen: SeekBar - private lateinit var seekBlue: SeekBar - private lateinit var recyclerView: RecyclerView + private var _binding: FragmentCustomThemeBinding? = null + private val binding get() = _binding!! private var currentColor: Int = Color.BLACK private var isUpdatingFromHex = false @@ -49,8 +45,14 @@ class CustomThemeFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? - ): View? { - return inflater.inflate(R.layout.fragment_custom_theme, container, false) + ): View { + _binding = FragmentCustomThemeBinding.inflate(inflater, container, false) + return binding.root + } + + override fun onDestroyView() { + super.onDestroyView() + _binding = null } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { @@ -58,13 +60,6 @@ class CustomThemeFragment : Fragment() { (activity as? AppCompatActivity)?.supportActionBar?.title = getString(R.string.pref_custom_theme_title) - colorPreview = view.findViewById(R.id.color_preview) - hexCode = view.findViewById(R.id.hex_code) - seekRed = view.findViewById(R.id.seek_red) - seekGreen = view.findViewById(R.id.seek_green) - seekBlue = view.findViewById(R.id.seek_blue) - recyclerView = view.findViewById(R.id.color_recycler_view) - currentColor = PreferencesHelper.loadCustomThemeColor(requireContext()) applyColor(currentColor) @@ -72,29 +67,29 @@ class CustomThemeFragment : Fragment() { val seekBarListener = object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) { if (fromUser) { - val r = seekRed.progress - val g = seekGreen.progress - val b = seekBlue.progress + val r = binding.seekRed.progress + val g = binding.seekGreen.progress + val b = binding.seekBlue.progress currentColor = Color.rgb(r, g, b) updatePreview(currentColor) PreferencesHelper.saveCustomTheme(currentColor, -1) - (recyclerView.adapter as? ColorAdapter)?.resetSelection() + (binding.colorRecyclerView.adapter as? ColorAdapter)?.resetSelection() } } override fun onStartTrackingTouch(seekBar: SeekBar?) {} override fun onStopTrackingTouch(seekBar: SeekBar?) {} } - seekRed.setOnSeekBarChangeListener(seekBarListener) - seekGreen.setOnSeekBarChangeListener(seekBarListener) - seekBlue.setOnSeekBarChangeListener(seekBarListener) + binding.seekRed.setOnSeekBarChangeListener(seekBarListener) + binding.seekGreen.setOnSeekBarChangeListener(seekBarListener) + binding.seekBlue.setOnSeekBarChangeListener(seekBarListener) // Clipboard logic (Non-TV) if (!isAndroidTV) { - hexCode.setOnClickListener { - copyToClipboard(hexCode.text.toString()) + binding.hexCode.setOnClickListener { + copyToClipboard(binding.hexCode.text.toString()) } - hexCode.addTextChangedListener(object : TextWatcher { + binding.hexCode.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {} override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { if (!isUpdatingFromHex) { @@ -104,7 +99,7 @@ class CustomThemeFragment : Fragment() { isUpdatingFromHex = true applyColor(color) PreferencesHelper.saveCustomTheme(currentColor, -1) - (recyclerView.adapter as? ColorAdapter)?.resetSelection() + (binding.colorRecyclerView.adapter as? ColorAdapter)?.resetSelection() isUpdatingFromHex = false } catch (_: Exception) {} } @@ -112,44 +107,44 @@ class CustomThemeFragment : Fragment() { override fun afterTextChanged(s: Editable?) {} }) } else { - hexCode.isFocusable = false - hexCode.isFocusableInTouchMode = false + binding.hexCode.isFocusable = false + binding.hexCode.isFocusableInTouchMode = false } setupRecyclerView() } - private fun copyToClipboard(text: String) { - val clipboard = requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager - val clip = ClipData.newPlainText(getString(R.string.hex_code), text) - clipboard.setPrimaryClip(clip) - Toast.makeText(requireContext(), R.string.toastmessage_copied_to_clipboard, Toast.LENGTH_SHORT).show() - } - private fun updateSeekBars(color: Int) { - seekRed.progress = Color.red(color) - seekGreen.progress = Color.green(color) - seekBlue.progress = Color.blue(color) + binding.seekRed.progress = Color.red(color) + binding.seekGreen.progress = Color.green(color) + binding.seekBlue.progress = Color.blue(color) } private fun updatePreview(color: Int) { - colorPreview.setBackgroundColor(color) + binding.colorPreview.setBackgroundColor(color) if (!isUpdatingFromHex) { isUpdatingFromHex = true - hexCode.setText(String.format("#%08X", 0xFFFFFF and color)) + binding.hexCode.setText(String.format("#%08X", 0xFFFFFF and color)) isUpdatingFromHex = false } } private fun setupRecyclerView() { - recyclerView.layoutManager = GridLayoutManager(requireContext(), 5) + binding.colorRecyclerView.layoutManager = GridLayoutManager(requireContext(), 5) val colors = ThemeHelper.getPredefinedColors(requireContext()) val adapter = ColorAdapter(colors) { color, index -> currentColor = color applyColor(color) PreferencesHelper.saveCustomTheme(currentColor, index) } - recyclerView.adapter = adapter + binding.colorRecyclerView.adapter = adapter + } + + private fun copyToClipboard(text: String) { + val clipboard = requireContext().getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager + val clip = android.content.ClipData.newPlainText(getString(R.string.hex_code), text) + clipboard.setPrimaryClip(clip) + Toast.makeText(requireContext(), R.string.toastmessage_copied_to_clipboard, Toast.LENGTH_SHORT).show() } private inner class ColorAdapter( @@ -169,12 +164,11 @@ class CustomThemeFragment : Fragment() { if (oldPos != -1) notifyItemChanged(oldPos) } - inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { - val circle: View = view.findViewById(R.id.color_circle) + inner class ViewHolder(val binding: ElementColorCircleBinding) : RecyclerView.ViewHolder(binding.root) { init { - view.isFocusable = true - view.isFocusableInTouchMode = isAndroidTV - view.setOnClickListener { + binding.root.isFocusable = true + binding.root.isFocusableInTouchMode = isAndroidTV + binding.root.setOnClickListener { val pos = bindingAdapterPosition if (pos != RecyclerView.NO_POSITION) { val oldPos = selectedPosition @@ -188,14 +182,18 @@ class CustomThemeFragment : Fragment() { } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { - val view = LayoutInflater.from(parent.context) - .inflate(R.layout.element_color_circle, parent, false) - return ViewHolder(view) + return ViewHolder( + ElementColorCircleBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ) + ) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val color = colors[position] - val drawable = holder.circle.background as GradientDrawable + val drawable = holder.binding.colorCircle.background as GradientDrawable drawable.setColor(color) // Set selection state diff --git a/app/src/main/java/com/michatec/radio/MainActivity.kt b/app/src/main/java/com/michatec/radio/MainActivity.kt index d365a91..3b908f9 100644 --- a/app/src/main/java/com/michatec/radio/MainActivity.kt +++ b/app/src/main/java/com/michatec/radio/MainActivity.kt @@ -17,7 +17,6 @@ import android.view.View import androidx.activity.enableEdgeToEdge import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity -import androidx.appcompat.widget.Toolbar import androidx.core.app.ActivityCompat import androidx.core.view.isVisible import androidx.localbroadcastmanager.content.LocalBroadcastManager @@ -27,6 +26,7 @@ import androidx.navigation.ui.NavigationUI import androidx.navigation.ui.navigateUp import android.content.* import com.google.android.material.snackbar.Snackbar +import com.michatec.radio.databinding.ActivityMainBinding import com.michatec.radio.helpers.AppThemeHelper import com.michatec.radio.helpers.FileHelper import com.michatec.radio.helpers.LanguageHelper @@ -41,8 +41,8 @@ import java.util.Locale class MainActivity : AppCompatActivity() { /* Main class variables */ + private lateinit var binding: ActivityMainBinding private lateinit var appBarConfiguration: AppBarConfiguration - private lateinit var mainRoot: View // Check if the device running the app is an Android TV instance private val isAndroidTV: Boolean by lazy { @@ -55,7 +55,7 @@ class MainActivity : AppCompatActivity() { ) { isGranted -> if (!isGranted) { val snackbar = Snackbar.make( - findViewById(android.R.id.content), + binding.mainRoot, R.string.snackbar_failed_permission_notification, Snackbar.LENGTH_LONG ) @@ -68,7 +68,9 @@ class MainActivity : AppCompatActivity() { startActivity(intent) } } - snackbar.anchorView = findViewById(R.id.bottom_sheet) + findViewById(R.id.bottom_sheet)?.let { + snackbar.anchorView = it + } snackbar.show() } } @@ -94,25 +96,25 @@ class MainActivity : AppCompatActivity() { setTheme(R.style.AppTheme) super.onCreate(savedInstanceState) + binding = ActivityMainBinding.inflate(layoutInflater) + setContentView(binding.root) + // Free Android FreeDroidWarn.showWarningOnUpgrade(this, BuildConfig.VERSION_CODE) // set up views - setContentView(R.layout.activity_main) - mainRoot = findViewById(R.id.main_root) applyCustomTheme() // create .nomedia file - if not yet existing FileHelper.createNomediaFile(getExternalFilesDir(null)) // set up action bar - setSupportActionBar(findViewById(R.id.main_toolbar)) - val toolbar: Toolbar = findViewById(R.id.main_toolbar) + setSupportActionBar(binding.mainToolbar) val navHostFragment = supportFragmentManager.findFragmentById(R.id.main_host_container) as NavHostFragment val navController = navHostFragment.navController appBarConfiguration = AppBarConfiguration(navController.graph) - NavigationUI.setupWithNavController(toolbar, navController, appBarConfiguration) + NavigationUI.setupWithNavController(binding.mainToolbar, navController, appBarConfiguration) supportActionBar?.hide() // TV-specific loading logic: Hide the overlay once the app is ready @@ -122,7 +124,7 @@ class MainActivity : AppCompatActivity() { hideLoadingOverlay() }, 1200) } else { - findViewById(R.id.loading_layout)?.visibility = View.GONE + binding.loadingLayout.visibility = View.GONE } // register listener for changes in shared preferences @@ -151,7 +153,7 @@ class MainActivity : AppCompatActivity() { /* Hides the loading/splash overlay */ private fun hideLoadingOverlay() { - findViewById(R.id.loading_layout)?.let { overlay -> + binding.loadingLayout.let { overlay -> if (overlay.isVisible) { overlay.animate().alpha(0f).setDuration(500) .withEndAction { overlay.visibility = View.GONE } @@ -177,12 +179,12 @@ class MainActivity : AppCompatActivity() { } } } - mainRoot.setBackgroundColor(color) + binding.mainRoot.setBackgroundColor(color) } else { // Reset to default theme background color val typedValue = TypedValue() theme.resolveAttribute(android.R.attr.colorBackground, typedValue, true) - mainRoot.setBackgroundColor(typedValue.data) + binding.mainRoot.setBackgroundColor(typedValue.data) } } @@ -206,7 +208,7 @@ class MainActivity : AppCompatActivity() { /* Overrides onSupportNavigateUp from AppCompatActivity */ override fun onSupportNavigateUp(): Boolean { val navHostFragment = - supportFragmentManager.findFragmentById(R.id.main_host_container) as NavHostFragment + supportFragmentManager.findFragmentById(binding.mainHostContainer.id) as NavHostFragment val navController = navHostFragment.navController return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } @@ -246,11 +248,13 @@ class MainActivity : AppCompatActivity() { override fun onReceive(context: Context, intent: Intent) { if (intent.action == Keys.ACTION_REMOTE_SERVER_ERROR) { val snackbar = Snackbar.make( - findViewById(R.id.main_root), + binding.mainRoot, R.string.error_webserver, Snackbar.LENGTH_LONG ) - snackbar.anchorView = findViewById(R.id.bottom_sheet) + this@MainActivity.findViewById(R.id.bottom_sheet)?.let { + snackbar.anchorView = it + } snackbar.show() } } diff --git a/app/src/main/java/com/michatec/radio/PlayerFragment.kt b/app/src/main/java/com/michatec/radio/PlayerFragment.kt index fe401a0..8cdab3e 100644 --- a/app/src/main/java/com/michatec/radio/PlayerFragment.kt +++ b/app/src/main/java/com/michatec/radio/PlayerFragment.kt @@ -61,6 +61,7 @@ import com.michatec.radio.dialogs.AddStationDialog import com.michatec.radio.dialogs.FindStationDialog import com.michatec.radio.dialogs.YesNoDialog import com.michatec.radio.extensions.* +import com.michatec.radio.databinding.FragmentPlayerBinding import com.michatec.radio.helpers.* import com.michatec.radio.ui.LayoutHolder import com.michatec.radio.ui.PlayerState @@ -85,6 +86,8 @@ class PlayerFragment : Fragment(), private val TAG: String = PlayerFragment::class.java.simpleName /* Main class variables */ + private var _binding: FragmentPlayerBinding? = null + private val binding get() = _binding!! private lateinit var collectionViewModel: CollectionViewModel private lateinit var layout: LayoutHolder private lateinit var collectionAdapter: CollectionAdapter @@ -183,26 +186,31 @@ class PlayerFragment : Fragment(), savedInstanceState: Bundle? ): View { // find views and set them up - val rootView: View = inflater.inflate(R.layout.fragment_player, container, false) - layout = LayoutHolder(rootView) + _binding = FragmentPlayerBinding.inflate(inflater, container, false) + layout = LayoutHolder(binding) isSearchActive = false - shaderEffectView = rootView.findViewById(R.id.player_shader_effect) + shaderEffectView = binding.playerSheet?.playerShaderEffect ?: binding.playerShaderEffect initializeViews() // hide action bar (activity as AppCompatActivity).supportActionBar?.hide() - ViewCompat.setOnApplyWindowInsetsListener(layout.rootView) { v, insets -> + ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) - v.updatePadding(bottom = systemBars.bottom) + v.updatePadding(top = systemBars.top, bottom = systemBars.bottom) insets } // associate the ItemTouchHelper with the RecyclerView itemTouchHelper = ItemTouchHelper(ItemTouchHelperCallback()) - itemTouchHelper?.attachToRecyclerView(layout.recyclerView) + itemTouchHelper?.attachToRecyclerView(binding.stationList) - return rootView + return binding.root + } + + override fun onDestroyView() { + super.onDestroyView() + _binding = null } diff --git a/app/src/main/java/com/michatec/radio/collection/CollectionAdapter.kt b/app/src/main/java/com/michatec/radio/collection/CollectionAdapter.kt index eabac24..c3e8380 100644 --- a/app/src/main/java/com/michatec/radio/collection/CollectionAdapter.kt +++ b/app/src/main/java/com/michatec/radio/collection/CollectionAdapter.kt @@ -9,12 +9,8 @@ import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.EditorInfo -import android.widget.CheckBox -import android.widget.ImageView -import android.widget.ProgressBar import android.widget.TextView import androidx.appcompat.app.AppCompatActivity -import androidx.constraintlayout.widget.Group import androidx.core.net.toUri import androidx.core.view.isGone import androidx.core.view.isVisible @@ -23,19 +19,31 @@ import androidx.lifecycle.ViewModelProvider import androidx.navigation.findNavController import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView -import com.google.android.material.button.MaterialButton -import com.google.android.material.card.MaterialCardView -import com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton -import com.google.android.material.textfield.TextInputEditText import com.michatec.radio.Keys import com.michatec.radio.R import com.michatec.radio.core.Collection import com.michatec.radio.core.Station -import com.michatec.radio.helpers.* -import kotlinx.coroutines.* +import com.michatec.radio.databinding.CardAddNewStationBinding +import com.michatec.radio.databinding.CardStationBinding +import com.michatec.radio.helpers.CollectionHelper +import com.michatec.radio.helpers.FileHelper +import com.michatec.radio.helpers.ImageHelper +import com.michatec.radio.helpers.NetworkHelper +import com.michatec.radio.helpers.PreferencesHelper +import com.michatec.radio.helpers.ShortcutHelper +import com.michatec.radio.helpers.UiHelper +import com.michatec.radio.helpers.UpdateHelper +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Deferred +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.Main -import java.util.* +import kotlinx.coroutines.Job +import kotlinx.coroutines.async +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.util.Collections +import java.util.Locale /* @@ -94,16 +102,22 @@ class CollectionAdapter( return when (viewType) { Keys.VIEW_TYPE_ADD_NEW -> { - // get view, put view into holder and return - val v = LayoutInflater.from(parent.context) - .inflate(R.layout.card_add_new_station, parent, false) - AddNewViewHolder(v) + AddNewViewHolder( + CardAddNewStationBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ) + ) } else -> { - // get view, put view into holder and return - val v = LayoutInflater.from(parent.context) - .inflate(R.layout.card_station, parent, false) - StationViewHolder(v) + StationViewHolder( + CardStationBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ) + ) } } } @@ -191,22 +205,21 @@ class CollectionAdapter( when (holder) { // CASE ADD NEW CARD is AddNewViewHolder -> { - // get reference to StationViewHolder - val addNewViewHolder: AddNewViewHolder = holder - addNewViewHolder.addNewStationView.setOnClickListener { + val binding = holder.binding + binding.cardAddNewStation.setOnClickListener { // show the add station dialog collectionAdapterListener.onAddNewButtonTapped() } - addNewViewHolder.settingsButtonView.setOnClickListener { + binding.cardSettings.setOnClickListener { it.findNavController().navigate(R.id.settings_destination) } - addNewViewHolder.visualizerButtonView.setOnClickListener { + binding.cardVisualizer.setOnClickListener { it.findNavController().navigate(R.id.visualizer_destination) } - addNewViewHolder.playerSearchButtonView.setOnClickListener { + binding.playerSearchButton.setOnClickListener { collectionAdapterListener.onSearchButtonTapped() } - addNewViewHolder.playerSearchButtonView.isVisible = collection.stations.isNotEmpty() + binding.playerSearchButton.isVisible = collection.stations.isNotEmpty() } // CASE STATION CARD is StationViewHolder -> { @@ -225,11 +238,11 @@ class CollectionAdapter( setDownloadProgress(stationViewHolder, station) if (reorderStationUuid == station.uuid) { - stationViewHolder.reorderCheckbox.isVisible = true - stationViewHolder.reorderCheckbox.isChecked = true + stationViewHolder.binding.reorderCheckbox.isVisible = true + stationViewHolder.binding.reorderCheckbox.isChecked = true } else { - stationViewHolder.reorderCheckbox.isGone = true - stationViewHolder.reorderCheckbox.isChecked = false + stationViewHolder.binding.reorderCheckbox.isGone = true + stationViewHolder.binding.reorderCheckbox.isChecked = false } updateVisibility(stationViewHolder, station) @@ -251,17 +264,17 @@ class CollectionAdapter( /* Sets the station name view */ private fun setStationName(stationViewHolder: StationViewHolder, station: Station) { - stationViewHolder.stationNameView.text = station.name + stationViewHolder.binding.stationName.text = station.name } /* Sets the playback progress view */ private fun setPlaybackProgress(stationViewHolder: StationViewHolder, station: Station) { if (station.bufferingProgress > 0) { - stationViewHolder.bufferingProgress.progress = station.bufferingProgress - stationViewHolder.bufferingProgress.isVisible = true + stationViewHolder.binding.bufferingProgress.progress = station.bufferingProgress + stationViewHolder.binding.bufferingProgress.isVisible = true } else { - stationViewHolder.bufferingProgress.isGone = true + stationViewHolder.binding.bufferingProgress.isGone = true } } @@ -269,25 +282,26 @@ class CollectionAdapter( /* Sets the download progress view */ private fun setDownloadProgress(stationViewHolder: StationViewHolder, station: Station) { if (station.downloadProgress > 0) { - stationViewHolder.downloadProgress.progress = station.downloadProgress - stationViewHolder.downloadProgress.isVisible = true + stationViewHolder.binding.downloadProgress.progress = station.downloadProgress + stationViewHolder.binding.downloadProgress.isVisible = true } else { - stationViewHolder.downloadProgress.isGone = true + stationViewHolder.binding.downloadProgress.isGone = true } } /* Sets the edit views */ private fun setEditViews(stationViewHolder: StationViewHolder, station: Station) { - stationViewHolder.stationNameEditView.setText(station.name, TextView.BufferType.EDITABLE) - stationViewHolder.stationUriEditView.setText( + val binding = stationViewHolder.binding + binding.editStationName.setText(station.name, TextView.BufferType.EDITABLE) + binding.editStreamUri.setText( station.getStreamUri(), TextView.BufferType.EDITABLE ) // Remove existing TextWatcher to prevent leaks and redundant updates stationViewHolder.textWatcher?.let { - stationViewHolder.stationUriEditView.removeTextChangedListener(it) + binding.editStreamUri.removeTextChangedListener(it) } val newTextWatcher = object : TextWatcher { @@ -299,35 +313,35 @@ class CollectionAdapter( override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {} } stationViewHolder.textWatcher = newTextWatcher - stationViewHolder.stationUriEditView.addTextChangedListener(newTextWatcher) + binding.editStreamUri.addTextChangedListener(newTextWatcher) - stationViewHolder.cancelButton.setOnClickListener { + binding.cancelButton.setOnClickListener { val position: Int = stationViewHolder.bindingAdapterPosition toggleEditViews(position, station.uuid) - UiHelper.hideSoftKeyboard(context, stationViewHolder.stationNameEditView) + UiHelper.hideSoftKeyboard(context, binding.editStationName) } - stationViewHolder.saveButton.setOnClickListener { + binding.saveButton.setOnClickListener { val position: Int = stationViewHolder.bindingAdapterPosition toggleEditViews(position, station.uuid) saveStation( station, - stationViewHolder.stationNameEditView.text.toString(), - stationViewHolder.stationUriEditView.text.toString() + binding.editStationName.text.toString(), + binding.editStreamUri.text.toString() ) - UiHelper.hideSoftKeyboard(context, stationViewHolder.stationNameEditView) + UiHelper.hideSoftKeyboard(context, binding.editStationName) } - stationViewHolder.placeOnHomeScreenButton.setOnClickListener { + binding.placeOnHomeScreenButton.setOnClickListener { val position: Int = stationViewHolder.bindingAdapterPosition ShortcutHelper.placeShortcut(context, station) toggleEditViews(position, station.uuid) - UiHelper.hideSoftKeyboard(context, stationViewHolder.stationNameEditView) + UiHelper.hideSoftKeyboard(context, binding.editStationName) } - stationViewHolder.stationImageChangeView.setOnClickListener { + binding.changeImageView.setOnClickListener { val position: Int = stationViewHolder.bindingAdapterPosition collectionAdapterListener.onChangeImageButtonTapped(station.uuid) stationViewHolder.bindingAdapterPosition toggleEditViews(position, station.uuid) - UiHelper.hideSoftKeyboard(context, stationViewHolder.stationNameEditView) + UiHelper.hideSoftKeyboard(context, binding.editStationName) } } @@ -377,47 +391,49 @@ class CollectionAdapter( /* Updates the visibility of a station's views based on its expanded state */ private fun updateVisibility(stationViewHolder: StationViewHolder, station: Station) { + val binding = stationViewHolder.binding val isExpanded = expandedStationUuid == station.uuid if (isExpanded) { - stationViewHolder.stationNameView.isVisible = false - stationViewHolder.playButtonView.isGone = true - stationViewHolder.stationStarredView.isGone = true - stationViewHolder.editViews.isVisible = true + binding.stationName.isVisible = false + binding.playbackButton.isGone = true + binding.starredIcon.isGone = true + binding.defaultEditViews.isVisible = true if (editStationStreamsEnabled) { - stationViewHolder.stationUriEditView.isVisible = true - stationViewHolder.stationUriEditView.imeOptions = EditorInfo.IME_ACTION_DONE + binding.editStreamUri.isVisible = true + binding.editStreamUri.imeOptions = EditorInfo.IME_ACTION_DONE } else { - stationViewHolder.stationUriEditView.isGone = true - stationViewHolder.stationNameEditView.imeOptions = EditorInfo.IME_ACTION_DONE + binding.editStreamUri.isGone = true + binding.editStationName.imeOptions = EditorInfo.IME_ACTION_DONE } // Allow internal focus - stationViewHolder.stationCardView.descendantFocusability = ViewGroup.FOCUS_AFTER_DESCENDANTS + binding.stationCard.descendantFocusability = ViewGroup.FOCUS_AFTER_DESCENDANTS } else { - stationViewHolder.stationNameView.isVisible = true - stationViewHolder.stationStarredView.isVisible = station.starred - stationViewHolder.editViews.isGone = true - stationViewHolder.stationUriEditView.isGone = true + binding.stationName.isVisible = true + binding.starredIcon.isVisible = station.starred + binding.defaultEditViews.isGone = true + binding.editStreamUri.isGone = true // Block internal focus - stationViewHolder.stationCardView.descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS + binding.stationCard.descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS } } /* Toggles the starred icon */ private fun setStarredIcon(stationViewHolder: StationViewHolder, station: Station) { + val binding = stationViewHolder.binding val isExpanded = expandedStationUuid == station.uuid when (station.starred) { true -> { if (station.imageColor != -1) { - stationViewHolder.stationStarredView.setColorFilter(station.imageColor) + binding.starredIcon.setColorFilter(station.imageColor) } else { - stationViewHolder.stationStarredView.clearColorFilter() + binding.starredIcon.clearColorFilter() } - stationViewHolder.stationStarredView.isVisible = !isExpanded + binding.starredIcon.isVisible = !isExpanded } false -> { - stationViewHolder.stationStarredView.clearColorFilter() - stationViewHolder.stationStarredView.isGone = true + binding.starredIcon.clearColorFilter() + binding.starredIcon.isGone = true } } } @@ -425,46 +441,48 @@ class CollectionAdapter( /* Sets the station image view */ private fun setStationImage(stationViewHolder: StationViewHolder, station: Station) { + val binding = stationViewHolder.binding if (station.imageColor != -1) { - stationViewHolder.stationImageView.setBackgroundColor(station.imageColor) + binding.stationIcon.setBackgroundColor(station.imageColor) } - stationViewHolder.stationImageView.setImageBitmap( + binding.stationIcon.setImageBitmap( ImageHelper.getStationImage( context, station.smallImage ) ) - stationViewHolder.stationImageView.contentDescription = + binding.stationIcon.contentDescription = "${context.getString(R.string.descr_player_station_image)}: ${station.name}" } /* Sets up a station's play and edit buttons */ private fun setStationButtons(stationViewHolder: StationViewHolder, station: Station) { + val binding = stationViewHolder.binding when (station.isPlaying) { - true -> stationViewHolder.playButtonView.visibility = View.VISIBLE - false -> stationViewHolder.playButtonView.visibility = View.INVISIBLE + true -> binding.playbackButton.visibility = View.VISIBLE + false -> binding.playbackButton.visibility = View.INVISIBLE } - stationViewHolder.stationCardView.setOnClickListener { + binding.stationCard.setOnClickListener { if (reorderStationUuid.isNotEmpty()) return@setOnClickListener if (expandedStationPosition == stationViewHolder.bindingAdapterPosition) return@setOnClickListener collectionAdapterListener.onPlayButtonTapped(station.uuid) } - stationViewHolder.playButtonView.setOnClickListener { + binding.playbackButton.setOnClickListener { collectionAdapterListener.onPlayButtonTapped(station.uuid) } - stationViewHolder.stationNameView.setOnClickListener { + binding.stationName.setOnClickListener { collectionAdapterListener.onPlayButtonTapped(station.uuid) } - stationViewHolder.stationStarredView.setOnClickListener { + binding.starredIcon.setOnClickListener { collectionAdapterListener.onPlayButtonTapped(station.uuid) } - stationViewHolder.stationImageView.setOnClickListener { + binding.stationIcon.setOnClickListener { collectionAdapterListener.onPlayButtonTapped(station.uuid) } // TV improvement: Allow reordering with DPAD - stationViewHolder.stationCardView.setOnKeyListener { _, keyCode, event -> + binding.stationCard.setOnKeyListener { _, keyCode, event -> if (event.action == KeyEvent.ACTION_DOWN) { // Reorder mode handling if (reorderStationUuid == station.uuid) { @@ -517,7 +535,7 @@ class CollectionAdapter( false } - stationViewHolder.playButtonView.setOnLongClickListener { + binding.playbackButton.setOnLongClickListener { if (editStationsEnabled) { val position: Int = stationViewHolder.bindingAdapterPosition toggleEditViews(position, station.uuid) @@ -526,7 +544,7 @@ class CollectionAdapter( return@setOnLongClickListener false } } - stationViewHolder.stationNameView.setOnLongClickListener { + binding.stationName.setOnLongClickListener { if (editStationsEnabled) { val position: Int = stationViewHolder.bindingAdapterPosition toggleEditViews(position, station.uuid) @@ -535,7 +553,7 @@ class CollectionAdapter( return@setOnLongClickListener false } } - stationViewHolder.stationStarredView.setOnLongClickListener { + binding.starredIcon.setOnLongClickListener { if (editStationsEnabled) { val position: Int = stationViewHolder.bindingAdapterPosition toggleEditViews(position, station.uuid) @@ -544,7 +562,7 @@ class CollectionAdapter( return@setOnLongClickListener false } } - stationViewHolder.stationImageView.setOnLongClickListener { + binding.stationIcon.setOnLongClickListener { if (editStationsEnabled) { val position: Int = stationViewHolder.bindingAdapterPosition toggleEditViews(position, station.uuid) @@ -562,15 +580,16 @@ class CollectionAdapter( s: Editable?, streamUri: String ) { + val binding = stationViewHolder.binding if (editStationStreamsEnabled) { val input: String = s.toString() if (input == streamUri) { // enable save button - stationViewHolder.saveButton.isEnabled = true + binding.saveButton.isEnabled = true stationViewHolder.validationJob?.cancel() } else { // 1. disable save button - stationViewHolder.saveButton.isEnabled = false + binding.saveButton.isEnabled = false // 2. check for valid station uri - and re-enable button if (input.length > 10 && input.startsWith("http")) { // cancel previous validation job @@ -592,7 +611,7 @@ class CollectionAdapter( ) { // re-enable save button withContext(Main) { - stationViewHolder.saveButton.isEnabled = true + binding.saveButton.isEnabled = true } } } @@ -790,17 +809,8 @@ class CollectionAdapter( /* * Inner class: ViewHolder for the Add New Station action */ - private class AddNewViewHolder(listItemAddNewLayout: View) : - RecyclerView.ViewHolder(listItemAddNewLayout) { - val addNewStationView: ExtendedFloatingActionButton = - listItemAddNewLayout.findViewById(R.id.card_add_new_station) - val settingsButtonView: ExtendedFloatingActionButton = - listItemAddNewLayout.findViewById(R.id.card_settings) - val visualizerButtonView: ExtendedFloatingActionButton = - listItemAddNewLayout.findViewById(R.id.card_visualizer) - val playerSearchButtonView: ExtendedFloatingActionButton = - listItemAddNewLayout.findViewById(R.id.player_search_button) - } + private class AddNewViewHolder(val binding: CardAddNewStationBinding) : + RecyclerView.ViewHolder(binding.root) /* * End of inner class */ @@ -809,29 +819,8 @@ class CollectionAdapter( /* * Inner class: ViewHolder for a station */ - private class StationViewHolder(stationCardLayout: View) : - RecyclerView.ViewHolder(stationCardLayout) { - val stationCardView: MaterialCardView = stationCardLayout.findViewById(R.id.station_card) - val stationImageView: ImageView = stationCardLayout.findViewById(R.id.station_icon) - val stationNameView: TextView = stationCardLayout.findViewById(R.id.station_name) - val stationStarredView: ImageView = stationCardLayout.findViewById(R.id.starred_icon) - val reorderCheckbox: CheckBox = stationCardLayout.findViewById(R.id.reorder_checkbox) - val bufferingProgress: ProgressBar = stationCardLayout.findViewById(R.id.buffering_progress) - val downloadProgress: ProgressBar = stationCardLayout.findViewById(R.id.download_progress) - - val playButtonView: ImageView = stationCardLayout.findViewById(R.id.playback_button) - val editViews: Group = stationCardLayout.findViewById(R.id.default_edit_views) - val stationImageChangeView: ImageView = - stationCardLayout.findViewById(R.id.change_image_view) - val stationNameEditView: TextInputEditText = - stationCardLayout.findViewById(R.id.edit_station_name) - val stationUriEditView: TextInputEditText = - stationCardLayout.findViewById(R.id.edit_stream_uri) - val placeOnHomeScreenButton: MaterialButton = - stationCardLayout.findViewById(R.id.place_on_home_screen_button) - val cancelButton: MaterialButton = stationCardLayout.findViewById(R.id.cancel_button) - val saveButton: MaterialButton = stationCardLayout.findViewById(R.id.save_button) - + private class StationViewHolder(val binding: CardStationBinding) : + RecyclerView.ViewHolder(binding.root) { var textWatcher: TextWatcher? = null var validationJob: Job? = null } diff --git a/app/src/main/java/com/michatec/radio/dialogs/AddStationDialog.kt b/app/src/main/java/com/michatec/radio/dialogs/AddStationDialog.kt index 062a79e..0bded43 100644 --- a/app/src/main/java/com/michatec/radio/dialogs/AddStationDialog.kt +++ b/app/src/main/java/com/michatec/radio/dialogs/AddStationDialog.kt @@ -2,15 +2,14 @@ package com.michatec.radio.dialogs import android.content.Context import android.view.LayoutInflater -import android.widget.Button import androidx.appcompat.app.AlertDialog import androidx.core.view.isGone import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager -import androidx.recyclerview.widget.RecyclerView import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.michatec.radio.R import com.michatec.radio.core.Station +import com.michatec.radio.databinding.DialogAddStationBinding import com.michatec.radio.search.SearchResultAdapter @@ -31,10 +30,8 @@ class AddStationDialog ( /* Main class variables */ + private lateinit var binding: DialogAddStationBinding private lateinit var dialog: AlertDialog - private lateinit var stationSearchResultList: RecyclerView - private var customPositiveButton: Button? = null - private var customNegativeButton: Button? = null private lateinit var searchResultAdapter: SearchResultAdapter private var station: Station = Station() @@ -55,18 +52,12 @@ class AddStationDialog ( // set title builder.setTitle(R.string.dialog_add_station_title) - // get views - val inflater = LayoutInflater.from(context) - val view = inflater.inflate(R.layout.dialog_add_station, null) - stationSearchResultList = view.findViewById(R.id.station_list) + // get binding + binding = DialogAddStationBinding.inflate(LayoutInflater.from(context)) // set up list of search results setupRecyclerView(context) - // find custom buttons (for TV layout) - customPositiveButton = view.findViewById(R.id.dialog_positive_button) - customNegativeButton = view.findViewById(R.id.dialog_negative_button) - // add okay ("Add") button builder.setPositiveButton(R.string.dialog_find_station_button_add) { _, _ -> // listen for click on add button @@ -83,29 +74,29 @@ class AddStationDialog ( } // set up custom buttons if they exist (TV layout) - customPositiveButton?.setOnClickListener { + binding.dialogPositiveButton?.setOnClickListener { listener.onAddStationDialog(station) searchResultAdapter.stopPrePlayback() dialog.dismiss() } - customNegativeButton?.setOnClickListener { + binding.dialogNegativeButton?.setOnClickListener { searchResultAdapter.stopPrePlayback() dialog.dismiss() } // set dialog view - builder.setView(view) + builder.setView(binding.root) // create and display dialog dialog = builder.create() dialog.show() // handle button visibility and state - if (customPositiveButton != null) { + if (binding.dialogPositiveButton != null) { // hide default buttons if custom ones are used dialog.getButton(AlertDialog.BUTTON_POSITIVE).isGone = true dialog.getButton(AlertDialog.BUTTON_NEGATIVE).isGone = true - customPositiveButton?.isEnabled = false + binding.dialogPositiveButton?.isEnabled = false } else { // initially disable default "Add" button dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false @@ -116,28 +107,28 @@ class AddStationDialog ( /* Sets up list of results (RecyclerView) */ private fun setupRecyclerView(context: Context) { searchResultAdapter = SearchResultAdapter(this, stationList) - stationSearchResultList.adapter = searchResultAdapter + binding.stationList.adapter = searchResultAdapter val layoutManager: LinearLayoutManager = object: LinearLayoutManager(context) { override fun supportsPredictiveItemAnimations(): Boolean { return true } } - stationSearchResultList.layoutManager = layoutManager - stationSearchResultList.itemAnimator = DefaultItemAnimator() + binding.stationList.layoutManager = layoutManager + binding.stationList.itemAnimator = DefaultItemAnimator() } /* Implement activateAddButton to enable the "Add" button */ override fun activateAddButton() { dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = true - customPositiveButton?.isEnabled = true + binding.dialogPositiveButton?.isEnabled = true } /* Implement deactivateAddButton to disable the "Add" button */ override fun deactivateAddButton() { dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false - customPositiveButton?.isEnabled = false + binding.dialogPositiveButton?.isEnabled = false } diff --git a/app/src/main/java/com/michatec/radio/dialogs/ErrorDialog.kt b/app/src/main/java/com/michatec/radio/dialogs/ErrorDialog.kt index 2c488ef..3e1d131 100644 --- a/app/src/main/java/com/michatec/radio/dialogs/ErrorDialog.kt +++ b/app/src/main/java/com/michatec/radio/dialogs/ErrorDialog.kt @@ -4,12 +4,12 @@ import android.content.Context import android.text.method.ScrollingMovementMethod import android.view.LayoutInflater import android.view.View -import android.widget.TextView import android.widget.Toast import androidx.core.view.isGone import androidx.core.view.isVisible import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.michatec.radio.R +import com.michatec.radio.databinding.DialogGenericWithDetailsBinding /* @@ -30,41 +30,37 @@ class ErrorDialog { // set title builder.setTitle(context.getString(errorTitle)) - // get views - val inflater: LayoutInflater = LayoutInflater.from(context) - val view: View = inflater.inflate(R.layout.dialog_generic_with_details, null) - val errorMessageView: TextView = view.findViewById(R.id.dialog_message) - val errorDetailsLinkView: TextView = view.findViewById(R.id.dialog_details_link) - val errorDetailsView: TextView = view.findViewById(R.id.dialog_details) + // get binding + val binding = DialogGenericWithDetailsBinding.inflate(LayoutInflater.from(context)) // set dialog view - builder.setView(view) + builder.setView(binding.root) // set detail view val detailsNotEmpty = errorDetails.isNotEmpty() // show/hide details link depending on whether details are empty or not - errorDetailsLinkView.isVisible = detailsNotEmpty + binding.dialogDetailsLink.isVisible = detailsNotEmpty if (detailsNotEmpty) { // allow scrolling on details view - errorDetailsView.movementMethod = ScrollingMovementMethod() + binding.dialogDetails.movementMethod = ScrollingMovementMethod() // show and hide details on click - errorDetailsLinkView.setOnClickListener { - when (errorDetailsView.visibility) { - View.GONE -> errorDetailsView.isVisible = true - View.VISIBLE -> errorDetailsView.isGone = true + binding.dialogDetailsLink.setOnClickListener { + when (binding.dialogDetails.visibility) { + View.GONE -> binding.dialogDetails.isVisible = true + View.VISIBLE -> binding.dialogDetails.isGone = true View.INVISIBLE -> { return@setOnClickListener } } } // set details text view - errorDetailsView.text = errorDetails + binding.dialogDetails.text = errorDetails } // set text views - errorMessageView.text = context.getString(errorMessage) + binding.dialogMessage.text = context.getString(errorMessage) // add okay button builder.setPositiveButton(R.string.dialog_generic_button_okay) { _, _ -> diff --git a/app/src/main/java/com/michatec/radio/dialogs/FindStationDialog.kt b/app/src/main/java/com/michatec/radio/dialogs/FindStationDialog.kt index 00f7624..924b79e 100644 --- a/app/src/main/java/com/michatec/radio/dialogs/FindStationDialog.kt +++ b/app/src/main/java/com/michatec/radio/dialogs/FindStationDialog.kt @@ -6,20 +6,17 @@ import android.os.Handler import android.os.Looper import android.view.LayoutInflater import android.view.inputmethod.InputMethodManager -import android.widget.Button -import android.widget.ProgressBar import androidx.appcompat.app.AlertDialog import androidx.appcompat.widget.SearchView import androidx.core.view.isGone import androidx.core.view.isVisible import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager -import androidx.recyclerview.widget.RecyclerView import com.google.android.material.dialog.MaterialAlertDialogBuilder -import com.google.android.material.textview.MaterialTextView import com.michatec.radio.Keys import com.michatec.radio.R import com.michatec.radio.core.Station +import com.michatec.radio.databinding.DialogFindStationBinding import com.michatec.radio.search.DirectInputCheck import com.michatec.radio.search.RadioBrowserResult import com.michatec.radio.search.RadioBrowserSearch @@ -44,13 +41,8 @@ class FindStationDialog ( /* Main class variables */ + private lateinit var binding: DialogFindStationBinding private lateinit var dialog: AlertDialog - private lateinit var stationSearchBoxView: SearchView - private lateinit var searchRequestProgressIndicator: ProgressBar - private lateinit var noSearchResultsTextView: MaterialTextView - private lateinit var stationSearchResultList: RecyclerView - private var customPositiveButton: Button? = null - private var customNegativeButton: Button? = null private lateinit var searchResultAdapter: SearchResultAdapter private lateinit var radioBrowserSearch: RadioBrowserSearch private lateinit var directInputCheck: DirectInputCheck @@ -65,7 +57,7 @@ class FindStationDialog ( // hide keyboard val imm: InputMethodManager = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager - imm.hideSoftInputFromWindow(stationSearchBoxView.windowToken, 0) + imm.hideSoftInputFromWindow(binding.stationSearchBoxView.windowToken, 0) // make add button clickable activateAddButton() } @@ -106,22 +98,13 @@ class FindStationDialog ( // set title builder.setTitle(R.string.dialog_find_station_title) - // get views - val inflater = LayoutInflater.from(context) - val view = inflater.inflate(R.layout.dialog_find_station, null) - stationSearchBoxView = view.findViewById(R.id.station_search_box_view) - searchRequestProgressIndicator = view.findViewById(R.id.search_request_progress_indicator) - stationSearchResultList = view.findViewById(R.id.station_search_result_list) - noSearchResultsTextView = view.findViewById(R.id.no_results_text_view) - noSearchResultsTextView.isGone = true + // get binding + binding = DialogFindStationBinding.inflate(LayoutInflater.from(context)) + binding.noResultsTextView.isGone = true // set up list of search results setupRecyclerView(context) - // find custom buttons (for TV layout) - customPositiveButton = view.findViewById(R.id.dialog_positive_button) - customNegativeButton = view.findViewById(R.id.dialog_negative_button) - // add okay ("Add") button builder.setPositiveButton(R.string.dialog_find_station_button_add) { _, _ -> // listen for click on add button @@ -141,19 +124,19 @@ class FindStationDialog ( } // set up custom buttons if they exist (TV layout) - customPositiveButton?.setOnClickListener { + binding.dialogPositiveButton?.setOnClickListener { listener.onFindStationDialog(station) searchResultAdapter.stopPrePlayback() dialog.dismiss() } - customNegativeButton?.setOnClickListener { + binding.dialogNegativeButton?.setOnClickListener { radioBrowserSearch.stopSearchRequest() searchResultAdapter.stopPrePlayback() dialog.dismiss() } // listen for input - stationSearchBoxView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { + binding.stationSearchBoxView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextChange(query: String): Boolean { handleSearchBoxLiveInput(context, query) searchResultAdapter.stopPrePlayback() @@ -168,18 +151,18 @@ class FindStationDialog ( }) // set dialog view - builder.setView(view) + builder.setView(binding.root) // create and display dialog dialog = builder.create() dialog.show() // handle button visibility and state - if (customPositiveButton != null) { + if (binding.dialogPositiveButton != null) { // hide default buttons if custom ones are used dialog.getButton(AlertDialog.BUTTON_POSITIVE).isGone = true dialog.getButton(AlertDialog.BUTTON_NEGATIVE).isGone = true - customPositiveButton?.isEnabled = false + binding.dialogPositiveButton?.isEnabled = false } else { // initially disable default "Add" button dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false @@ -192,14 +175,14 @@ class FindStationDialog ( /* Sets up list of results (RecyclerView) */ private fun setupRecyclerView(context: Context) { searchResultAdapter = SearchResultAdapter(this, listOf()) - stationSearchResultList.adapter = searchResultAdapter + binding.stationSearchResultList.adapter = searchResultAdapter val layoutManager: LinearLayoutManager = object : LinearLayoutManager(context) { override fun supportsPredictiveItemAnimations(): Boolean { return true } } - stationSearchResultList.layoutManager = layoutManager - stationSearchResultList.itemAnimator = DefaultItemAnimator() + binding.stationSearchResultList.layoutManager = layoutManager + binding.stationSearchResultList.itemAnimator = DefaultItemAnimator() } @@ -250,25 +233,25 @@ class FindStationDialog ( /* Makes the "Add" button clickable */ override fun activateAddButton() { dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = true - customPositiveButton?.isEnabled = true - searchRequestProgressIndicator.isGone = true - noSearchResultsTextView.isGone = true + binding.dialogPositiveButton?.isEnabled = true + binding.searchRequestProgressIndicator.isGone = true + binding.noResultsTextView.isGone = true } override fun deactivateAddButton() { dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false - customPositiveButton?.isEnabled = false - searchRequestProgressIndicator.isGone = true - noSearchResultsTextView.isGone = true + binding.dialogPositiveButton?.isEnabled = false + binding.searchRequestProgressIndicator.isGone = true + binding.noResultsTextView.isGone = true } /* Resets the dialog layout to default state */ private fun resetLayout(clearAdapter: Boolean = false) { dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false - customPositiveButton?.isEnabled = false - searchRequestProgressIndicator.isGone = true - noSearchResultsTextView.isGone = true + binding.dialogPositiveButton?.isEnabled = false + binding.searchRequestProgressIndicator.isGone = true + binding.noResultsTextView.isGone = true searchResultAdapter.resetSelection(clearAdapter) } @@ -276,18 +259,18 @@ class FindStationDialog ( /* Display the "No Results" error - hide other unneeded views */ private fun showNoResultsError() { dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false - customPositiveButton?.isEnabled = false - searchRequestProgressIndicator.isGone = true - noSearchResultsTextView.isVisible = true + binding.dialogPositiveButton?.isEnabled = false + binding.searchRequestProgressIndicator.isGone = true + binding.noResultsTextView.isVisible = true } /* Display the "No Results" error - hide other unneeded views */ private fun showProgressIndicator() { dialog.getButton(AlertDialog.BUTTON_POSITIVE).isEnabled = false - customPositiveButton?.isEnabled = false - searchRequestProgressIndicator.isVisible = true - noSearchResultsTextView.isGone = true + binding.dialogPositiveButton?.isEnabled = false + binding.searchRequestProgressIndicator.isVisible = true + binding.noResultsTextView.isGone = true } } diff --git a/app/src/main/java/com/michatec/radio/dialogs/LanguageSelectionDialog.kt b/app/src/main/java/com/michatec/radio/dialogs/LanguageSelectionDialog.kt index e52cb10..68232f0 100644 --- a/app/src/main/java/com/michatec/radio/dialogs/LanguageSelectionDialog.kt +++ b/app/src/main/java/com/michatec/radio/dialogs/LanguageSelectionDialog.kt @@ -3,10 +3,10 @@ package com.michatec.radio.dialogs import android.content.Context import android.view.LayoutInflater import android.widget.RadioButton -import android.widget.RadioGroup import androidx.appcompat.app.AlertDialog import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.michatec.radio.R +import com.michatec.radio.databinding.DialogLanguageSelectionBinding import com.michatec.radio.helpers.PreferencesHelper @@ -58,11 +58,7 @@ class LanguageSelectionDialog(private var languageSelectionDialogListener: Langu val builder = MaterialAlertDialogBuilder(context) // inflate custom layout - val inflater = LayoutInflater.from(context) - val view = inflater.inflate(R.layout.dialog_language_selection, null) - - // find radio group - val radioGroup = view.findViewById(R.id.language_radio_group) + val binding = DialogLanguageSelectionBinding.inflate(LayoutInflater.from(context)) val currentLanguage = PreferencesHelper.loadSelectedLanguage() // add radio buttons for each supported language @@ -74,12 +70,12 @@ class LanguageSelectionDialog(private var languageSelectionDialogListener: Langu textSize = if (isTelevision(context)) 20f else 16f setPadding(dpToPx(context, 8), dpToPx(context, 16), dpToPx(context, 16), dpToPx(context, 16)) } - radioGroup.addView(radioButton) + binding.languageRadioGroup.addView(radioButton) } // set current selection - for (i in 0 until radioGroup.childCount) { - val radioButton = radioGroup.getChildAt(i) as RadioButton + for (i in 0 until binding.languageRadioGroup.childCount) { + val radioButton = binding.languageRadioGroup.getChildAt(i) as RadioButton if (radioButton.tag == currentLanguage) { radioButton.isChecked = true break @@ -87,14 +83,14 @@ class LanguageSelectionDialog(private var languageSelectionDialogListener: Langu } // if no language is selected, check the first one (system) - if (radioGroup.checkedRadioButtonId == -1) { - val firstButton = radioGroup.getChildAt(0) as RadioButton + if (binding.languageRadioGroup.checkedRadioButtonId == -1) { + val firstButton = binding.languageRadioGroup.getChildAt(0) as RadioButton firstButton.isChecked = true } // set up radio group listener - radioGroup.setOnCheckedChangeListener { _, checkedId -> - val selectedButton = radioGroup.findViewById(checkedId) + binding.languageRadioGroup.setOnCheckedChangeListener { _, checkedId -> + val selectedButton = binding.languageRadioGroup.findViewById(checkedId) val selectedLanguageCode = selectedButton?.tag as? String ?: "system" // save language selection to preferences @@ -108,7 +104,7 @@ class LanguageSelectionDialog(private var languageSelectionDialogListener: Langu } // set custom view - builder.setView(view) + builder.setView(binding.root) // handle outside-click as cancel builder.setOnCancelListener { diff --git a/app/src/main/java/com/michatec/radio/dialogs/PresetSelectionDialog.kt b/app/src/main/java/com/michatec/radio/dialogs/PresetSelectionDialog.kt index b9265c5..e5cb53a 100644 --- a/app/src/main/java/com/michatec/radio/dialogs/PresetSelectionDialog.kt +++ b/app/src/main/java/com/michatec/radio/dialogs/PresetSelectionDialog.kt @@ -2,11 +2,11 @@ package com.michatec.radio.dialogs import android.content.Context import android.view.LayoutInflater -import android.widget.RadioButton import androidx.appcompat.app.AlertDialog import androidx.core.content.ContextCompat.getString import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.michatec.radio.R +import com.michatec.radio.databinding.DialogPresetSelectionBinding import com.michatec.radio.helpers.PreferencesHelper @@ -31,30 +31,21 @@ class PresetSelectionDialog(private var presetSelectionDialogListener: PresetSel val builder = MaterialAlertDialogBuilder(context) // inflate custom layout - val inflater = LayoutInflater.from(context) - val view = inflater.inflate(R.layout.dialog_preset_selection, null) - - // find radio buttons - val radioGroup = view.findViewById(R.id.preset_radio_group) - val radioNone = view.findViewById(R.id.radio_preset_none) - val radioRock = view.findViewById(R.id.radio_preset_rock) - val radioPop = view.findViewById(R.id.radio_preset_pop) - val radioJazz = view.findViewById(R.id.radio_preset_jazz) - val radioFlat = view.findViewById(R.id.radio_preset_flat) + val binding = DialogPresetSelectionBinding.inflate(LayoutInflater.from(context)) // set current selection val currentPreset = PreferencesHelper.loadSelectedPreset() when (currentPreset) { - "" -> radioNone.isChecked = true - getString(context, R.string.pref_preset_rock) -> radioRock.isChecked = true - getString(context, R.string.pref_preset_pop) -> radioPop.isChecked = true - getString(context, R.string.pref_preset_jazz) -> radioJazz.isChecked = true - getString(context, R.string.pref_preset_flat) -> radioFlat.isChecked = true - else -> radioNone.isChecked = true + "" -> binding.radioPresetNone.isChecked = true + getString(context, R.string.pref_preset_rock) -> binding.radioPresetRock.isChecked = true + getString(context, R.string.pref_preset_pop) -> binding.radioPresetPop.isChecked = true + getString(context, R.string.pref_preset_jazz) -> binding.radioPresetJazz.isChecked = true + getString(context, R.string.pref_preset_flat) -> binding.radioPresetFlat.isChecked = true + else -> binding.radioPresetNone.isChecked = true } // set up radio group listener - radioGroup.setOnCheckedChangeListener { _, checkedId -> + binding.presetRadioGroup.setOnCheckedChangeListener { _, checkedId -> val selectedPreset = when (checkedId) { R.id.radio_preset_none -> "" R.id.radio_preset_rock -> getString(context, R.string.pref_preset_rock) @@ -72,7 +63,7 @@ class PresetSelectionDialog(private var presetSelectionDialogListener: PresetSel } // set custom view - builder.setView(view) + builder.setView(binding.root) // handle outside-click as cancel builder.setOnCancelListener { diff --git a/app/src/main/java/com/michatec/radio/dialogs/ThemeSelectionDialog.kt b/app/src/main/java/com/michatec/radio/dialogs/ThemeSelectionDialog.kt index 4013019..82059a5 100644 --- a/app/src/main/java/com/michatec/radio/dialogs/ThemeSelectionDialog.kt +++ b/app/src/main/java/com/michatec/radio/dialogs/ThemeSelectionDialog.kt @@ -2,11 +2,11 @@ package com.michatec.radio.dialogs import android.content.Context import android.view.LayoutInflater -import android.widget.RadioButton import androidx.appcompat.app.AlertDialog import com.google.android.material.dialog.MaterialAlertDialogBuilder import com.michatec.radio.Keys import com.michatec.radio.R +import com.michatec.radio.databinding.DialogThemeSelectionBinding import com.michatec.radio.helpers.AppThemeHelper import com.michatec.radio.helpers.PreferencesHelper @@ -33,31 +33,24 @@ class ThemeSelectionDialog(private var themeSelectionDialogListener: ThemeSelect val builder = MaterialAlertDialogBuilder(context) // inflate custom layout - val inflater = LayoutInflater.from(context) - val view = inflater.inflate(R.layout.dialog_theme_selection, null) - - // find radio buttons - val radioGroup = view.findViewById(R.id.theme_radio_group) - val radioFollowSystem = view.findViewById(R.id.radio_theme_follow_system) - val radioLight = view.findViewById(R.id.radio_theme_light) - val radioDark = view.findViewById(R.id.radio_theme_dark) + val binding = DialogThemeSelectionBinding.inflate(LayoutInflater.from(context)) // set current selection val currentTheme = AppThemeHelper.getCurrentTheme(context) when (currentTheme) { context.getString(R.string.pref_theme_selection_mode_device_default) -> { - radioFollowSystem.isChecked = true + binding.radioThemeFollowSystem.isChecked = true } context.getString(R.string.pref_theme_selection_mode_light) -> { - radioLight.isChecked = true + binding.radioThemeLight.isChecked = true } context.getString(R.string.pref_theme_selection_mode_dark) -> { - radioDark.isChecked = true + binding.radioThemeDark.isChecked = true } } // set up radio group listener - radioGroup.setOnCheckedChangeListener { _, checkedId -> + binding.themeRadioGroup.setOnCheckedChangeListener { _, checkedId -> val selectedTheme = when (checkedId) { R.id.radio_theme_follow_system -> Keys.STATE_THEME_FOLLOW_SYSTEM R.id.radio_theme_light -> Keys.STATE_THEME_LIGHT_MODE @@ -75,7 +68,7 @@ class ThemeSelectionDialog(private var themeSelectionDialogListener: ThemeSelect } // set custom view - builder.setView(view) + builder.setView(binding.root) // handle outside-click as cancel builder.setOnCancelListener { diff --git a/app/src/main/java/com/michatec/radio/search/SearchResultAdapter.kt b/app/src/main/java/com/michatec/radio/search/SearchResultAdapter.kt index 8e05aed..3faa0a3 100644 --- a/app/src/main/java/com/michatec/radio/search/SearchResultAdapter.kt +++ b/app/src/main/java/com/michatec/radio/search/SearchResultAdapter.kt @@ -20,9 +20,9 @@ import androidx.media3.exoplayer.audio.AudioSink import androidx.media3.exoplayer.audio.DefaultAudioSink import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView -import com.google.android.material.textview.MaterialTextView import com.michatec.radio.R import com.michatec.radio.core.Station +import com.michatec.radio.databinding.ElementSearchResultBinding import com.michatec.radio.helpers.NativeAudioProcessor import com.michatec.radio.helpers.PreferencesHelper @@ -51,9 +51,13 @@ class SearchResultAdapter( /* Overrides onCreateViewHolder from RecyclerView.Adapter */ override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { - val v = LayoutInflater.from(parent.context) - .inflate(R.layout.element_search_result, parent, false) - return SearchResultViewHolder(v) + return SearchResultViewHolder( + ElementSearchResultBinding.inflate( + LayoutInflater.from(parent.context), + parent, + false + ) + ) } @@ -67,43 +71,45 @@ class SearchResultAdapter( override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { // get reference to ViewHolder val searchResultViewHolder: SearchResultViewHolder = holder as SearchResultViewHolder + val binding = searchResultViewHolder.binding val searchResult: Station = searchResults[position] // update text - searchResultViewHolder.nameView.text = searchResult.name - searchResultViewHolder.streamView.text = searchResult.getStreamUri() + binding.stationName.text = searchResult.name + binding.stationUrl.text = searchResult.getStreamUri() if (searchResult.codec.isNotEmpty()) { if (searchResult.bitrate == 0) { // show only the codec when the bitrate is at "0" from radio-browser.info API - searchResultViewHolder.bitrateView.text = searchResult.codec + binding.stationBitrate.text = searchResult.codec } else { // show the bitrate and codec if the result is available in the radio-browser.info API - searchResultViewHolder.bitrateView.text = buildString { + binding.stationBitrate.text = buildString { append(searchResult.codec) append(" | ") append(searchResult.bitrate) append("kbps")} } + binding.stationBitrate.visibility = View.VISIBLE } else { // do not show for M3U and PLS playlists as they do not include codec or bitrate - searchResultViewHolder.bitrateView.visibility = View.GONE + binding.stationBitrate.visibility = View.GONE } // mark selected if necessary val isSelected = selectedPosition == holder.bindingAdapterPosition - searchResultViewHolder.searchResultLayout.isSelected = isSelected + binding.root.isSelected = isSelected // toggle text scrolling (marquee) if necessary - searchResultViewHolder.nameView.isSelected = isSelected - searchResultViewHolder.streamView.isSelected = isSelected + binding.stationName.isSelected = isSelected + binding.stationUrl.isSelected = isSelected // reduce the shadow left and right because of scrolling (Marquee) - searchResultViewHolder.nameView.setFadingEdgeLength(10) - searchResultViewHolder.streamView.setFadingEdgeLength(10) + binding.stationName.setFadingEdgeLength(10) + binding.stationUrl.setFadingEdgeLength(10) // attach touch listener - searchResultViewHolder.searchResultLayout.setOnClickListener { + binding.root.setOnClickListener { // move marked position val previousSelectedPosition = selectedPosition selectedPosition = holder.bindingAdapterPosition @@ -120,7 +126,7 @@ class SearchResultAdapter( // get the selected station from searchResults val selectedStation = searchResults[holder.bindingAdapterPosition] // perform pre-playback here - performPrePlayback(searchResultViewHolder.searchResultLayout.context, selectedStation.getStreamUri()) + performPrePlayback(binding.root.context, selectedStation.getStreamUri()) // hand over station listener.onSearchResultTapped(searchResult) } @@ -284,11 +290,7 @@ class SearchResultAdapter( /* * Inner class: ViewHolder for a radio station search result */ - private class SearchResultViewHolder(var searchResultLayout: View) : - RecyclerView.ViewHolder(searchResultLayout) { - val nameView: MaterialTextView = searchResultLayout.findViewById(R.id.station_name) - val streamView: MaterialTextView = searchResultLayout.findViewById(R.id.station_url) - val bitrateView: MaterialTextView = searchResultLayout.findViewById(R.id.station_bitrate) - } + private class SearchResultViewHolder(val binding: ElementSearchResultBinding) : + RecyclerView.ViewHolder(binding.root) } diff --git a/app/src/main/java/com/michatec/radio/ui/LayoutHolder.kt b/app/src/main/java/com/michatec/radio/ui/LayoutHolder.kt index 0f37cfd..f3a05bf 100644 --- a/app/src/main/java/com/michatec/radio/ui/LayoutHolder.kt +++ b/app/src/main/java/com/michatec/radio/ui/LayoutHolder.kt @@ -36,49 +36,51 @@ import com.michatec.radio.helpers.DateTimeHelper import com.michatec.radio.helpers.ImageHelper import com.michatec.radio.helpers.PreferencesHelper import com.michatec.radio.helpers.ThemeHelper -import com.michatec.radio.helpers.UiHelper +import com.michatec.radio.databinding.FragmentPlayerBinding +import com.michatec.radio.helpers.* import java.util.Locale /* * LayoutHolder class */ -data class LayoutHolder(var rootView: View) { +class LayoutHolder(binding: FragmentPlayerBinding) { /* Main class variables */ - var recyclerView: RecyclerView = rootView.findViewById(R.id.station_list) + private val rootView: View = binding.root + var recyclerView: RecyclerView = binding.stationList val layoutManager: LinearLayoutManager - var bottomSheet: ConstraintLayout? = rootView.findViewById(R.id.bottom_sheet) + var bottomSheet: ConstraintLayout? = binding.playerSheet?.bottomSheet //private var sheetMetadataViews: Group - private var sleepTimerRunningViews: Group? = rootView.findViewById(R.id.sleep_timer_running_views) - private var downloadProgressIndicator: ProgressBar? = rootView.findViewById(R.id.download_progress_indicator) - private var stationImageView: ImageView? = rootView.findViewById(R.id.station_icon) - private var shaderEffectView: ShaderEffectView? = rootView.findViewById(R.id.player_shader_effect) - private var stationNameView: TextView? = rootView.findViewById(R.id.player_station_name) - private var metadataView: TextView? = rootView.findViewById(R.id.player_station_metadata) - var playButtonView: ImageButton = rootView.findViewById(R.id.player_play_button) - var playerPrevButtonView: ImageButton? = rootView.findViewById(R.id.player_prev_button) - var playerNextButtonView: ImageButton? = rootView.findViewById(R.id.player_next_button) - private var bufferingIndicator: ProgressBar = rootView.findViewById(R.id.player_buffering_indicator) - private var searchLayout: View? = rootView.findViewById(R.id.search_layout) - var searchInputEditText: TextInputEditText? = rootView.findViewById(R.id.search_input_edit_text) - var searchFilterFavoritesSwitch: MaterialSwitch? = rootView.findViewById(R.id.search_filter_favorites_switch) - private var searchNoResultsView: View? = rootView.findViewById(R.id.search_no_results_view) - private var sheetStreamingLinkHeadline: TextView? = rootView.findViewById(R.id.sheet_streaming_link_headline) - private var sheetStreamingLinkView: TextView? = rootView.findViewById(R.id.sheet_streaming_link) - private var sheetMetadataHistoryHeadline: TextView? = rootView.findViewById(R.id.sheet_metadata_headline) - private var sheetMetadataHistoryView: TextView? = rootView.findViewById(R.id.sheet_metadata_history) - private var sheetNextMetadataView: ImageButton? = rootView.findViewById(R.id.sheet_next_metadata_button) - private var sheetPreviousMetadataView: ImageButton? = rootView.findViewById(R.id.sheet_previous_metadata_button) - private var sheetCopyMetadataButtonView: ImageButton? = rootView.findViewById(R.id.copy_station_metadata_button) - private var mediaRouteButton: MediaRouteButton? = rootView.findViewById(R.id.media_route_button) - private var sheetShareLinkButtonView: ImageView? = rootView.findViewById(R.id.sheet_share_link_button) - private var sheetBitrateView: TextView? = rootView.findViewById(R.id.sheet_bitrate_view) - var sheetSleepTimerStartButtonView: ImageButton? = rootView.findViewById(R.id.sleep_timer_start_button) - var sheetSleepTimerCancelButtonView: ImageButton? = rootView.findViewById(R.id.sleep_timer_cancel_button) - private var sheetSleepTimerRemainingTimeView: TextView = rootView.findViewById(R.id.sleep_timer_remaining_time) - private var onboardingLayout: ConstraintLayout = rootView.findViewById(R.id.onboarding_layout) + private var sleepTimerRunningViews: Group? = binding.playerSheet?.sleepTimerRunningViews + private var downloadProgressIndicator: ProgressBar? = binding.downloadProgressIndicator + private var stationImageView: ImageView? = binding.playerSheet?.stationIcon ?: binding.stationIcon + private var shaderEffectView: ShaderEffectView? = binding.playerSheet?.playerShaderEffect ?: binding.playerShaderEffect + private var stationNameView: TextView? = binding.playerSheet?.playerStationName ?: binding.playerStationName + private var metadataView: TextView? = binding.playerSheet?.playerStationMetadata ?: binding.playerStationMetadata + var playButtonView: ImageButton = binding.playerSheet?.playerPlayButton ?: binding.playerPlayButton!! + var playerPrevButtonView: ImageButton? = binding.playerPrevButton + var playerNextButtonView: ImageButton? = binding.playerNextButton + private var bufferingIndicator: ProgressBar = binding.playerSheet?.playerBufferingIndicator ?: binding.playerBufferingIndicator!! + private var searchLayout: View? = binding.searchLayout + var searchInputEditText: TextInputEditText? = binding.searchInputEditText + var searchFilterFavoritesSwitch: MaterialSwitch? = binding.searchFilterFavoritesSwitch + private var searchNoResultsView: View? = binding.searchNoResultsView + private var sheetStreamingLinkHeadline: TextView? = binding.playerSheet?.sheetStreamingLinkHeadline + private var sheetStreamingLinkView: TextView? = binding.playerSheet?.sheetStreamingLink + private var sheetMetadataHistoryHeadline: TextView? = binding.playerSheet?.sheetMetadataHeadline + private var sheetMetadataHistoryView: TextView? = binding.playerSheet?.sheetMetadataHistory + private var sheetNextMetadataView: ImageButton? = binding.playerSheet?.sheetNextMetadataButton + private var sheetPreviousMetadataView: ImageButton? = binding.playerSheet?.sheetPreviousMetadataButton + private var sheetCopyMetadataButtonView: ImageButton? = binding.playerSheet?.copyStationMetadataButton ?: binding.copyStationMetadataButton + private var mediaRouteButton: MediaRouteButton? = binding.playerSheet?.mediaRouteButton + private var sheetShareLinkButtonView: ImageView? = binding.playerSheet?.sheetShareLinkButton + private var sheetBitrateView: TextView? = binding.playerSheet?.sheetBitrateView + var sheetSleepTimerStartButtonView: ImageButton? = binding.playerSheet?.sleepTimerStartButton ?: binding.sleepTimerStartButton + var sheetSleepTimerCancelButtonView: ImageButton? = binding.playerSheet?.sleepTimerCancelButton ?: binding.sleepTimerCancelButton + private var sheetSleepTimerRemainingTimeView: TextView? = binding.playerSheet?.sleepTimerRemainingTime ?: binding.sleepTimerRemainingTime + private var onboardingLayout: ConstraintLayout = binding.root.findViewById(R.id.onboarding_layout) private var bottomSheetBehavior: BottomSheetBehavior? = bottomSheet?.let { BottomSheetBehavior.from(it) } private var metadataHistory: MutableList private var metadataHistoryPosition: Int @@ -303,14 +305,14 @@ data class LayoutHolder(var rootView: View) { when (timeRemaining) { 0L -> { sleepTimerRunningViews?.isGone = true - sheetSleepTimerRemainingTimeView.isVisible = false + sheetSleepTimerRemainingTimeView?.isVisible = false } else -> { sleepTimerRunningViews?.isVisible = true - sheetSleepTimerRemainingTimeView.isVisible = true + sheetSleepTimerRemainingTimeView?.isVisible = true val sleepTimerTimeRemaining = DateTimeHelper.convertToHoursMinutesSeconds(timeRemaining) - sheetSleepTimerRemainingTimeView.text = sleepTimerTimeRemaining - sheetSleepTimerRemainingTimeView.contentDescription = "${context.getString(R.string.descr_expanded_player_sleep_timer_remaining_time)}: $sleepTimerTimeRemaining" + sheetSleepTimerRemainingTimeView?.text = sleepTimerTimeRemaining + sheetSleepTimerRemainingTimeView?.contentDescription = "${context.getString(R.string.descr_expanded_player_sleep_timer_remaining_time)}: $sleepTimerTimeRemaining" stationNameView?.isSelected = false } } diff --git a/app/src/main/res/layout/fragment_player.xml b/app/src/main/res/layout/fragment_player.xml index 8405acd..bdacb9e 100644 --- a/app/src/main/res/layout/fragment_player.xml +++ b/app/src/main/res/layout/fragment_player.xml @@ -95,7 +95,9 @@ - +