coroutines: convert the rest

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
This commit is contained in:
Jason A. Donenfeld
2020-09-15 12:30:15 +02:00
parent 2fc0bb1a03
commit bab70ab51e
23 changed files with 571 additions and 534 deletions
@@ -9,6 +9,9 @@ import androidx.databinding.CallbackRegistry
import androidx.databinding.CallbackRegistry.NotifierCallback
import com.wireguard.android.Application
import com.wireguard.android.model.ObservableTunnel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
/**
* Base class for activities that need to remember the currently-selected tunnel.
@@ -35,11 +38,8 @@ abstract class BaseActivity : ThemeChangeAwareActivity() {
intent != null -> intent.getStringExtra(KEY_SELECTED_TUNNEL)
else -> null
}
if (savedTunnelName != null) {
Application.getTunnelManager()
.tunnels
.thenAccept { selectedTunnel = it[savedTunnelName] }
}
if (savedTunnelName != null)
GlobalScope.launch(Dispatchers.Main.immediate) { selectedTunnel = Application.getTunnelManager().getTunnels()[savedTunnelName] }
// The selected tunnel must be set before the superclass method recreates fragments.
super.onCreate(savedInstanceState)
@@ -51,6 +51,7 @@ abstract class BaseActivity : ThemeChangeAwareActivity() {
}
protected abstract fun onSelectedTunnelChanged(oldTunnel: ObservableTunnel?, newTunnel: ObservableTunnel?)
fun removeOnSelectedTunnelChangedListener(
listener: OnSelectedTunnelChangedListener) {
selectionChangeRegistry.remove(listener)
@@ -42,6 +42,7 @@ import com.wireguard.android.widget.EdgeToEdge.setUpScrollingContent
import com.wireguard.crypto.KeyPair
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@@ -67,7 +68,7 @@ class LogViewerActivity : AppCompatActivity() {
private var rawLogLines = StringBuffer()
private var recyclerView: RecyclerView? = null
private var saveButton: MenuItem? = null
private val coroutineScope = CoroutineScope(Dispatchers.Default)
private val logStreamingScope = CoroutineScope(Dispatchers.IO)
private val year by lazy {
val yearFormatter: DateFormat = SimpleDateFormat("yyyy", Locale.US)
yearFormatter.format(Date())
@@ -114,7 +115,7 @@ class LogViewerActivity : AppCompatActivity() {
addItemDecoration(DividerItemDecoration(context, LinearLayoutManager.VERTICAL))
}
coroutineScope.launch { streamingLog() }
logStreamingScope.launch { streamingLog() }
binding.shareFab.setOnClickListener {
revokeLastUri()
@@ -133,6 +134,11 @@ class LogViewerActivity : AppCompatActivity() {
}
}
override fun onDestroy() {
super.onDestroy()
logStreamingScope.cancel()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == SHARE_ACTIVITY_REQUEST) {
revokeLastUri()
@@ -153,27 +159,21 @@ class LogViewerActivity : AppCompatActivity() {
true
}
R.id.save_log -> {
coroutineScope.launch { saveLog() }
GlobalScope.launch { saveLog() }
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onDestroy() {
super.onDestroy()
coroutineScope.cancel()
}
private suspend fun saveLog() {
val context = this
withContext(Dispatchers.Main) {
withContext(Dispatchers.Main.immediate) {
saveButton?.isEnabled = false
withContext(Dispatchers.IO) {
var exception: Throwable? = null
var outputFile: DownloadsFileSaver.DownloadsFile? = null
try {
outputFile = DownloadsFileSaver.save(context, "wireguard-log.txt", "text/plain", true)
outputFile = DownloadsFileSaver.save(this@LogViewerActivity, "wireguard-log.txt", "text/plain", true)
outputFile.outputStream.use {
it.write(rawLogLines.toString().toByteArray(Charsets.UTF_8))
}
@@ -181,7 +181,7 @@ class LogViewerActivity : AppCompatActivity() {
outputFile?.delete()
exception = e
}
withContext(Dispatchers.Main) {
withContext(Dispatchers.Main.immediate) {
saveButton?.isEnabled = true
Snackbar.make(findViewById(android.R.id.content),
if (exception == null) getString(R.string.log_export_success, outputFile?.fileName)
@@ -212,7 +212,7 @@ class LogViewerActivity : AppCompatActivity() {
rawLogLines.append(line)
rawLogLines.append('\n')
val logLine = parseLine(line)
withContext(Dispatchers.Main) {
withContext(Dispatchers.Main.immediate) {
if (logLine != null) {
recyclerView?.let {
val shouldScroll = haveScrolled && !it.canScrollVertically(1)
@@ -348,7 +348,7 @@ class LogViewerActivity : AppCompatActivity() {
return openPipeHelper(uri, "text/plain", null, log) { output, _, _, _, l ->
try {
FileOutputStream(output.fileDescriptor).write(l!!)
} catch (_: Exception) {
} catch (_: Throwable) {
}
}
}
@@ -19,8 +19,8 @@ import com.wireguard.android.R
import com.wireguard.android.backend.WgQuickBackend
import com.wireguard.android.util.AdminKnobs
import com.wireguard.android.util.ModuleLoader
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.ArrayList
@@ -102,8 +102,8 @@ class SettingsActivity : ThemeChangeAwareActivity() {
preferenceManager.findPreference<Preference>("multiple_tunnels")
).filterNotNull()
wgQuickOnlyPrefs.forEach { it.isVisible = false }
Application.getBackendAsync().thenAccept { backend ->
if (backend is WgQuickBackend) {
GlobalScope.launch(Dispatchers.Main.immediate) {
if (Application.getBackend() is WgQuickBackend) {
++preferenceScreen.initialExpandedChildrenCount
wgQuickOnlyPrefs.forEach { it.isVisible = true }
} else {
@@ -121,11 +121,11 @@ class SettingsActivity : ThemeChangeAwareActivity() {
moduleInstaller?.parent?.removePreference(moduleInstaller)
} else {
kernelModuleDisabler?.parent?.removePreference(kernelModuleDisabler)
CoroutineScope(Dispatchers.Main).launch {
GlobalScope.launch(Dispatchers.Main.immediate) {
try {
withContext(Dispatchers.IO) { Application.getRootShell().start() }
moduleInstaller?.isVisible = true
} catch (_: Exception) {
} catch (_: Throwable) {
moduleInstaller?.parent?.removePreference(moduleInstaller)
}
}
@@ -17,27 +17,31 @@ import com.wireguard.android.QuickTileService
import com.wireguard.android.R
import com.wireguard.android.backend.Tunnel
import com.wireguard.android.util.ErrorMessages
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
@RequiresApi(Build.VERSION_CODES.N)
class TunnelToggleActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val tunnel = Application.getTunnelManager().lastUsedTunnel ?: return
tunnel.setStateAsync(Tunnel.State.TOGGLE).whenComplete { _, t ->
TileService.requestListeningState(this, ComponentName(this, QuickTileService::class.java))
onToggleFinished(t)
GlobalScope.launch(Dispatchers.Main.immediate) {
try {
tunnel.setStateAsync(Tunnel.State.TOGGLE)
} catch (e: Throwable) {
TileService.requestListeningState(this@TunnelToggleActivity, ComponentName(this@TunnelToggleActivity, QuickTileService::class.java))
val error = ErrorMessages[e]
val message = getString(R.string.toggle_error, error)
Log.e(TAG, message, e)
Toast.makeText(this@TunnelToggleActivity, message, Toast.LENGTH_LONG).show()
finishAffinity()
return@launch
}
TileService.requestListeningState(this@TunnelToggleActivity, ComponentName(this@TunnelToggleActivity, QuickTileService::class.java))
finishAffinity()
}
}
private fun onToggleFinished(throwable: Throwable?) {
if (throwable == null) return
val error = ErrorMessages[throwable]
val message = getString(R.string.toggle_error, error)
Log.e(TAG, message, throwable)
Toast.makeText(this, message, Toast.LENGTH_LONG).show()
}
companion object {
private const val TAG = "WireGuard/TunnelToggleActivity"
}