666 lines
28 KiB
Kotlin
666 lines
28 KiB
Kotlin
package de.fojadrachi.playtube
|
||
|
||
import android.Manifest
|
||
import android.animation.ValueAnimator
|
||
import android.content.Context
|
||
import android.content.Intent
|
||
import android.content.pm.PackageManager
|
||
import android.graphics.Color
|
||
import android.graphics.Outline
|
||
import android.graphics.drawable.GradientDrawable
|
||
import android.os.Build
|
||
import android.os.Bundle
|
||
import android.os.Handler
|
||
import android.os.Looper
|
||
import android.text.InputFilter
|
||
import android.text.InputType
|
||
import android.view.LayoutInflater
|
||
import android.view.View
|
||
import android.view.ViewGroup
|
||
import android.view.ViewOutlineProvider
|
||
import android.widget.BaseAdapter
|
||
import android.widget.Button
|
||
import android.widget.EditText
|
||
import android.widget.ImageButton
|
||
import android.widget.ImageView
|
||
import android.widget.LinearLayout
|
||
import android.widget.ListView
|
||
import android.widget.SeekBar
|
||
import android.widget.TextView
|
||
import androidx.activity.OnBackPressedCallback
|
||
import androidx.activity.result.contract.ActivityResultContracts
|
||
import androidx.appcompat.app.AlertDialog
|
||
import androidx.appcompat.app.AppCompatActivity
|
||
import androidx.core.content.ContextCompat
|
||
import androidx.core.graphics.ColorUtils
|
||
import androidx.core.view.ViewCompat
|
||
import androidx.core.view.WindowInsetsCompat
|
||
import androidx.palette.graphics.Palette
|
||
|
||
/**
|
||
* "PC steuern": findet Playtube auf dem PC im selben WLAN und steuert es wie eine Fernbedienung
|
||
* (Titel, Cover, Play/Pause, Spulen, Lautstaerke, Like, Warteschlange, Playlists). Die Verbindung
|
||
* haelt [PcSession] mit dem Vordergrunddienst [PcRemoteService] - sie bleibt bestehen, wenn man diesen
|
||
* Bildschirm verlaesst. Protokoll siehe [PcRemote].
|
||
*/
|
||
class PcRemoteActivity : AppCompatActivity(), PcSession.Listener {
|
||
private val main = Handler(Looper.getMainLooper())
|
||
|
||
private var draggingPosition = false
|
||
private var draggingVolume = false
|
||
private var coverUrl = ""
|
||
private var gradientColor = BACKGROUND
|
||
private var gradientAnimator: ValueAnimator? = null
|
||
private var lastPhase = PcSession.Phase.IDLE
|
||
private var pendingTarget: PcDevice? = null
|
||
|
||
/** Meldung (Fehler / Verbindung verloren), die die Suche nicht ueberschreiben soll. */
|
||
private var note: String? = null
|
||
private var listMode: ListMode? = null
|
||
private var queueItems = listOf<QueueItem>()
|
||
private var playlistItems = listOf<PcPlaylist>()
|
||
private val devices = mutableListOf<PcDevice>()
|
||
|
||
private lateinit var status: TextView
|
||
private lateinit var devicePanel: View
|
||
private lateinit var playerPanel: View
|
||
private lateinit var listPanel: View
|
||
private lateinit var gradient: View
|
||
private lateinit var cover: ImageView
|
||
private lateinit var deviceName: TextView
|
||
private lateinit var trackTitle: TextView
|
||
private lateinit var trackSubtitle: TextView
|
||
private lateinit var positionBar: SeekBar
|
||
private lateinit var positionText: TextView
|
||
private lateinit var durationText: TextView
|
||
private lateinit var playPause: ImageButton
|
||
private lateinit var like: ImageButton
|
||
private lateinit var repeat: ImageButton
|
||
private lateinit var volumeBar: SeekBar
|
||
private lateinit var tabYoutube: Button
|
||
private lateinit var tabMusic: Button
|
||
private lateinit var deviceAdapter: RowAdapter
|
||
private lateinit var itemAdapter: RowAdapter
|
||
private lateinit var listTitle: TextView
|
||
private lateinit var listMessage: TextView
|
||
private lateinit var itemList: ListView
|
||
|
||
private enum class ListMode { QUEUE, PLAYLISTS }
|
||
|
||
private val notificationPermission =
|
||
registerForActivityResult(ActivityResultContracts.RequestPermission()) { /* ohne Erlaubnis: nur keine Benachrichtigung */ }
|
||
|
||
override fun onCreate(savedInstanceState: Bundle?) {
|
||
super.onCreate(savedInstanceState)
|
||
setContentView(R.layout.activity_pc_remote)
|
||
keepContentBetweenSystemBars()
|
||
|
||
status = findViewById(R.id.remoteStatus)
|
||
devicePanel = findViewById(R.id.devicePanel)
|
||
playerPanel = findViewById(R.id.playerPanel)
|
||
listPanel = findViewById(R.id.listPanel)
|
||
gradient = findViewById(R.id.gradient)
|
||
cover = findViewById(R.id.cover)
|
||
deviceName = findViewById(R.id.deviceName)
|
||
trackTitle = findViewById(R.id.trackTitle)
|
||
trackSubtitle = findViewById(R.id.trackSubtitle)
|
||
positionBar = findViewById(R.id.positionBar)
|
||
positionText = findViewById(R.id.positionText)
|
||
durationText = findViewById(R.id.durationText)
|
||
playPause = findViewById(R.id.playPauseButton)
|
||
like = findViewById(R.id.likeButton)
|
||
repeat = findViewById(R.id.repeatButton)
|
||
volumeBar = findViewById(R.id.volumeBar)
|
||
tabYoutube = findViewById(R.id.tabYoutube)
|
||
tabMusic = findViewById(R.id.tabMusic)
|
||
listTitle = findViewById(R.id.listTitle)
|
||
listMessage = findViewById(R.id.listMessage)
|
||
itemList = findViewById(R.id.itemList)
|
||
|
||
setupRoundCover()
|
||
applyGradient(BACKGROUND)
|
||
|
||
deviceAdapter = RowAdapter(this)
|
||
findViewById<ListView>(R.id.deviceList).apply {
|
||
adapter = deviceAdapter
|
||
setOnItemClickListener { _, _, position, _ -> devices.getOrNull(position)?.let(::connectTo) }
|
||
}
|
||
itemAdapter = RowAdapter(this)
|
||
itemList.apply {
|
||
adapter = itemAdapter
|
||
setOnItemClickListener { _, _, position, _ -> onListItemClicked(position) }
|
||
}
|
||
|
||
findViewById<Button>(R.id.searchButton).setOnClickListener {
|
||
note = null
|
||
search()
|
||
}
|
||
findViewById<Button>(R.id.manualButton).setOnClickListener { askForAddress() }
|
||
findViewById<Button>(R.id.disconnectButton).setOnClickListener { PcSession.disconnect() }
|
||
findViewById<ImageButton>(R.id.deviceBack).setOnClickListener { showPlayer() }
|
||
findViewById<ImageButton>(R.id.closeButton).setOnClickListener { finish() }
|
||
findViewById<ImageButton>(R.id.devicesButton).setOnClickListener { showDevices() }
|
||
findViewById<ImageButton>(R.id.listBack).setOnClickListener { closeList() }
|
||
findViewById<Button>(R.id.queueButton).setOnClickListener { openList(ListMode.QUEUE) }
|
||
findViewById<Button>(R.id.playlistsButton).setOnClickListener { openList(ListMode.PLAYLISTS) }
|
||
sleepButton = findViewById(R.id.sleepButton)
|
||
sleepButton.setOnClickListener { showPcSleepDialog() }
|
||
findViewById<Button>(R.id.historyButton).setOnClickListener { showPcHistory() }
|
||
|
||
findViewById<ImageButton>(R.id.previousButton).setOnClickListener { PcSession.send("previous") }
|
||
findViewById<ImageButton>(R.id.nextButton).setOnClickListener { PcSession.send("next") }
|
||
findViewById<ImageButton>(R.id.shuffleButton).setOnClickListener { PcSession.send("shuffle") }
|
||
repeat.setOnClickListener { PcSession.send("repeat") }
|
||
playPause.setOnClickListener {
|
||
PcSession.send("play_pause") // der naechste Status (1 s) bestaetigt; die Taste schaltet sofort um
|
||
renderPlayPause(!PcSession.state.playing)
|
||
}
|
||
like.setOnClickListener { PcSession.send("like") }
|
||
tabYoutube.setOnClickListener { PcSession.send("switch_tab", target = "youtube") }
|
||
tabMusic.setOnClickListener { PcSession.send("switch_tab", target = "music") }
|
||
|
||
positionBar.setOnSeekBarChangeListener(object : SeekBarListener() {
|
||
override fun onStartTrackingTouch(bar: SeekBar) {
|
||
draggingPosition = true
|
||
}
|
||
|
||
override fun onProgressChanged(bar: SeekBar, progress: Int, fromUser: Boolean) {
|
||
if (fromUser) positionText.text = PcRemote.formatTime(progress.toDouble())
|
||
}
|
||
|
||
override fun onStopTrackingTouch(bar: SeekBar) {
|
||
draggingPosition = false
|
||
// Der PC spult relativ ("seek" = Sekunden vor/zurueck).
|
||
val delta = (bar.progress - PcSession.state.position).coerceIn(-3600.0, 3600.0)
|
||
PcSession.send("seek", value = delta)
|
||
}
|
||
})
|
||
volumeBar.setOnSeekBarChangeListener(object : SeekBarListener() {
|
||
override fun onStartTrackingTouch(bar: SeekBar) {
|
||
draggingVolume = true
|
||
}
|
||
|
||
override fun onStopTrackingTouch(bar: SeekBar) {
|
||
draggingVolume = false
|
||
PcSession.send("set_volume", value = bar.progress.toDouble())
|
||
}
|
||
})
|
||
|
||
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
|
||
override fun handleOnBackPressed() {
|
||
when {
|
||
listMode != null -> closeList()
|
||
PcSession.isActive && devicePanel.visibility == View.VISIBLE -> showPlayer()
|
||
else -> {
|
||
isEnabled = false
|
||
onBackPressedDispatcher.onBackPressed()
|
||
}
|
||
}
|
||
}
|
||
})
|
||
|
||
if (Build.VERSION.SDK_INT >= 33 &&
|
||
ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED
|
||
) {
|
||
notificationPermission.launch(Manifest.permission.POST_NOTIFICATIONS)
|
||
}
|
||
|
||
if (PcSession.isActive) {
|
||
lastPhase = PcSession.phase
|
||
showPlayer()
|
||
} else {
|
||
showDevices()
|
||
}
|
||
}
|
||
|
||
override fun onStart() {
|
||
super.onStart()
|
||
PcSession.addListener(this)
|
||
onUpdate()
|
||
}
|
||
|
||
override fun onStop() {
|
||
PcSession.removeListener(this)
|
||
super.onStop()
|
||
}
|
||
|
||
override fun onDestroy() {
|
||
main.removeCallbacksAndMessages(null)
|
||
gradientAnimator?.cancel()
|
||
super.onDestroy()
|
||
}
|
||
|
||
private fun keepContentBetweenSystemBars() {
|
||
val root = findViewById<View>(R.id.remoteRoot)
|
||
ViewCompat.setOnApplyWindowInsetsListener(root) { view, insets ->
|
||
val bars = insets.getInsets(WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.ime())
|
||
view.setPadding(bars.left, bars.top, bars.right, bars.bottom)
|
||
WindowInsetsCompat.CONSUMED
|
||
}
|
||
}
|
||
|
||
/** Quadratisches Cover mit runden Ecken, so gross wie der freie Platz erlaubt. */
|
||
private fun setupRoundCover() {
|
||
val corner = 12 * resources.displayMetrics.density
|
||
cover.clipToOutline = true
|
||
cover.outlineProvider = object : ViewOutlineProvider() {
|
||
override fun getOutline(view: View, outline: Outline) {
|
||
outline.setRoundRect(0, 0, view.width, view.height, corner)
|
||
}
|
||
}
|
||
findViewById<View>(R.id.coverBox).addOnLayoutChangeListener { box, left, top, right, bottom, _, _, _, _ ->
|
||
val side = minOf(right - left, bottom - top).coerceAtLeast(0)
|
||
if (cover.layoutParams.width != side || cover.layoutParams.height != side) {
|
||
cover.layoutParams = cover.layoutParams.apply {
|
||
width = side
|
||
height = side
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------------ Bereiche umschalten
|
||
|
||
private fun showPlayer() {
|
||
devicePanel.visibility = View.GONE
|
||
playerPanel.visibility = View.VISIBLE
|
||
render()
|
||
}
|
||
|
||
private fun showDevices() {
|
||
closeList()
|
||
val connected = PcSession.isActive
|
||
playerPanel.visibility = View.GONE
|
||
devicePanel.visibility = View.VISIBLE
|
||
findViewById<View>(R.id.deviceBack).visibility = if (connected) View.VISIBLE else View.GONE
|
||
findViewById<View>(R.id.disconnectButton).visibility = if (connected) View.VISIBLE else View.GONE
|
||
applyGradient(BACKGROUND)
|
||
search()
|
||
}
|
||
|
||
// ------------------------------------------------------------------ PC-Sitzung (Listener)
|
||
|
||
override fun onUpdate() {
|
||
val phase = PcSession.phase
|
||
val previous = lastPhase
|
||
lastPhase = phase
|
||
when (phase) {
|
||
PcSession.Phase.IDLE -> {
|
||
if (previous != PcSession.Phase.IDLE) showDevices()
|
||
}
|
||
PcSession.Phase.CONNECTING -> status.text = getString(R.string.pc_connecting, PcSession.device?.name.orEmpty())
|
||
PcSession.Phase.CONNECTED, PcSession.Phase.RECONNECTING -> {
|
||
if (previous == PcSession.Phase.CONNECTING) showPlayer()
|
||
if (playerPanel.visibility == View.VISIBLE) render()
|
||
}
|
||
}
|
||
}
|
||
|
||
override fun onProblem(problem: PcSession.Problem, message: String) {
|
||
when (problem) {
|
||
PcSession.Problem.PAIRING_REQUIRED -> pendingTarget?.let(::askForCode)
|
||
PcSession.Problem.FAILED -> {
|
||
note = getString(R.string.pc_error, message)
|
||
status.text = note
|
||
if (playerPanel.visibility == View.VISIBLE) showDevices()
|
||
}
|
||
PcSession.Problem.LOST -> {
|
||
note = getString(R.string.pc_lost, message)
|
||
status.text = note
|
||
showDevices()
|
||
}
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------------ PCs finden
|
||
|
||
private fun search() {
|
||
if (note == null) status.setText(R.string.pc_searching) else status.text = note
|
||
Thread {
|
||
val found = PcRemote.discover()
|
||
main.post {
|
||
if (isFinishing || isDestroyed) return@post
|
||
devices.clear()
|
||
devices.addAll(found)
|
||
val connectedHost = PcSession.device?.takeIf { PcSession.isActive }?.host
|
||
deviceAdapter.setRows(
|
||
found.map {
|
||
Row(
|
||
title = it.name,
|
||
subtitle = if (it.host == connectedHost) getString(R.string.pc_this_pc) else it.host,
|
||
iconRes = R.drawable.ic_computer,
|
||
highlighted = it.host == connectedHost,
|
||
)
|
||
},
|
||
)
|
||
if (PcSession.phase != PcSession.Phase.CONNECTING) {
|
||
note?.let { status.text = it } ?: status.setText(if (found.isEmpty()) R.string.pc_none_found else R.string.pc_found)
|
||
}
|
||
}
|
||
}.start()
|
||
}
|
||
|
||
private fun askForAddress() {
|
||
val input = EditText(this).apply {
|
||
hint = getString(R.string.pc_manual_hint)
|
||
inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI
|
||
setText(PcSession.prefs(this@PcRemoteActivity).getString(PcSession.KEY_LAST_HOST, ""))
|
||
}
|
||
AlertDialog.Builder(this)
|
||
.setTitle(R.string.pc_manual)
|
||
.setView(padded(input))
|
||
.setPositiveButton(R.string.pc_connect) { _, _ ->
|
||
val host = input.text.toString().trim()
|
||
if (host.isNotEmpty()) {
|
||
val name = PcSession.prefs(this).getString(PcSession.KEY_NAME_FOR + host, null) ?: host
|
||
connectTo(PcDevice(name, host))
|
||
}
|
||
}
|
||
.setNegativeButton(R.string.pc_cancel, null)
|
||
.show()
|
||
}
|
||
|
||
// ------------------------------------------------------------------ Verbinden / Koppeln
|
||
|
||
private fun connectTo(target: PcDevice) {
|
||
note = null
|
||
pendingTarget = target
|
||
val token = PcSession.prefs(this).getString(PcSession.KEY_TOKEN_FOR + target.name, null)
|
||
if (token == null) {
|
||
askForCode(target)
|
||
return
|
||
}
|
||
PcSession.connect(this, target, token, null)
|
||
}
|
||
|
||
private fun askForCode(target: PcDevice) {
|
||
val input = EditText(this).apply {
|
||
hint = getString(R.string.pc_pair_hint)
|
||
inputType = InputType.TYPE_CLASS_NUMBER
|
||
filters = arrayOf(InputFilter.LengthFilter(6))
|
||
}
|
||
AlertDialog.Builder(this)
|
||
.setTitle(getString(R.string.pc_pair_title, target.name))
|
||
.setMessage(R.string.pc_pair_message)
|
||
.setView(padded(input))
|
||
.setPositiveButton(R.string.pc_pair) { _, _ ->
|
||
PcSession.connect(this, target, null, input.text.toString().trim())
|
||
}
|
||
.setNegativeButton(R.string.pc_cancel, null)
|
||
.show()
|
||
}
|
||
|
||
// ------------------------------------------------------------------ Anzeige
|
||
|
||
private fun render() {
|
||
val state = PcSession.state
|
||
deviceName.text = PcSession.device?.name.orEmpty()
|
||
trackTitle.text = state.title.ifBlank { getString(R.string.pc_nothing_playing) }
|
||
trackSubtitle.text = if (PcSession.phase == PcSession.Phase.RECONNECTING) getString(R.string.pc_reconnecting) else state.subtitle
|
||
renderPlayPause(state.playing)
|
||
|
||
val duration = state.duration.toInt().coerceAtLeast(0)
|
||
positionBar.max = duration
|
||
positionBar.isEnabled = duration > 0
|
||
durationText.text = PcRemote.formatTime(state.duration)
|
||
if (!draggingPosition) {
|
||
positionBar.progress = state.position.toInt().coerceIn(0, duration)
|
||
positionText.text = PcRemote.formatTime(state.position)
|
||
}
|
||
if (!draggingVolume) volumeBar.progress = state.volume
|
||
|
||
like.setImageResource(if (state.liked) R.drawable.ic_favorite else R.drawable.ic_favorite_border)
|
||
like.imageTintList = tint(if (state.liked) R.color.brand_to else R.color.text)
|
||
repeat.setImageResource(if (state.repeatMode == "ONE") R.drawable.ic_repeat_one else R.drawable.ic_repeat)
|
||
repeat.imageTintList = tint(if (state.repeatMode == "ALL" || state.repeatMode == "ONE") R.color.brand_to else R.color.text_muted)
|
||
findViewById<ImageButton>(R.id.shuffleButton).imageTintList = tint(R.color.text_muted)
|
||
tabYoutube.alpha = if (state.visibleTab == "youtube") 1f else 0.45f
|
||
tabMusic.alpha = if (state.visibleTab == "music") 1f else 0.45f
|
||
renderSleep(state.sleepTimer)
|
||
|
||
if (state.thumbnail != coverUrl) loadCover(state.thumbnail)
|
||
}
|
||
|
||
private fun renderPlayPause(playing: Boolean) {
|
||
playPause.setImageResource(if (playing) R.drawable.ic_pause else R.drawable.ic_play)
|
||
playPause.contentDescription = getString(if (playing) R.string.action_pause else R.string.action_play)
|
||
}
|
||
|
||
private fun tint(colorRes: Int) = android.content.res.ColorStateList.valueOf(ContextCompat.getColor(this, colorRes))
|
||
|
||
private fun loadCover(url: String) {
|
||
coverUrl = url
|
||
if (url.isEmpty()) {
|
||
cover.setImageDrawable(null)
|
||
applyGradient(BACKGROUND)
|
||
return
|
||
}
|
||
ImageCache.load(url, 544) { bitmap ->
|
||
if (coverUrl != url || isDestroyed) return@load
|
||
cover.setImageBitmap(bitmap)
|
||
if (bitmap != null) {
|
||
Palette.from(bitmap).maximumColorCount(12).generate { palette ->
|
||
if (coverUrl != url || palette == null || isDestroyed) return@generate
|
||
val base = palette.getDarkMutedColor(palette.getMutedColor(palette.getDominantColor(BACKGROUND)))
|
||
animateGradient(ColorUtils.blendARGB(base, BACKGROUND, 0.2f))
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
private fun animateGradient(target: Int) {
|
||
gradientAnimator?.cancel()
|
||
gradientAnimator = ValueAnimator.ofArgb(gradientColor, target).apply {
|
||
duration = 500
|
||
addUpdateListener { applyGradient(it.animatedValue as Int) }
|
||
start()
|
||
}
|
||
}
|
||
|
||
private fun applyGradient(color: Int) {
|
||
gradientColor = color
|
||
gradient.background = GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, intArrayOf(color, BACKGROUND, BACKGROUND))
|
||
}
|
||
|
||
// ------------------------------------------------------------------ Warteschlange / Playlists
|
||
|
||
private fun openList(mode: ListMode) {
|
||
listMode = mode
|
||
listPanel.visibility = View.VISIBLE
|
||
listTitle.setText(if (mode == ListMode.QUEUE) R.string.pc_queue else R.string.pc_playlists)
|
||
itemAdapter.setRows(emptyList())
|
||
showListMessage(getString(R.string.pc_loading))
|
||
loadList(mode, scrollToCurrent = true)
|
||
}
|
||
|
||
// ------------------------------------------------------------------ Schlaf-Timer und Verlauf am PC
|
||
|
||
private lateinit var sleepButton: Button
|
||
|
||
private fun renderSleep(seconds: Long?) {
|
||
sleepButton.text = when (seconds) {
|
||
null -> getString(R.string.pc_sleep)
|
||
-1L -> getString(R.string.sleep_end_short)
|
||
else -> SleepTimer.format(seconds)
|
||
}
|
||
sleepButton.compoundDrawableTintList = tint(if (seconds != null) R.color.brand_to else R.color.text)
|
||
}
|
||
|
||
private fun showPcSleepDialog() {
|
||
val minutes = SleepTimer.CHOICES
|
||
val labels = minutes.map { getString(R.string.sleep_minutes, it) } +
|
||
getString(R.string.sleep_end) + getString(R.string.sleep_off)
|
||
AlertDialog.Builder(this)
|
||
.setTitle(R.string.sleep_title)
|
||
.setItems(labels.toTypedArray()) { _, which ->
|
||
val value = when {
|
||
which < minutes.size -> minutes[which]
|
||
which == minutes.size -> -1
|
||
else -> 0
|
||
}
|
||
PcSession.request("sleep_timer", { put("value", value) }) { result ->
|
||
result.onFailure { error ->
|
||
val text = if (PcRemote.isUnknownCommand(error.message)) getString(R.string.pc_too_old)
|
||
else error.message ?: error.javaClass.simpleName
|
||
android.widget.Toast.makeText(this, text, android.widget.Toast.LENGTH_LONG).show()
|
||
}
|
||
}
|
||
}
|
||
.show()
|
||
}
|
||
|
||
private fun showPcHistory() {
|
||
PcSession.request("history", { put("value", 200) }) { result ->
|
||
if (isDestroyed) return@request
|
||
result.onSuccess { reply ->
|
||
HistoryDialog.show(this, getString(R.string.history_pc_title), PlayHistory.parsePcHistory(reply), onPick = { entry ->
|
||
PcSession.request("play_video", { put("video", entry.videoId) })
|
||
})
|
||
}.onFailure { error ->
|
||
val text = if (PcRemote.isUnknownCommand(error.message)) getString(R.string.pc_too_old)
|
||
else error.message ?: error.javaClass.simpleName
|
||
android.widget.Toast.makeText(this, text, android.widget.Toast.LENGTH_LONG).show()
|
||
}
|
||
}
|
||
}
|
||
|
||
private fun closeList() {
|
||
listMode = null
|
||
listPanel.visibility = View.GONE
|
||
}
|
||
|
||
private fun loadList(mode: ListMode, scrollToCurrent: Boolean) {
|
||
val command = if (mode == ListMode.QUEUE) "queue" else "list_playlists"
|
||
PcSession.request(command, { if (mode == ListMode.QUEUE) put("target", PcSession.state.activeTab) }) { result ->
|
||
if (listMode != mode || isDestroyed) return@request
|
||
result.onSuccess { reply ->
|
||
if (mode == ListMode.QUEUE) {
|
||
queueItems = PcRemote.parseQueue(reply)
|
||
itemAdapter.setRows(
|
||
queueItems.map {
|
||
Row(it.title.ifBlank { "–" }, it.subtitle, it.thumbnail, R.drawable.ic_queue_music, it.current)
|
||
},
|
||
)
|
||
showListMessage(if (queueItems.isEmpty()) getString(R.string.pc_queue_empty) else null)
|
||
if (scrollToCurrent) queueItems.indexOfFirst { it.current }.takeIf { it > 0 }?.let { itemList.setSelection(it) }
|
||
} else {
|
||
playlistItems = PcRemote.parsePlaylists(reply)
|
||
itemAdapter.setRows(playlistItems.map { Row(it.title, "", "", R.drawable.ic_library_music, false) })
|
||
showListMessage(if (playlistItems.isEmpty()) getString(R.string.pc_playlists_empty) else null)
|
||
}
|
||
}.onFailure { error ->
|
||
val text = if (PcRemote.isUnknownCommand(error.message)) {
|
||
getString(R.string.pc_update_pc)
|
||
} else {
|
||
getString(R.string.pc_list_error, error.message ?: error.javaClass.simpleName)
|
||
}
|
||
showListMessage(text)
|
||
}
|
||
}
|
||
}
|
||
|
||
private fun showListMessage(text: String?) {
|
||
listMessage.text = text.orEmpty()
|
||
listMessage.visibility = if (text == null) View.GONE else View.VISIBLE
|
||
}
|
||
|
||
private fun onListItemClicked(position: Int) {
|
||
when (listMode) {
|
||
ListMode.QUEUE -> {
|
||
if (position !in queueItems.indices) return
|
||
PcSession.send("play_queue_item", target = PcSession.state.activeTab, value = position.toDouble())
|
||
// Sofort markieren; kurz darauf ist die Liste vom PC neu geladen.
|
||
itemAdapter.setHighlight(position)
|
||
main.postDelayed({ if (listMode == ListMode.QUEUE) loadList(ListMode.QUEUE, scrollToCurrent = false) }, 1500)
|
||
}
|
||
ListMode.PLAYLISTS -> {
|
||
val playlist = playlistItems.getOrNull(position) ?: return
|
||
PcSession.request("play_playlist", { put("playlist", playlist.id) })
|
||
closeList()
|
||
}
|
||
null -> {}
|
||
}
|
||
}
|
||
|
||
// ------------------------------------------------------------------ Hilfen
|
||
|
||
private fun padded(view: View): View =
|
||
LinearLayout(this).apply {
|
||
val pad = (20 * resources.displayMetrics.density).toInt()
|
||
setPadding(pad, pad / 2, pad, 0)
|
||
addView(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)
|
||
}
|
||
|
||
/** SeekBar-Listener mit leeren Standardmethoden. */
|
||
private open class SeekBarListener : SeekBar.OnSeekBarChangeListener {
|
||
override fun onProgressChanged(bar: SeekBar, progress: Int, fromUser: Boolean) {}
|
||
override fun onStartTrackingTouch(bar: SeekBar) {}
|
||
override fun onStopTrackingTouch(bar: SeekBar) {}
|
||
}
|
||
|
||
/** Eine Zeile in Geraete-, Warteschlangen- und Playlist-Listen. */
|
||
private data class Row(
|
||
val title: String,
|
||
val subtitle: String,
|
||
val imageUrl: String = "",
|
||
val iconRes: Int = 0,
|
||
val highlighted: Boolean = false,
|
||
)
|
||
|
||
private class RowAdapter(private val context: Context) : BaseAdapter() {
|
||
private var rows = listOf<Row>()
|
||
private val pink = ContextCompat.getColor(context, R.color.brand_to)
|
||
private val white = ContextCompat.getColor(context, R.color.text)
|
||
private val density = context.resources.displayMetrics.density
|
||
|
||
fun setRows(new: List<Row>) {
|
||
rows = new
|
||
notifyDataSetChanged()
|
||
}
|
||
|
||
fun setHighlight(position: Int) {
|
||
rows = rows.mapIndexed { i, row -> row.copy(highlighted = i == position) }
|
||
notifyDataSetChanged()
|
||
}
|
||
|
||
override fun getCount() = rows.size
|
||
override fun getItem(position: Int) = rows[position]
|
||
override fun getItemId(position: Int) = position.toLong()
|
||
|
||
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
|
||
val view = convertView ?: LayoutInflater.from(context).inflate(R.layout.item_row, parent, false)
|
||
val row = rows[position]
|
||
val title = view.findViewById<TextView>(R.id.rowTitle)
|
||
val subtitle = view.findViewById<TextView>(R.id.rowSubtitle)
|
||
val image = view.findViewById<ImageView>(R.id.rowImage)
|
||
title.text = row.title
|
||
title.setTextColor(if (row.highlighted) pink else white)
|
||
subtitle.text = row.subtitle
|
||
subtitle.visibility = if (row.subtitle.isEmpty()) View.GONE else View.VISIBLE
|
||
|
||
image.tag = row.imageUrl
|
||
image.scaleType = ImageView.ScaleType.CENTER
|
||
image.setImageResource(row.iconRes)
|
||
image.imageTintList = android.content.res.ColorStateList.valueOf(ContextCompat.getColor(context, R.color.text_muted))
|
||
if (row.imageUrl.isNotEmpty()) {
|
||
ImageCache.load(row.imageUrl, (48 * density).toInt()) { bitmap ->
|
||
if (bitmap != null && image.tag == row.imageUrl) {
|
||
image.imageTintList = null
|
||
image.scaleType = ImageView.ScaleType.CENTER_CROP
|
||
image.setImageBitmap(bitmap)
|
||
}
|
||
}
|
||
}
|
||
return view
|
||
}
|
||
}
|
||
|
||
companion object {
|
||
private val BACKGROUND = Color.parseColor("#121212")
|
||
|
||
fun start(context: Context) {
|
||
context.startActivity(Intent(context, PcRemoteActivity::class.java))
|
||
}
|
||
}
|
||
}
|