Skip to content

Commit

Permalink
Various cleanups
Browse files Browse the repository at this point in the history
  • Loading branch information
mathiascode committed Mar 23, 2024
1 parent 8a82332 commit 2dba320
Show file tree
Hide file tree
Showing 7 changed files with 65 additions and 65 deletions.
6 changes: 3 additions & 3 deletions app/src/main/kotlin/org/cuberite/android/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,10 @@ class MainActivity : AppCompatActivity(), NavigationBarView.OnItemSelectedListen
private val requestPermissionLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) { isGranted: Boolean ->
if (isGranted) {
Log.i(LOG, "Got permissions, using public directory")
MainApplication.preferences.edit().putString("cuberiteLocation", "$MainApplication.publicDir/cuberite-server").apply()
MainApplication.preferences.edit().putString("cuberiteLocation", "${MainApplication.publicDir}/cuberite-server").apply()
} else {
Log.i(LOG, "Permissions denied, boo, using private directory")
MainApplication.preferences.edit().putString("cuberiteLocation", "$MainApplication.privateDir/cuberite-server").apply()
MainApplication.preferences.edit().putString("cuberiteLocation", "${MainApplication.privateDir}/cuberite-server").apply()
}
}

Expand Down Expand Up @@ -105,7 +105,7 @@ class MainActivity : AppCompatActivity(), NavigationBarView.OnItemSelectedListen
}
} else if (location!!.isEmpty() || location.startsWith(MainApplication.privateDir)) {
val editor = MainApplication.preferences.edit()
editor.putString("cuberiteLocation", "$MainApplication.publicDir/cuberite-server")
editor.putString("cuberiteLocation", "${MainApplication.publicDir}/cuberite-server")
editor.apply()
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ class ConsoleFragment : Fragment() {
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
CuberiteService.updateLogLiveData.observe(viewLifecycleOwner) { result ->
if (result == null) {
return@observe
Expand All @@ -40,7 +41,7 @@ class ConsoleFragment : Fragment() {
inputLine = view.findViewById(R.id.inputLine)
inputLine.setOnEditorActionListener { _: TextView?, actionId: Int, _: KeyEvent? ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
val command = inputLine.getText().toString()
val command = inputLine.text.toString()
sendExecuteCommand(command)
inputLine.setText("")
// return true makes sure the keyboard doesn't close
Expand All @@ -50,7 +51,7 @@ class ConsoleFragment : Fragment() {
}
val textInputLayout = view.findViewById<TextInputLayout>(R.id.inputWrapper)
textInputLayout.setEndIconOnClickListener {
val command = inputLine.getText().toString()
val command = inputLine.text.toString()
sendExecuteCommand(command)
inputLine.setText("")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ class ControlFragment : Fragment() {
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
CuberiteService.endedLiveData.observe(viewLifecycleOwner) { ended ->
if (!ended) {
return@observe
Expand Down Expand Up @@ -68,7 +69,7 @@ class ControlFragment : Fragment() {
Log.d(LOG, "Changing color from " + Integer.toHexString(colorFrom) + " to " + Integer.toHexString(colorTo))
val colorAnimation = ValueAnimator.ofObject(ArgbEvaluator(), colorFrom, colorTo)
colorAnimation.setDuration(300)
colorAnimation.addUpdateListener { animator: ValueAnimator -> button.setBackgroundColor(animator.getAnimatedValue() as Int) }
colorAnimation.addUpdateListener { animator: ValueAnimator -> button.setBackgroundColor(animator.animatedValue as Int) }
colorAnimation.start()
mainButtonColor = colorTo
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,11 +146,9 @@ class SettingsFragment : PreferenceFragmentCompat() {
val url = getWebadminUrl(webadminFile)
if (url != null) {
val webadminDescription = findPreference<Preference>("webadminDescription")
webadminDescription!!.setSummary("""
${webadminDescription.getSummary().toString()}
webadminDescription!!.setSummary("""${webadminDescription.summary}
URL: $url
""".trimIndent())
URL: $url""")
}
val webadminOpen = findPreference<Preference>("webadminOpen")
webadminOpen!!.onPreferenceClickListener = Preference.OnPreferenceClickListener {
Expand Down Expand Up @@ -237,14 +235,14 @@ class SettingsFragment : PreferenceFragmentCompat() {
}
val oldUsername = username
val layout = View.inflate(requireContext(), R.layout.dialog_webadmin_credentials, null)
(layout.findViewById<View>(R.id.webadminUsername) as EditText).setText(username)
(layout.findViewById<View>(R.id.webadminPassword) as EditText).setText(password)
layout.findViewById<EditText>(R.id.webadminUsername).setText(username)
layout.findViewById<EditText>(R.id.webadminPassword).setText(password)
val dialog = MaterialAlertDialogBuilder(requireContext())
.setView(layout)
.setTitle(R.string.settings_webadmin_login)
.setPositiveButton(R.string.ok) { _: DialogInterface?, _: Int ->
val newUsername = (layout.findViewById<View>(R.id.webadminUsername) as EditText).getText().toString()
val newPassword = (layout.findViewById<View>(R.id.webadminPassword) as EditText).getText().toString()
val newUsername = layout.findViewById<EditText>(R.id.webadminUsername).text.toString()
val newPassword = layout.findViewById<EditText>(R.id.webadminPassword).text.toString()
ini.remove("User:$oldUsername")
ini.put("User:$newUsername", "Password", newPassword)
try {
Expand Down Expand Up @@ -280,11 +278,9 @@ class SettingsFragment : PreferenceFragmentCompat() {
}
val abi = String.format(getString(R.string.settings_install_manually_abi), CuberiteService.preferredABI)
val setABIText = findPreference<Preference>("abiText")
setABIText!!.setSummary("""
${setABIText.getSummary().toString()}
$abi
""".trimIndent())
setABIText!!.setSummary("""${setABIText.summary}
$abi""")
val installBinary = findPreference<Preference>("installBinary")
installBinary!!.onPreferenceClickListener = Preference.OnPreferenceClickListener {
pickFile(pickFileBinaryLauncher)
Expand Down Expand Up @@ -328,11 +324,9 @@ Download URL: ${InstallService.DOWNLOAD_HOST}"""
val thirdPartyLicenses = findPreference<Preference>("thirdPartyLicenses")
thirdPartyLicenses!!.onPreferenceClickListener = Preference.OnPreferenceClickListener {
val title = getString(R.string.settings_info_libraries)
val message = """
${getString(R.string.ini4j_license)}
${getString(R.string.ini4j_license_description)}
""".trimIndent()
val message = """${getString(R.string.ini4j_license)}
${getString(R.string.ini4j_license_description)}"""
showInfoPopup(title, message)
true
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,14 @@ import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.progressindicator.LinearProgressIndicator
import org.cuberite.android.R

class ProgressReceiver(private val cont: Context, handler: Handler?) : ResultReceiver(handler) {
class ProgressReceiver(private val context: Context, handler: Handler?) : ResultReceiver(handler) {
private var progressDialog: AlertDialog? = null
private lateinit var progressBar: LinearProgressIndicator

private fun createDialog(title: String?) {
val layout = View.inflate(cont, R.layout.dialog_progress, null)
progressBar = layout.findViewById<View>(R.id.progressBar) as LinearProgressIndicator
progressDialog = MaterialAlertDialogBuilder(cont)
val layout = View.inflate(context, R.layout.dialog_progress, null)
progressBar = layout.findViewById(R.id.progressBar)
progressDialog = MaterialAlertDialogBuilder(context)
.setTitle(title)
.setView(layout)
.setCancelable(false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import android.net.NetworkInfo
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.Log
import androidx.core.app.NotificationCompat
import androidx.lifecycle.MutableLiveData
Expand Down Expand Up @@ -62,7 +61,7 @@ class CuberiteService : IntentService("CuberiteService") {
// Clear previous output
consoleOutput = StringBuilder()
consoleOutput.append("Info: Cuberite is starting...").append("\n")
Handler(Looper.getMainLooper()).post { updateLogLiveData.postValue(consoleOutput) }
updateLogLiveData.postValue(consoleOutput)

// Make sure we can execute the binary
File(filesDir, EXECUTABLE_NAME).setExecutable(true, true)
Expand All @@ -84,7 +83,7 @@ class CuberiteService : IntentService("CuberiteService") {
while (processScanner.nextLine().also { line = it } != null) {
Log.i(LOG, line!!)
consoleOutput.append(line).append("\n")
Handler(Looper.getMainLooper()).post { updateLogLiveData.postValue(consoleOutput) }
updateLogLiveData.postValue(consoleOutput)
}
} catch (e: NoSuchElementException) {
// Do nothing. Workaround for issues in older Android versions.
Expand Down Expand Up @@ -144,7 +143,7 @@ class CuberiteService : IntentService("CuberiteService") {
process.destroy()
MainActivity.killCuberiteLiveData.postValue(false)
}
Handler(Looper.getMainLooper()).post {
Handler(applicationContext.mainLooper).post {
MainActivity.executeCommandLiveData.observeForever(executeObserver)
MainActivity.killCuberiteLiveData.observeForever(killObserver)
}
Expand All @@ -156,14 +155,12 @@ class CuberiteService : IntentService("CuberiteService") {
// Logic waits here until Cuberite has stopped. Everything after that is cleanup for the next run
val logTimeEnd = System.currentTimeMillis()
if (logTimeEnd - logTimeStart < 100) {
Handler(Looper.getMainLooper()).post {
startupErrorLiveData.postValue(true)
}
startupErrorLiveData.postValue(true)
}

// Shutdown
unregisterReceiver(updateIp)
Handler(Looper.getMainLooper()).post {
Handler(applicationContext.mainLooper).post {
MainActivity.executeCommandLiveData.removeObserver(executeObserver)
MainActivity.killCuberiteLiveData.removeObserver(killObserver)
}
Expand All @@ -172,10 +169,11 @@ class CuberiteService : IntentService("CuberiteService") {
Log.e(LOG, "An error occurred when starting Cuberite", e)

// Send error to user
Handler(Looper.getMainLooper()).post { startupErrorLiveData.postValue(true) }
startupErrorLiveData.postValue(true)
}
stopSelf()
Handler(Looper.getMainLooper()).post { endedLiveData.postValue(true) }
isRunning = false
endedLiveData.postValue(true)
}

@Deprecated("Deprecated in Java")
Expand Down
60 changes: 33 additions & 27 deletions app/src/main/kotlin/org/cuberite/android/services/InstallService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.PowerManager
import android.os.PowerManager.WakeLock
import android.os.ResultReceiver
Expand Down Expand Up @@ -48,7 +47,7 @@ class InstallService : IntentService("InstallService") {
private fun acquireWakelock(): WakeLock {
Log.d(LOG, "Acquiring wakeLock")
val pm = getSystemService(POWER_SERVICE) as PowerManager
val wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, javaClass.getName())
val wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, this::class.simpleName)
wakeLock.acquire(300000) // 5 min timeout
return wakeLock
}
Expand Down Expand Up @@ -131,14 +130,14 @@ class InstallService : IntentService("InstallService") {
try {
connection.setConnectTimeout(10000) // 10 secs
connection.connect()
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
val error = "Server returned HTTP " + connection.getResponseCode() + " " + connection.getResponseMessage()
if (connection.responseCode != HttpURLConnection.HTTP_OK) {
val error = "Server returned HTTP " + connection.responseCode + " " + connection.responseMessage
Log.e(LOG, error)
result = error
} else {
inputStream = connection.inputStream
outputStream = FileOutputStream(targetLocation)
val length = connection.getContentLength()
val length = connection.contentLength
val data = ByteArray(4096)
var total: Long = 0
var count: Int
Expand Down Expand Up @@ -204,7 +203,7 @@ class InstallService : IntentService("InstallService") {
val inputStream = contentResolver.openInputStream(fileUri!!)
val zipInputStream = ZipInputStream(inputStream)
var zipEntry: ZipEntry
while (zipInputStream.getNextEntry().also { zipEntry = it } != null) {
while (zipInputStream.nextEntry.also { zipEntry = it } != null) {
if (zipEntry.isDirectory) {
File(targetLocation, zipEntry.name).mkdir()
} else {
Expand Down Expand Up @@ -242,20 +241,29 @@ class InstallService : IntentService("InstallService") {
result = getString(R.string.status_update_binary_error)
} else if ("unzip" == intent.action) {
val uri = intent.parcelable("uri") as Uri?
val targetFolder = File(
if (state == State.PICK_FILE_BINARY) MainApplication.privateDir else intent.getStringExtra("targetFolder")!!
)
val filePath = if (state == State.PICK_FILE_BINARY) {
MainApplication.privateDir
} else {
MainApplication.preferences.getString("cuberiteLocation", "")!!
}
val targetFolder = File(filePath)
receiver = intent.parcelable("receiver")
result = unzip(uri, targetFolder)
} else {
val downloadHost = intent.getStringExtra("downloadHost")
val abi = CuberiteService.preferredABI
val targetFileName = (if (state == State.NEED_DOWNLOAD_BINARY || state == State.NEED_DOWNLOAD_BOTH) abi else "server") + ".zip"
val downloadUrl = downloadHost + targetFileName
val targetFileName = if (state == State.NEED_DOWNLOAD_BINARY || state == State.NEED_DOWNLOAD_BOTH) {
"$abi.zip"
} else {
"server.zip"
}
val downloadUrl = DOWNLOAD_HOST + targetFileName
val tempZip = File(cacheDir, targetFileName) // Zip files are temporary
val targetFolder = File(
if (state == State.NEED_DOWNLOAD_BINARY || state == State.NEED_DOWNLOAD_BOTH) MainApplication.privateDir else intent.getStringExtra("targetFolder")!!
)
val filePath = if (state == State.NEED_DOWNLOAD_BINARY || state == State.NEED_DOWNLOAD_BOTH) {
MainApplication.privateDir
} else {
MainApplication.preferences.getString("cuberiteLocation", "")!!
}
val targetFolder = File(filePath)
receiver = intent.parcelable("receiver")

// Download
Expand All @@ -274,7 +282,7 @@ class InstallService : IntentService("InstallService") {
}
}
stopSelf()
Handler(Looper.getMainLooper()).post { endedLiveData.setValue(result) }
endedLiveData.postValue(result)
}

companion object {
Expand Down Expand Up @@ -309,23 +317,21 @@ class InstallService : IntentService("InstallService") {
fun download(activity: Activity, state: State = this.state) {
val intent = Intent(activity, InstallService::class.java)
.setAction("download")
.putExtra("downloadHost", DOWNLOAD_HOST)
.putExtra("state", state)
.putExtra("targetFolder", MainApplication.preferences.getString("cuberiteLocation", ""))
.putExtra("receiver", ProgressReceiver(activity, Handler(Looper.getMainLooper())))
.putExtra("receiver", ProgressReceiver(activity, Handler(activity.mainLooper)))
activity.startService(intent)
}

fun installLocal(activity: Activity, selectedFileUri: Uri?, state: State = this.state) {
if (selectedFileUri != null) {
val intent = Intent(activity, InstallService::class.java)
.setAction("unzip")
.putExtra("uri", selectedFileUri)
.putExtra("state", state)
.putExtra("targetFolder", MainApplication.preferences.getString("cuberiteLocation", ""))
.putExtra("receiver", ProgressReceiver(activity, Handler(Looper.getMainLooper())))
activity.startService(intent)
if (selectedFileUri == null) {
return
}
val intent = Intent(activity, InstallService::class.java)
.setAction("unzip")
.putExtra("uri", selectedFileUri)
.putExtra("state", state)
.putExtra("receiver", ProgressReceiver(activity, Handler(activity.mainLooper)))
activity.startService(intent)
}
}
}

0 comments on commit 2dba320

Please sign in to comment.