Merge pull request #85 from Michatec/add-function-webapp-control

Add function webapp control & others
This commit is contained in:
Michachatz authored and GitHub committed 2026-08-05 21:52:38 +02:00
commit bce6d3e3e9
42 files changed
+2431 -583

No files matched your search

+1 -1
View File
@@ -10,6 +10,7 @@
**Radio is an application with a minimalist approach to listening to radio over the Internet.** <br>
**Radio only offers a very basic search option, and it imports audio streaming links when you tap them in a web browser.** <br>
**Radio now also supports Android TV and Cast to Devices (Beta) with the Version 14.5 and above.** <br>
**New Feature Update: Web Control with API for devs.**<br>
**Pull request are welcome at any time.**<br>
**Radio is free software. It is released under the [GPLv3 open source license](https://opensource.org/licenses/GPL-3.0).**
@@ -91,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
+3 -3
View File
@@ -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.
+18 -3
View File
@@ -1,5 +1,6 @@
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.serialization)
id("kotlin-parcelize")
}
@@ -22,12 +23,12 @@ android {
buildFeatures {
buildConfig = true
viewBinding = true
}
buildTypes {
debug {
isMinifyEnabled = false
//noinspection NotShrinkingResources
isShrinkResources = false
isCrunchPngs = false
proguardFiles.addAll(listOf(getDefaultProguardFile("proguard-android-optimize.txt"), file("proguard-rules.pro")))
@@ -36,8 +37,8 @@ android {
}
release {
isMinifyEnabled = true
isShrinkResources = true
isMinifyEnabled = false
isShrinkResources = false
isCrunchPngs = true
proguardFiles.addAll(listOf(getDefaultProguardFile("proguard-android-optimize.txt"), file("proguard-rules.pro")))
buildConfigField("boolean", "IS_DEBUG_ENABLED", "false")
@@ -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)
Binary file not shown.

After

Width:  |  Height:  |  Size: 4.6 KiB

+176
View File
@@ -0,0 +1,176 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title data-t="title">Radio Remote</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/png" href="favicon.png">
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body class="dark-theme">
<div class="dashboard">
<header>
<h1 data-t="title">Radio Remote</h1>
<button id="menuBtn" class="icon-btn"><span class="material-icons">settings</span></button>
</header>
<main id="mainDashboard">
<section class="now-playing glass">
<div class="current-station-info">
<div class="current-text-info">
<div class="current-title-row">
<div id="currentName" class="current-name" data-t="status_loading">Loading...</div>
<span id="currentStar" class="material-icons starred-icon hidden">star</span>
</div>
<div id="currentMetadata" class="current-metadata"></div>
</div>
<img id="currentImage" class="current-img" src="favicon.png" alt="Station">
</div>
<div id="status" class="status-badge" data-t="status_loading">Loading...</div>
<div class="controls">
<button id="prevBtn" class="icon-btn large"><span class="material-icons">skip_previous</span></button>
<button id="playPauseBtn" class="icon-btn x-large"><span class="material-icons" id="playPauseIcon">play_arrow</span></button>
<button id="nextBtn" class="icon-btn large"><span class="material-icons">skip_next</span></button>
</div>
</section>
<section class="station-section">
<h2 data-t="stations_title">Station Collection</h2>
<div id="stationList" class="station-grid"></div>
</section>
</main>
<main id="apiDocsView" class="hidden">
<div class="glass api-container">
<header class="api-header">
<button id="backToDashboard" class="icon-btn"><span class="material-icons">arrow_back</span></button>
<h1 data-t="api_docs">API Documentation</h1>
</header>
<div class="api-content">
<p>The Radio app provides a REST API to control playback and query information.</p>
<h2>API Reference</h2>
<div class="endpoint">
<h3><span class="method get">GET</span> <code>/api/status</code></h3>
<p>Returns current playback status.</p>
<div class="code-example">Response Example:</div>
<pre>
{
"isPlaying": true,
"playWhenReady": true,
"playbackState": 3,
"currentStationUuid": "fc080549-...",
"metadata": "Artist - Title",
"starred": true
} </pre>
</div>
<div class="endpoint">
<h3><span class="method get">GET</span> <code>/api/stations</code></h3>
<p>Returns all stations in collection.</p>
<div class="code-example">Response Example:</div>
<pre>
[
{
"uuid": "fc080549-...",
"name": "Station Name",
"hasImage": true,
"starred": true
}
] </pre>
</div>
<div class="endpoint">
<h3><span class="method get">GET</span> <code>/api/image/{uuid}</code></h3>
<p>Returns the image for a specific station.</p>
<div class="code-example">Response: Image (binary data, JPEG)</div>
</div>
<div class="endpoint">
<h3><span class="method get">GET</span> <code>/api/config</code></h3>
<p>Returns the app version.</p>
<div class="code-example">Response Example:</div>
<pre>{ "version": "15.1" }</pre>
</div>
<div class="endpoint">
<h3><span class="method post">POST</span> <code>/api/play/{uuid}</code></h3>
<p>Starts playback of a specific station.</p>
<div class="code-example">Response Example:</div>
<pre>{ "status": "ok" }</pre>
</div>
<div class="endpoint">
<h3><span class="method post">POST</span> <code>/api/pause</code></h3>
<p>Pauses current playback.</p>
<div class="code-example">Response Example:</div>
<pre>{ "status": "ok" }</pre>
</div>
<div class="endpoint">
<h3><span class="method post">POST</span> <code>/api/resume</code></h3>
<p>Resumes current playback.</p>
<div class="code-example">Response Example:</div>
<pre>{ "status": "ok" }</pre>
</div>
<div class="endpoint">
<h3><span class="method post">POST</span> <code>/api/next</code></h3>
<p>Plays the next station.</p>
<div class="code-example">Response Example:</div>
<pre>{ "status": "ok" }</pre>
</div>
<div class="endpoint">
<h3><span class="method post">POST</span> <code>/api/prev</code></h3>
<p>Plays the previous station.</p>
<div class="code-example">Response Example:</div>
<pre>{ "status": "ok" }</pre>
</div>
</div>
</div>
</main>
<div id="settingsPanel" class="settings-panel glass hidden">
<div class="settings-content">
<div class="settings-header">
<h3 data-t="menu_theme">Theme</h3>
<button id="closeMenuBtn" class="icon-btn"><span class="material-icons">close</span></button>
</div>
<div class="setting-item">
<span data-t="menu_theme">Theme</span>
<label for="themeSelect"></label>
<select id="themeSelect">
<option value="auto_browser" data-t="theme_follow_browser">Follow Browser</option>
<option value="dark" data-t="theme_dark">Dark</option>
<option value="light" data-t="theme_light">Light</option>
</select>
</div>
<div class="setting-item">
<span data-t="menu_language">Language</span>
<label for="langSelect"></label>
<select id="langSelect">
<option value="auto_browser" data-t="lang_auto_browser">Auto (Browser)</option>
<option value="en">English</option>
<option value="de">Deutsch</option>
<option value="fr">Français</option>
<option value="ru">Русский</option>
<option value="nl">Nederlands</option>
<option value="pl">Polski</option>
<option value="ja">日本語</option>
<option value="uk">Українська</option>
<option value="el">Ελληνικά</option>
<option value="da">Dansk</option>
</select>
</div>
<div class="settings-footer">
<button id="showApiDocsBtn" class="link-btn" data-t="api_docs">API Documentation</button>
</div>
</div>
</div>
</div>
<script src="script.js?v=18"></script>
</body>
</html>
+298
View File
@@ -0,0 +1,298 @@
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 currentStarEl = document.getElementById('currentStar');
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.playWhenReady && !data.isPlaying) {
statusText = "Buffering...";
}
if (data.playbackState === STATE_BUFFERING) {
statusText = "Buffering...";
}
statusEl.innerText = statusText;
playPauseIcon.innerText = (data.isPlaying || data.playWhenReady) ? 'pause' : 'play_arrow';
const stationUuid = data.currentStationUuid;
updateActiveStation(stationUuid);
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';
}
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 content = document.createElement('div');
content.className = 'station-item-content';
const img = document.createElement('img');
img.className = 'station-img';
if (station.hasImage) {
img.src = '/api/image/' + station.uuid;
} else {
img.src = 'favicon.png';
}
content.appendChild(img);
const name = document.createElement('div');
name.className = 'station-name';
name.innerText = station.name || 'Unnamed Station';
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);
});
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('currentStar').classList.toggle('hidden', !station.starred);
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();
+369
View File
@@ -0,0 +1,369 @@
: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-title-row {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 4px;
}
.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;
}
.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-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;
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%; }
}
+202
View File
@@ -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"
}
}
@@ -1,15 +1,12 @@
package com.michatec.radio
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
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
@@ -18,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
@@ -39,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
@@ -57,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
@@ -93,7 +78,12 @@ class AddStationFragment : Fragment(),
}
})
return view
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onDestroy() {
@@ -106,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<EditText>(androidx.appcompat.R.id.search_src_text)
@@ -126,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) {
@@ -166,29 +156,25 @@ class AddStationFragment : Fragment(),
}
override fun activateAddButton() {
positiveButton.isEnabled = true
binding.dialogPositiveButton?.isEnabled = true
}
override fun deactivateAddButton() {
positiveButton.isEnabled = false
binding.dialogPositiveButton?.isEnabled = false
}
@SuppressLint("NotifyDataSetChanged")
override fun onRadioBrowserSearchResults(results: Array<RadioBrowserResult>) {
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<Station>) {
if (stationList.isNotEmpty()) {
searchResultAdapter.searchResults = stationList
searchResultAdapter.notifyDataSetChanged()
searchResultAdapter.updateSearchResults(stationList)
resetLayout(false)
} else {
showNoResultsError()
@@ -196,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
}
}
@@ -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
@@ -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
@@ -115,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
@@ -17,14 +17,16 @@ 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
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.databinding.ActivityMainBinding
import com.michatec.radio.helpers.AppThemeHelper
import com.michatec.radio.helpers.FileHelper
import com.michatec.radio.helpers.LanguageHelper
@@ -39,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 {
@@ -53,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
)
@@ -66,7 +68,9 @@ class MainActivity : AppCompatActivity() {
startActivity(intent)
}
}
snackbar.anchorView = findViewById(R.id.bottom_sheet)
findViewById<View>(R.id.bottom_sheet)?.let {
snackbar.anchorView = it
}
snackbar.show()
}
}
@@ -92,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
@@ -120,7 +124,7 @@ class MainActivity : AppCompatActivity() {
hideLoadingOverlay()
}, 1200)
} else {
findViewById<View>(R.id.loading_layout)?.visibility = View.GONE
binding.loadingLayout.visibility = View.GONE
}
// register listener for changes in shared preferences
@@ -132,9 +136,24 @@ 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<View>(R.id.loading_layout)?.let { overlay ->
binding.loadingLayout.let { overlay ->
if (overlay.isVisible) {
overlay.animate().alpha(0f).setDuration(500)
.withEndAction { overlay.visibility = View.GONE }
@@ -160,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)
}
}
@@ -189,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()
}
@@ -220,6 +239,26 @@ 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(
binding.mainRoot,
R.string.error_webserver,
Snackbar.LENGTH_LONG
)
this@MainActivity.findViewById<View>(R.id.bottom_sheet)?.let {
snackbar.anchorView = it
}
snackbar.show()
}
}
}
/*
* End of declaration
*/
@@ -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
@@ -58,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
@@ -82,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
@@ -97,6 +103,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 {
@@ -179,25 +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
}
@@ -381,6 +394,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 +545,7 @@ class PlayerFragment : Fragment(),
Snackbar.LENGTH_SHORT
)
if (!isAndroidTV) {
snackbar.setAnchorView(layout.bottomSheet)
snackbar.anchorView = layout.bottomSheet
}
snackbar.show()
}
@@ -532,6 +559,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 +648,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 +773,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)
@@ -60,6 +60,41 @@ 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)
}
onGetCollection = {
collection
}
onPause = {
player.pause()
}
onResume = {
if (player.playbackState == Player.STATE_IDLE) {
val mediaId = player.currentMediaItem?.mediaId ?: PreferencesHelper.loadLastPlayedStationUuid()
playStation(mediaId)
} else {
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 +112,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 +147,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 +417,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 +450,14 @@ 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)
}
}
/* Starts playback of a radio station */
private fun playStation(station: Station) {
@@ -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)
@@ -474,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)
@@ -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
@@ -10,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
@@ -24,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
/*
@@ -50,12 +57,15 @@ class CollectionAdapter(
/* Main class variables */
private lateinit var collectionViewModel: CollectionViewModel
private var collection: Collection = Collection()
private var filteredStations: MutableList<Station> = 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 +73,7 @@ class CollectionAdapter(
fun onPlayButtonTapped(stationUuid: String)
fun onAddNewButtonTapped()
fun onChangeImageButtonTapped(stationUuid: String)
fun onSearchButtonTapped()
}
@@ -91,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
)
)
}
}
}
@@ -108,31 +125,34 @@ 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
}
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)
@@ -141,8 +161,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,28 +178,53 @@ class CollectionAdapter(
}
/* Filters the station list based on query and favorite status */
fun filter(query: String, onlyFavorites: Boolean) {
currentSearchQuery = query
currentOnlyFavorites = onlyFavorites
applyFilter()
}
private fun applyFilter() {
val oldStations = filteredStations.toList()
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()
}
val diffResult = DiffUtil.calculateDiff(CollectionDiffCallback(oldStations, filteredStations))
diffResult.dispatchUpdatesTo(this)
}
/* Overrides onBindViewHolder */
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
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)
}
binding.playerSearchButton.setOnClickListener {
collectionAdapterListener.onSearchButtonTapped()
}
binding.playerSearchButton.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
@@ -189,44 +238,14 @@ 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
}
// 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)
}
}
}
@@ -238,29 +257,24 @@ 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()
}
/* 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
}
}
@@ -268,57 +282,66 @@ 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
)
stationViewHolder.stationUriEditView.addTextChangedListener(object : TextWatcher {
// Remove existing TextWatcher to prevent leaks and redundant updates
stationViewHolder.textWatcher?.let {
binding.editStreamUri.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.cancelButton.setOnClickListener {
}
stationViewHolder.textWatcher = newTextWatcher
binding.editStreamUri.addTextChangedListener(newTextWatcher)
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,
position,
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)
}
}
@@ -339,49 +362,78 @@ 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 binding = stationViewHolder.binding
val isExpanded = expandedStationUuid == station.uuid
if (isExpanded) {
binding.stationName.isVisible = false
binding.playbackButton.isGone = true
binding.starredIcon.isGone = true
binding.defaultEditViews.isVisible = true
if (editStationStreamsEnabled) {
binding.editStreamUri.isVisible = true
binding.editStreamUri.imeOptions = EditorInfo.IME_ACTION_DONE
} else {
binding.editStreamUri.isGone = true
binding.editStationName.imeOptions = EditorInfo.IME_ACTION_DONE
}
// Allow internal focus
binding.stationCard.descendantFocusability = ViewGroup.FOCUS_AFTER_DESCENDANTS
} else {
binding.stationName.isVisible = true
binding.starredIcon.isVisible = station.starred
binding.defaultEditViews.isGone = true
binding.editStreamUri.isGone = true
// Block internal focus
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 = true
binding.starredIcon.isVisible = !isExpanded
}
false -> {
stationViewHolder.stationStarredView.clearColorFilter()
stationViewHolder.stationStarredView.isGone = true
binding.starredIcon.clearColorFilter()
binding.starredIcon.isGone = true
}
}
}
@@ -389,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) {
@@ -464,13 +518,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
@@ -488,7 +535,7 @@ class CollectionAdapter(
false
}
stationViewHolder.playButtonView.setOnLongClickListener {
binding.playbackButton.setOnLongClickListener {
if (editStationsEnabled) {
val position: Int = stationViewHolder.bindingAdapterPosition
toggleEditViews(position, station.uuid)
@@ -497,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)
@@ -506,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)
@@ -515,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)
@@ -533,18 +580,22 @@ 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.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<NetworkHelper.ContentType> =
async(Dispatchers.Default) {
NetworkHelper.detectContentTypeSuspended(input)
@@ -560,7 +611,7 @@ class CollectionAdapter(
) {
// re-enable save button
withContext(Main) {
stationViewHolder.saveButton.isEnabled = true
binding.saveButton.isEnabled = true
}
}
}
@@ -583,7 +634,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) {
@@ -603,6 +654,10 @@ class CollectionAdapter(
Keys.HOLDER_UPDATE_DOWNLOAD_STATE -> {
setDownloadProgress(holder, station)
}
Keys.HOLDER_UPDATE_EXPANSION -> {
setEditViews(holder, station)
updateVisibility(holder, station)
}
}
}
}
@@ -621,19 +676,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,16 +702,25 @@ class CollectionAdapter(
/* Toggles starred status of a station */
fun toggleStarredStation(context: Context, position: Int) {
// 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 }
// sort collection
val station = filteredStations[position]
val originalIndex = collection.stations.indexOfFirst { it.uuid == station.uuid }
if (originalIndex == -1) return
// 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)
// update list
notifyItemMoved(position, CollectionHelper.getStationPosition(collection, stationUuid))
// save collection and broadcast changes
// Trigger immediate UI update via DiffUtil
applyFilter()
// Save collection and broadcast changes
CollectionHelper.saveCollection(context, collection)
}
@@ -659,30 +728,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)
}
@@ -690,23 +759,14 @@ class CollectionAdapter(
/* Determines if position is last */
private fun isPositionFooter(position: Int): Boolean {
return position == collection.stations.size
return position == filteredStations.size
}
/* 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
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)
}
applyFilter()
}
@@ -724,7 +784,7 @@ class CollectionAdapter(
/* Observe view model of station collection*/
private fun observeCollectionViewModel(owner: LifecycleOwner) {
collectionViewModel.collectionLiveData.observe(owner) { newCollection ->
updateRecyclerView(collection, newCollection)
updateRecyclerView(newCollection)
}
}
@@ -749,15 +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)
}
private class AddNewViewHolder(val binding: CardAddNewStationBinding) :
RecyclerView.ViewHolder(binding.root)
/*
* End of inner class
*/
@@ -766,28 +819,10 @@ 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
}
/*
* End of inner class
@@ -798,27 +833,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<Station>,
private val newStations: List<Station>
) : 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
@@ -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
}
@@ -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) { _, _ ->
@@ -1,26 +1,22 @@
package com.michatec.radio.dialogs
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
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
@@ -45,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
@@ -66,20 +57,17 @@ 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()
}
/* Overrides onRadioBrowserSearchResults from RadioBrowserSearchListener */
/* TODO: Remove @SuppressLint("NotifyDataSetChanged"), remove NotifyDataSetChanged */
@SuppressLint("NotifyDataSetChanged")
override fun onRadioBrowserSearchResults(results: Array<RadioBrowserResult>) {
if (results.isNotEmpty()) {
val stationList: List<Station> = results.map {it.toStation()}
searchResultAdapter.searchResults = stationList
searchResultAdapter.notifyDataSetChanged()
searchResultAdapter.updateSearchResults(stationList)
resetLayout(clearAdapter = false)
} else {
showNoResultsError()
@@ -90,9 +78,7 @@ class FindStationDialog (
/* Overrides onDirectInputCheck from DirectInputCheck */
override fun onDirectInputCheck(stationList: MutableList<Station>) {
if (stationList.isNotEmpty()) {
val startPosition = searchResultAdapter.searchResults.size
searchResultAdapter.searchResults = stationList
searchResultAdapter.notifyItemRangeInserted(startPosition, stationList.size)
searchResultAdapter.updateSearchResults(stationList)
resetLayout(clearAdapter = false)
} else {
showNoResultsError()
@@ -112,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
@@ -147,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()
@@ -174,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
@@ -198,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()
}
@@ -256,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)
}
@@ -282,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
}
}
@@ -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<RadioGroup>(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<RadioButton>(checkedId)
binding.languageRadioGroup.setOnCheckedChangeListener { _, checkedId ->
val selectedButton = binding.languageRadioGroup.findViewById<RadioButton>(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 {
@@ -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<android.widget.RadioGroup>(R.id.preset_radio_group)
val radioNone = view.findViewById<RadioButton>(R.id.radio_preset_none)
val radioRock = view.findViewById<RadioButton>(R.id.radio_preset_rock)
val radioPop = view.findViewById<RadioButton>(R.id.radio_preset_pop)
val radioJazz = view.findViewById<RadioButton>(R.id.radio_preset_jazz)
val radioFlat = view.findViewById<RadioButton>(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 {
@@ -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<android.widget.RadioGroup>(R.id.theme_radio_group)
val radioFollowSystem = view.findViewById<RadioButton>(R.id.radio_theme_follow_system)
val radioLight = view.findViewById<RadioButton>(R.id.radio_theme_light)
val radioDark = view.findViewById<RadioButton>(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 {
@@ -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}")
@@ -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 {
@@ -0,0 +1,284 @@
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<NettyApplicationEngine, NettyApplicationEngine.Configuration>? = null
private var player: Player? = null
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
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 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,
"starred" to station.starred
)
}
call.respond(status)
} catch (e: Exception) {
call.respond(HttpStatusCode.InternalServerError, mapOf("error" to e.message))
}
}
}
get("/api/stations") {
try {
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(),
"starred" to it.starred
)
}
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)
}
}
}
}
@@ -18,10 +18,11 @@ 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
import com.michatec.radio.core.Station
import com.michatec.radio.databinding.ElementSearchResultBinding
import com.michatec.radio.helpers.NativeAudioProcessor
import com.michatec.radio.helpers.PreferencesHelper
@@ -48,16 +49,15 @@ 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)
.inflate(R.layout.element_search_result, parent, false)
return SearchResultViewHolder(v)
return SearchResultViewHolder(
ElementSearchResultBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
)
}
@@ -67,51 +67,49 @@ 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
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
@@ -128,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)
}
@@ -247,9 +245,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,14 +253,44 @@ class SearchResultAdapter(
}
/* Updates the search results using DiffUtil */
fun updateSearchResults(newList: List<Station>) {
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<Station>,
private val newList: List<Station>
) : 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
*/
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)
}
@@ -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
@@ -31,45 +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 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<ConstraintLayout>? = bottomSheet?.let { BottomSheetBehavior.from(it) }
private var metadataHistory: MutableList<String>
private var metadataHistoryPosition: Int
@@ -294,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
}
}
@@ -362,6 +373,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 {
@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="@color/icon_default"
android:pathData="M15.5,14h-0.79l-0.28,-0.27C15.41,12.59 16,11.11 16,9.5 16,5.91 13.09,3 9.5,3S3,5.91 3,9.5 5.91,16 9.5,16c1.61,0 3.09,-0.59 4.23,-1.57l0.27,0.28v0.79l5,4.99L20.49,19l-4.99,-5zM9.5,14C7.01,14 5,11.99 5,9.5S7.01,5 9.5,5 14,7.01 14,9.5 11.99,14 9.5,14z"/>
</vector>
@@ -12,6 +12,54 @@
android:layout_height="match_parent"
android:layout_weight="1">
<!-- SEARCH BAR -->
<LinearLayout
android:id="@+id/search_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp"
android:visibility="gone"
app:layout_constraintTop_toTopOf="parent"
tools:visibility="visible">
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/search_input_layout"
style="@style/Widget.Material3.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:endIconMode="clear_text"
app:startIconDrawable="@drawable/ic_search_24dp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/search_input_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/search_hint"
android:inputType="text"
android:maxLines="1" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.materialswitch.MaterialSwitch
android:id="@+id/search_filter_favorites_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:text="@string/search_filter_favorites" />
<!-- NO RESULTS MESSAGE -->
<TextView
android:id="@+id/search_no_results_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/search_no_results"
android:textAppearance="@style/TextAppearance.Material3.BodyLarge"
android:visibility="gone" />
</LinearLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/station_list"
android:layout_width="match_parent"
@@ -19,7 +67,7 @@
android:clipToPadding="false"
android:padding="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintTop_toTopOf="parent" />
app:layout_constraintTop_toBottomOf="@+id/search_layout" />
<include
layout="@layout/element_onboarding"
@@ -22,6 +22,24 @@
app:strokeColor="@color/list_card_stroke_background"
app:strokeWidth="3dp" />
<com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
android:id="@+id/player_search_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginTop="10dp"
android:layout_marginEnd="130dp"
android:layout_marginBottom="24dp"
android:focusable="true"
android:clickable="true"
android:stateListAnimator="@null"
app:backgroundTint="@color/list_card_background"
app:icon="@drawable/ic_search_24dp"
app:iconTint="@color/icon_default"
app:rippleColor="@color/list_card_stroke_background"
app:strokeColor="@color/list_card_stroke_background"
app:strokeWidth="3dp" />
<com.google.android.material.floatingactionbutton.ExtendedFloatingActionButton
android:id="@+id/card_visualizer"
android:layout_width="wrap_content"
+74 -10
View File
@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
@@ -19,21 +20,84 @@
android:orientation="vertical"
tools:context="com.michatec.radio.PlayerFragment">
<!-- STATION LIST -->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/station_list"
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="2dp"
android:visibility="visible" />
android:orientation="vertical">
<!-- ONBOARDING -->
<include
layout="@layout/element_onboarding"
android:visibility="gone" />
<!-- SEARCH BAR -->
<LinearLayout
android:id="@+id/search_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp"
android:visibility="gone"
tools:visibility="visible">
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/search_input_layout"
style="@style/Widget.Material3.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:endIconMode="clear_text"
app:startIconDrawable="@drawable/ic_search_24dp">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/search_input_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/search_hint"
android:inputType="text"
android:maxLines="1" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.materialswitch.MaterialSwitch
android:id="@+id/search_filter_favorites_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="4dp"
android:text="@string/search_filter_favorites" />
<!-- NO RESULTS MESSAGE -->
<TextView
android:id="@+id/search_no_results_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/search_no_results"
android:textAppearance="@style/TextAppearance.Material3.BodyLarge"
android:visibility="gone" />
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<!-- STATION LIST -->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/station_list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="2dp"
android:visibility="visible" />
<!-- ONBOARDING -->
<include
layout="@layout/element_onboarding"
android:visibility="gone" />
</FrameLayout>
</LinearLayout>
<!-- PLAYER SHEET -->
<include layout="@layout/bottom_sheet_playback_controls" />
<include
android:id="@+id/player_sheet"
layout="@layout/bottom_sheet_playback_controls" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
+10
View File
@@ -185,4 +185,14 @@
<string name="widget_favorites_title">Favoritter</string>
<string name="widget_favorites_empty">Ingen favoritter tilføjet endnu.</string>
<string name="widget_favorites_description">Viser en liste over dine yndlingsstationer for hurtig adgang.</string>
<!-- Remote Control -->
<string name="pref_remote_control_title">Fjernbetjening</string>
<string name="pref_remote_control_summary">Betjen radioen fra din webbrowser</string>
<string name="pref_remote_control_url">Betjen radioen fra http://%1$s:8080</string>
<string name="error_webserver">Web fjernbetjeningsserver crashet/stoppede.</string>
<string name="search_hint">Søg stationer…</string>
<string name="search_filter_favorites">Kun favoritter</string>
<string name="search_no_results">Ingen stationer fundet.</string>
<string name="descr_player_search_button">Søg stationer</string>
</resources>
+10
View File
@@ -15,6 +15,7 @@
<string name="descr_expanded_player_sleep_timer_start_button">Schlaf-Timer starten</string>
<string name="descr_player_playback_button">Start/Pause</string>
<string name="descr_player_station_image">Senderbild</string>
<string name="descr_player_search_button">Sender suchen</string>
<!-- Dialogs -->
<string name="dialog_add_station_title">Station hinzufügen</string>
<string name="dialog_edit_station_name">Sendername</string>
@@ -187,4 +188,13 @@
<string name="widget_favorites_title">Favoriten</string>
<string name="widget_favorites_empty">Noch keine Favoriten hinzugefügt.</string>
<string name="widget_favorites_description">Zeigt eine Liste deiner Favoriten-Sender für den Schnellzugriff.</string>
<!-- Remote Control -->
<string name="pref_remote_control_title">Fernbedienung</string>
<string name="pref_remote_control_summary">Steuere das Radio über deinen Webbrowser</string>
<string name="pref_remote_control_url">Steuere das Radio über http://%1$s:8080</string>
<string name="error_webserver">Web-Fernbedienungsserver abgestürzt/gestoppt.</string>
<string name="search_hint">Sender suchen…</string>
<string name="search_filter_favorites">Nur Favoriten</string>
<string name="search_no_results">Keine Sender gefunden.</string>
</resources>
+11
View File
@@ -187,4 +187,15 @@
<string name="widget_favorites_title">Αγαπημένα</string>
<string name="widget_favorites_empty">Δεν έχουν προστεθεί ακόμα αγαπημένα.</string>
<string name="widget_favorites_description">Εμφανίζει μια λίστα με τους αγαπημένους σας σταθμούς για γρήγορη πρόσβαση.</string>
<!-- Remote Control -->
<string name="pref_remote_control_title">Τηλεχειριστήριο</string>
<string name="pref_remote_control_summary">Ελέγξτε το ραδιόφωνο από το πρόγραμμα περιήγησής σας</string>
<string name="pref_remote_control_url">Ελέγξτε το ραδιόφωνο από το http://%1$s:8080</string>
<string name="error_webserver">Ο διακομιστής τηλεχειριστηρίου ιστού κατέρρευσε/σταμάτησε.</string>
<string name="descr_player_search_button">Αναζήτηση σταθμών</string>
<string name="search_hint">Αναζήτηση σταθμών…</string>
<string name="search_filter_favorites">Μόνο αγαπημένα</string>
<string name="search_no_results">Δεν βρέθηκαν σταθμοί.</string>
</resources>
+11
View File
@@ -185,4 +185,15 @@
<string name="widget_favorites_title">Favoris</string>
<string name="widget_favorites_empty">Aucun favori ajouté pour le moment.</string>
<string name="widget_favorites_description">Affiche une liste de vos stations préférées pour un accès rapide.</string>
<!-- Remote Control -->
<string name="pref_remote_control_title">Télécommande</string>
<string name="pref_remote_control_summary">Contrôlez la radio depuis votre navigateur web</string>
<string name="pref_remote_control_url">Contrôlez la radio depuis http://%1$s:8080</string>
<string name="error_webserver">Serveur de télécommande Web planté/arrêté.</string>
<string name="descr_player_search_button">Rechercher des stations</string>
<string name="search_hint">Rechercher des stations…</string>
<string name="search_filter_favorites">Favoris uniquement</string>
<string name="search_no_results">Aucune station trouvée.</string>
</resources>
+11 -1
View File
@@ -130,9 +130,9 @@
<string name="dialog_yes_no_positive_button_update_collection">更新</string>
<string name="pref_audio_effects_title">オーディオエフェクト</string>
<string name="pref_bass_boost_title">バスブースト</string>
<string name="pref_bass_boost_summary">低音を増強します。</string>
<string name="pref_security_title">セキュリティ</string>
<string name="pref_security_summary">このアプリケーションのセキュリティについて詳しく知る</string>
<string name="pref_bass_boost_summary">低音を増強します。</string>
<string name="pref_reverb_title">リバーブ</string>
<string name="pref_reverb_summary">リバーブミスを調整します。</string>
<string name="pref_drc_title">ダイナミックレンジ圧縮</string>
@@ -186,4 +186,14 @@
<string name="widget_favorites_title">お気に入り</string>
<string name="widget_favorites_empty">お気に入りはまだ追加されていません。</string>
<string name="widget_favorites_description">お気に入りのステーションを一覧表示し、素早くアクセスできます。</string>
<!-- Remote Control -->
<string name="pref_remote_control_title">リモコン</string>
<string name="pref_remote_control_summary">ウェブブラウザからラジオを操作</string>
<string name="pref_remote_control_url">http://%1$s:8080 からラジオを操作</string>
<string name="error_webserver">Webリモートサーバーがクラッシュ/停止しました。</string>
<string name="search_hint">局を検索…</string>
<string name="search_filter_favorites">お気に入りのみ</string>
<string name="search_no_results">局が見つかりません。</string>
<string name="descr_player_search_button">局を検索</string>
</resources>
+10
View File
@@ -187,4 +187,14 @@
<string name="widget_favorites_title">Favorieten</string>
<string name="widget_favorites_empty">Nog geen favorieten toegevoegd.</string>
<string name="widget_favorites_description">Toont een lijst met je favoriete zenders voor snelle toegang.</string>
<!-- Remote Control -->
<string name="pref_remote_control_title">Afstandsbediening</string>
<string name="pref_remote_control_summary">Bedien de radio vanuit je webbrowser</string>
<string name="pref_remote_control_url">Bedien de radio via http://%1$s:8080</string>
<string name="error_webserver">De webserver voor de afstandsbediening is gecrasht of gestopt.</string>
<string name="search_hint">Zenders zoeken…</string>
<string name="search_filter_favorites">Alleen favorieten</string>
<string name="search_no_results">Geen zenders gevonden.</string>
<string name="descr_player_search_button">Zenders zoeken</string>
</resources>
+9
View File
@@ -187,4 +187,13 @@
<string name="widget_favorites_title">Ulubione</string>
<string name="widget_favorites_empty">Nie dodano jeszcze żadnych ulubionych.</string>
<string name="widget_favorites_description">Wyświetla listę ulubionych stacji, zapewniając szybki dostęp.</string>
<!-- Remote Control -->
<string name="pref_remote_control_title">Pilot</string>
<string name="pref_remote_control_summary">Steruj radiem z przeglądarki internetowej</string>
<string name="pref_remote_control_url">Steruj radiem przez http://%1$s:8080</string>
<string name="error_webserver">Serwer zdalnego sterowania uległ awarii/zatrzymaniu.</string>
<string name="search_hint">Szukaj stacji…</string>
<string name="search_filter_favorites">Tylko ulubione</string>
<string name="search_no_results">Nie znaleziono stacji.</string>
<string name="descr_player_search_button">Szukaj stacji</string>
</resources>
+10
View File
@@ -187,4 +187,14 @@
<string name="widget_favorites_title">Избранное</string>
<string name="widget_favorites_empty">Избранное пока не добавлено.</string>
<string name="widget_favorites_description">Показывает список ваших любимых станций для быстрого доступа.</string>
<!-- Remote Control -->
<string name="pref_remote_control_title">Удалённое управление</string>
<string name="pref_remote_control_summary">Управляйте радио из вашего веб-браузера</string>
<string name="pref_remote_control_url">Управляйте радио через http://%1$s:8080</string>
<string name="error_webserver">Веб-сервер удалённого управления упал/остановлен.</string>
<string name="search_hint">Поиск станций…</string>
<string name="search_filter_favorites">Только избранное</string>
<string name="search_no_results">Станции не найдены.</string>
<string name="descr_player_search_button">Поиск станций</string>
</resources>
+10
View File
@@ -187,4 +187,14 @@
<string name="widget_favorites_title">Обране</string>
<string name="widget_favorites_empty">Ще не додано жодної станції до обраного.</string>
<string name="widget_favorites_description">Показує список ваших улюблених станцій для швидкого доступу.</string>
<!-- Remote Control -->
<string name="pref_remote_control_title">Дистанційне керування</string>
<string name="pref_remote_control_summary">Керуйте радіо з вашого веб-браузера</string>
<string name="pref_remote_control_url">Керуйте радіо через http://%1$s:8080</string>
<string name="error_webserver">Веб-сервер дистанційного керування аварійно зупинився/зупинено.</string>
<string name="search_hint">Пошук станцій…</string>
<string name="search_filter_favorites">Тільки улюблені</string>
<string name="search_no_results">Станцій не знайдено.</string>
<string name="descr_player_search_button">Пошук станцій</string>
</resources>
+10
View File
@@ -18,6 +18,7 @@
<string name="descr_expanded_player_sleep_timer_start_button">Start sleep timer</string>
<string name="descr_player_playback_button">Play/pause</string>
<string name="descr_player_station_image">Station image</string>
<string name="descr_player_search_button">Search stations</string>
<!-- Dialogs -->
<string name="dialog_add_station_title">Add Station</string>
@@ -222,4 +223,13 @@
<string name="widget_favorites_title">Favorites</string>
<string name="widget_favorites_empty">No favorites added yet.</string>
<string name="widget_favorites_description">Shows a list of your favorite stations for quick access.</string>
<!-- Remote Control -->
<string name="pref_remote_control_title">Remote Control</string>
<string name="pref_remote_control_summary">Control radio from your web browser</string>
<string name="pref_remote_control_url">Control radio from http://%1$s:8080</string>
<string name="error_webserver">Web Remote server crashed / stopped.</string>
<string name="search_hint">Search stations…</string>
<string name="search_filter_favorites">Only favorites</string>
<string name="search_no_results">No stations found.</string>
</resources>
+8
View File
@@ -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" }