Miscellaneous improvements

pull/1264/head
mhmdanas 5 years ago
parent 07db650b5a
commit 96315daa9e

@ -92,12 +92,10 @@ class Tasks : Application(), Configuration.Provider {
appWidgetManager.get().reconfigureWidgets() appWidgetManager.get().reconfigureWidgets()
} }
override fun getWorkManagerConfiguration(): Configuration { override fun getWorkManagerConfiguration(): Configuration = Configuration.Builder()
return Configuration.Builder()
.setWorkerFactory(workerFactory) .setWorkerFactory(workerFactory)
.setMinimumLoggingLevel(if (BuildConfig.DEBUG) Log.DEBUG else Log.INFO) .setMinimumLoggingLevel(if (BuildConfig.DEBUG) Log.DEBUG else Log.INFO)
.build() .build()
}
private class RefreshBroadcastReceiver : BroadcastReceiver() { private class RefreshBroadcastReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) { override fun onReceive(context: Context, intent: Intent) {

@ -41,16 +41,13 @@ class AuthorizationService constructor(
fun getAuthorizationRequestIntent( fun getAuthorizationRequestIntent(
request: AuthorizationRequest, request: AuthorizationRequest,
customTabsIntent: CustomTabsIntent customTabsIntent: CustomTabsIntent
): Intent { ): Intent = authorizationService.getAuthorizationRequestIntent(request, customTabsIntent)
return authorizationService.getAuthorizationRequestIntent(request, customTabsIntent)
}
fun createCustomTabsIntent(uri: Uri, color: Int): CustomTabsIntent { fun createCustomTabsIntent(uri: Uri, color: Int): CustomTabsIntent =
return authorizationService authorizationService
.createCustomTabsIntentBuilder(uri) .createCustomTabsIntentBuilder(uri)
.setToolbarColor(color) .setToolbarColor(color)
.build() .build()
}
fun performRegistrationRequest( fun performRegistrationRequest(
request: RegistrationRequest, request: RegistrationRequest,
@ -59,16 +56,16 @@ class AuthorizationService constructor(
authorizationService.performRegistrationRequest(request, callback) authorizationService.performRegistrationRequest(request, callback)
} }
suspend fun performTokenRequest(request: TokenRequest, clientAuthentication: ClientAuthentication): TokenResponse? { suspend fun performTokenRequest(request: TokenRequest, clientAuthentication: ClientAuthentication): TokenResponse? =
return withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
suspendCoroutine { cont -> suspendCoroutine { cont ->
authorizationService.performTokenRequest(request, clientAuthentication) { response, exception -> authorizationService.performTokenRequest(request, clientAuthentication) { response, exception ->
if (exception != null) { cont.resumeWith(
cont.resumeWith(Result.failure(exception)) if (exception != null)
} else { Result.failure(exception)
cont.resumeWith(Result.success(response)) else
} Result.success(response)
} )
} }
} }
} }

@ -67,10 +67,7 @@ class Configuration constructor(
/** /**
* Indicates whether the configuration has changed from the last known valid state. * Indicates whether the configuration has changed from the last known valid state.
*/ */
fun hasConfigurationChanged(): Boolean { fun hasConfigurationChanged(): Boolean = configHash != lastKnownConfigHash
val lastHash = lastKnownConfigHash
return configHash != lastHash
}
/** /**
* Indicates whether the current configuration is valid. * Indicates whether the current configuration is valid.
@ -141,23 +138,18 @@ class Configuration constructor(
private fun getConfigString(propName: String?): String? { private fun getConfigString(propName: String?): String? {
var value = configJson!!.optString(propName) ?: return null var value = configJson!!.optString(propName) ?: return null
value = value.trim { it <= ' ' } value = value.trim { it <= ' ' }
return if (TextUtils.isEmpty(value)) { return if (TextUtils.isEmpty(value)) null else value
null
} else value
} }
@Throws(InvalidConfigurationException::class) @Throws(InvalidConfigurationException::class)
private fun getRequiredConfigString(propName: String): String { private fun getRequiredConfigString(propName: String): String = getConfigString(propName)
return getConfigString(propName)
?: throw InvalidConfigurationException( ?: throw InvalidConfigurationException(
"$propName is required but not specified in the configuration") "$propName is required but not specified in the configuration")
}
@Throws(InvalidConfigurationException::class) @Throws(InvalidConfigurationException::class)
fun getRequiredConfigUri(propName: String): Uri { fun getRequiredConfigUri(propName: String): Uri {
val uriStr = getRequiredConfigString(propName) val uriStr = getRequiredConfigString(propName)
val uri: Uri val uri = try {
uri = try {
Uri.parse(uriStr) Uri.parse(uriStr)
} catch (ex: Throwable) { } catch (ex: Throwable) {
throw InvalidConfigurationException("$propName could not be parsed", ex) throw InvalidConfigurationException("$propName could not be parsed", ex)
@ -195,12 +187,13 @@ class Configuration constructor(
get() { get() {
// ensure that the redirect URI declared in the configuration is handled by some activity // ensure that the redirect URI declared in the configuration is handled by some activity
// in the app, by querying the package manager speculatively // in the app, by querying the package manager speculatively
val redirectIntent = Intent() val redirectIntent = Intent().apply {
redirectIntent.setPackage(context.packageName) setPackage(context.packageName)
redirectIntent.action = Intent.ACTION_VIEW action = Intent.ACTION_VIEW
redirectIntent.addCategory(Intent.CATEGORY_BROWSABLE) addCategory(Intent.CATEGORY_BROWSABLE)
redirectIntent.data = mRedirectUri data = mRedirectUri
return !context.packageManager.queryIntentActivities(redirectIntent, 0).isEmpty() }
return context.packageManager.queryIntentActivities(redirectIntent, 0).isNotEmpty()
} }
class InvalidConfigurationException : Exception { class InvalidConfigurationException : Exception {

@ -52,13 +52,13 @@ class DebugConnectionBuilder @Inject constructor(
val hostnameVerifier = customCertManager.hostnameVerifier(OkHostnameVerifier) val hostnameVerifier = customCertManager.hostnameVerifier(OkHostnameVerifier)
val sslContext = SSLContext.getInstance("TLS") val sslContext = SSLContext.getInstance("TLS")
sslContext.init(null, arrayOf(customCertManager), null) sslContext.init(null, arrayOf(customCertManager), null)
val conn = URL(uri.toString()).openConnection() as HttpsURLConnection return (URL(uri.toString()).openConnection() as HttpsURLConnection).apply {
conn.connectTimeout = CONNECTION_TIMEOUT_MS connectTimeout = CONNECTION_TIMEOUT_MS
conn.readTimeout = READ_TIMEOUT_MS readTimeout = READ_TIMEOUT_MS
conn.instanceFollowRedirects = false instanceFollowRedirects = false
conn.hostnameVerifier = hostnameVerifier this.hostnameVerifier = hostnameVerifier
conn.sslSocketFactory = sslContext.socketFactory sslSocketFactory = sslContext.socketFactory
return conn }
} }
companion object { companion object {

@ -64,10 +64,8 @@ class TasksJsonExporter @Inject constructor(
this.progressDialog = progressDialog this.progressDialog = progressDialog
if (exportType == ExportType.EXPORT_TYPE_MANUAL) { if (exportType == ExportType.EXPORT_TYPE_MANUAL) {
handler = Handler() handler = Handler()
runBackup(exportType)
} else {
runBackup(exportType)
} }
runBackup(exportType)
} }
private suspend fun runBackup(exportType: ExportType) { private suspend fun runBackup(exportType: ExportType) {
@ -157,12 +155,11 @@ class TasksJsonExporter @Inject constructor(
} }
private fun getFileName(type: ExportType): String { private fun getFileName(type: ExportType): String =
return when (type) { when (type) {
ExportType.EXPORT_TYPE_SERVICE -> String.format(BackupConstants.BACKUP_FILE_NAME, dateForExport) ExportType.EXPORT_TYPE_SERVICE -> String.format(BackupConstants.BACKUP_FILE_NAME, dateForExport)
ExportType.EXPORT_TYPE_MANUAL -> String.format(BackupConstants.EXPORT_FILE_NAME, dateForExport) ExportType.EXPORT_TYPE_MANUAL -> String.format(BackupConstants.EXPORT_FILE_NAME, dateForExport)
} }
}
enum class ExportType { enum class ExportType {
EXPORT_TYPE_SERVICE, EXPORT_TYPE_MANUAL EXPORT_TYPE_SERVICE, EXPORT_TYPE_MANUAL

@ -12,24 +12,24 @@ public class XmlReader {
} }
public Long readLong(String name) { public Long readLong(String name) {
String value = xpp.getAttributeValue(null, name); final String value = xpp.getAttributeValue(null, name);
return value == null || XML_NULL.equals(value) ? null : Long.parseLong(value); return value == null || XML_NULL.equals(value) ? null : Long.parseLong(value);
} }
public void readLong(String name, ValueWriter<Long> writer) { public void readLong(String name, ValueWriter<Long> writer) {
Long value = readLong(name); final Long value = readLong(name);
if (value != null) { if (value != null) {
writer.write(value); writer.write(value);
} }
} }
public Integer readInteger(String name) { public Integer readInteger(String name) {
String value = xpp.getAttributeValue(null, name); final String value = xpp.getAttributeValue(null, name);
return value == null || XML_NULL.equals(value) ? null : Integer.parseInt(value); return value == null || XML_NULL.equals(value) ? null : Integer.parseInt(value);
} }
public void readInteger(String name, ValueWriter<Integer> writer) { public void readInteger(String name, ValueWriter<Integer> writer) {
Integer value = readInteger(name); final Integer value = readInteger(name);
if (value != null) { if (value != null) {
writer.write(value); writer.write(value);
} }
@ -40,14 +40,14 @@ public class XmlReader {
} }
public void readString(String name, ValueWriter<String> writer) { public void readString(String name, ValueWriter<String> writer) {
String value = readString(name); final String value = readString(name);
if (value != null) { if (value != null) {
writer.write(value); writer.write(value);
} }
} }
public Double readDouble(String name) { public Double readDouble(String name) {
String value = xpp.getAttributeValue(null, name); final String value = xpp.getAttributeValue(null, name);
return value == null || XML_NULL.equals(value) ? null : Double.parseDouble(value); return value == null || XML_NULL.equals(value) ? null : Double.parseDouble(value);
} }

@ -32,9 +32,9 @@ class Inventory @Inject constructor(
purchases.clear() purchases.clear()
} }
fun add(purchases: Iterable<Purchase>) { fun add(items: Iterable<Purchase>) {
verifyAndAdd(purchases) verifyAndAdd(items)
preferences.setPurchases(this.purchases.values) preferences.setPurchases(purchases.values)
localBroadcastManager.broadcastPurchasesUpdated() localBroadcastManager.broadcastPurchasesUpdated()
} }
@ -42,7 +42,7 @@ class Inventory @Inject constructor(
for (purchase in items) { for (purchase in items) {
if (signatureVerifier.verifySignature(purchase)) { if (signatureVerifier.verifySignature(purchase)) {
Timber.d("add(%s)", purchase) Timber.d("add(%s)", purchase)
this.purchases[purchase.sku] = purchase purchases[purchase.sku] = purchase
} }
} }
hasPro = purchases.values.any { it.isProSubscription } || purchases.containsKey(SKU_VIP) hasPro = purchases.values.any { it.isProSubscription } || purchases.containsKey(SKU_VIP)
@ -76,12 +76,12 @@ class Inventory @Inject constructor(
get() = purchases get() = purchases
.values .values
.filter { it.isProSubscription } .filter { it.isProSubscription }
.sortedWith{ l, r -> .sortedWith { l, r ->
r.isMonthly.compareTo(l.isMonthly) r.isMonthly.compareTo(l.isMonthly)
.takeIf { it != 0 }?.let { return@sortedWith it } .takeIf { it != 0 }?.let { return@sortedWith it }
l.isCanceled.compareTo(r.isCanceled) l.isCanceled.compareTo(r.isCanceled)
.takeIf { it != 0 }?.let { return@sortedWith it } .takeIf { it != 0 }?.let { return@sortedWith it }
return@sortedWith r.subscriptionPrice!!.compareTo(l.subscriptionPrice!!) r.subscriptionPrice!!.compareTo(l.subscriptionPrice!!)
} }
.firstOrNull() .firstOrNull()

@ -273,27 +273,28 @@ _${getString(R.string.upgrade_tasks_no_account)}_
ContextCompat.getColor(requireContext(), R.color.purchase_highlight) ContextCompat.getColor(requireContext(), R.color.purchase_highlight)
) )
binding.avgMonthly.text = aboveAverage binding.avgMonthly.text = aboveAverage
binding.payAnnually.let { with(binding.payAnnually) {
it.isEnabled = true isEnabled = true
it.text = getString( text = getString(
if (constrained) R.string.price_per_year_abbreviated else R.string.price_per_year, if (constrained) R.string.price_per_year_abbreviated else R.string.price_per_year,
annualPrice - .01 annualPrice - .01
) )
it.setOnClickListener { setOnClickListener {
initiatePurchase(false, if (nameYourPrice) sliderValue else 30) initiatePurchase(false, if (nameYourPrice) sliderValue else 30)
} }
} }
binding.payMonthly.let { with(binding.payMonthly) {
it.isEnabled = true isEnabled = true
it.text = getString( text = getString(
if (constrained) R.string.price_per_month_abbreviated else R.string.price_per_month, if (constrained) R.string.price_per_month_abbreviated else R.string.price_per_month,
monthlyPrice - .01 monthlyPrice - .01
) )
it.setOnClickListener { setOnClickListener {
initiatePurchase(true, if (nameYourPrice) sliderValue else 3) initiatePurchase(true, if (nameYourPrice) sliderValue else 3)
} }
it.isVisible = !nameYourPrice || sliderValue < 3 isVisible = !nameYourPrice || sliderValue < 3
} }
binding.avgMonthly.isVisible = nameYourPrice && binding.payMonthly.isVisible binding.avgMonthly.isVisible = nameYourPrice && binding.payMonthly.isVisible
currentSubscription?.let { currentSubscription?.let {
binding.payMonthly.isEnabled = binding.payMonthly.isEnabled =

@ -11,6 +11,7 @@ class AddCaldavAccountViewModel @ViewModelInject constructor(
provider provider
.forUrl(url, username, password) .forUrl(url, username, password)
.setForeground() .setForeground()
.homeSet(username, password) } .homeSet(username, password)
}
} }
} }

@ -70,14 +70,14 @@ abstract class BaseCaldavAccountSettingsActivity : ThemedInjectingAppCompatActiv
binding.description.visibility = View.GONE binding.description.visibility = View.GONE
} }
if (savedInstanceState == null) { if (savedInstanceState == null) {
if (caldavAccount != null) { caldavAccount?.let {
binding.name.setText(caldavAccount!!.name) binding.name.setText(it.name)
binding.url.setText(caldavAccount!!.url) binding.url.setText(it.url)
binding.user.setText(caldavAccount!!.username) binding.user.setText(it.username)
if (!isNullOrEmpty(caldavAccount!!.password)) { if (!isNullOrEmpty(it.password)) {
binding.password.setText(PASSWORD_MASK) binding.password.setText(PASSWORD_MASK)
} }
binding.repeat.isChecked = caldavAccount!!.isSuppressRepeatingTasks binding.repeat.isChecked = it.isSuppressRepeatingTasks
} }
} }
val toolbar = binding.toolbar.toolbar val toolbar = binding.toolbar.toolbar
@ -150,12 +150,10 @@ abstract class BaseCaldavAccountSettingsActivity : ThemedInjectingAppCompatActiv
if (PASSWORD_MASK == binding.password.text.toString()) { if (PASSWORD_MASK == binding.password.text.toString()) {
binding.password.setText("") binding.password.setText("")
} }
} else { } else if (TextUtils.isEmpty(binding.password.text) && caldavAccount != null) {
if (TextUtils.isEmpty(binding.password.text) && caldavAccount != null) {
binding.password.setText(PASSWORD_MASK) binding.password.setText(PASSWORD_MASK)
} }
} }
}
protected val newName: String protected val newName: String
get() { get() {
@ -252,21 +250,20 @@ abstract class BaseCaldavAccountSettingsActivity : ThemedInjectingAppCompatActiv
protected fun requestFailed(t: Throwable) { protected fun requestFailed(t: Throwable) {
hideProgressIndicator() hideProgressIndicator()
if (t is HttpException) { when (t) {
if (t.code == 401) { is HttpException ->
if (t.code == 401)
showSnackbar(R.string.invalid_username_or_password) showSnackbar(R.string.invalid_username_or_password)
} else { else
showSnackbar(t.message) showSnackbar(t.message)
} is DisplayableException -> showSnackbar(t.resId)
} else if (t is DisplayableException) { is ConnectException -> showSnackbar(R.string.network_error)
showSnackbar(t.resId) else -> {
} else if (t is ConnectException) {
showSnackbar(R.string.network_error)
} else {
Timber.e(t) Timber.e(t)
showSnackbar(R.string.error_adding_account, t.message!!) showSnackbar(R.string.error_adding_account, t.message!!)
} }
} }
}
private fun showSnackbar(resId: Int, vararg formatArgs: Any) { private fun showSnackbar(resId: Int, vararg formatArgs: Any) {
showSnackbar(getString(resId, *formatArgs)) showSnackbar(getString(resId, *formatArgs))
@ -298,11 +295,10 @@ abstract class BaseCaldavAccountSettingsActivity : ThemedInjectingAppCompatActiv
|| binding.repeat.isChecked != caldavAccount!!.isSuppressRepeatingTasks || binding.repeat.isChecked != caldavAccount!!.isSuppressRepeatingTasks
} }
protected open fun needsValidation(): Boolean { protected open fun needsValidation(): Boolean =
return (newURL != caldavAccount!!.url newURL != caldavAccount!!.url
|| newUsername != caldavAccount!!.username || newUsername != caldavAccount!!.username
|| passwordChanged()) || passwordChanged()
}
override fun finish() { override fun finish() {
if (!requestInProgress()) { if (!requestInProgress()) {
@ -338,14 +334,14 @@ abstract class BaseCaldavAccountSettingsActivity : ThemedInjectingAppCompatActiv
if (requestInProgress()) { if (requestInProgress()) {
return return
} }
if (!hasChanges()) { if (hasChanges()) {
finish()
} else {
dialogBuilder dialogBuilder
.newDialog(R.string.discard_changes) .newDialog(R.string.discard_changes)
.setPositiveButton(R.string.discard) { _, _ -> finish() } .setPositiveButton(R.string.discard) { _, _ -> finish() }
.setNegativeButton(R.string.cancel, null) .setNegativeButton(R.string.cancel, null)
.show() .show()
} else {
finish()
} }
} }

@ -96,16 +96,17 @@ abstract class BaseCaldavCalendarSettingsActivity : BaseListSettingsActivity() {
nameLayout.error = getString(R.string.name_cannot_be_empty) nameLayout.error = getString(R.string.name_cannot_be_empty)
return return
} }
if (caldavCalendar == null) { when {
caldavCalendar == null -> {
showProgressIndicator() showProgressIndicator()
createCalendar(caldavAccount, name, selectedColor) createCalendar(caldavAccount, name, selectedColor)
} else if (nameChanged() || colorChanged()) { }
nameChanged() || colorChanged() -> {
showProgressIndicator() showProgressIndicator()
updateNameAndColor(caldavAccount, caldavCalendar!!, name, selectedColor) updateNameAndColor(caldavAccount, caldavCalendar!!, name, selectedColor)
} else if (iconChanged()) { }
updateCalendar() iconChanged() -> updateCalendar()
} else { else -> finish()
finish()
} }
} }
@ -181,21 +182,17 @@ abstract class BaseCaldavCalendarSettingsActivity : BaseListSettingsActivity() {
finish() finish()
} }
override fun hasChanges(): Boolean { override fun hasChanges(): Boolean =
return if (caldavCalendar == null) !isNullOrEmpty(newName) || selectedColor != 0 || selectedIcon != -1 else nameChanged() || iconChanged() || colorChanged() if (caldavCalendar == null)
} !isNullOrEmpty(newName) || selectedColor != 0 || selectedIcon != -1
else
nameChanged() || iconChanged() || colorChanged()
private fun nameChanged(): Boolean { private fun nameChanged(): Boolean = caldavCalendar!!.name != newName
return caldavCalendar!!.name != newName
}
private fun colorChanged(): Boolean { private fun colorChanged(): Boolean = selectedColor != caldavCalendar!!.color
return selectedColor != caldavCalendar!!.color
}
private fun iconChanged(): Boolean { private fun iconChanged(): Boolean = selectedIcon != caldavCalendar!!.getIcon()
return selectedIcon != caldavCalendar!!.getIcon()
}
private val newName: String private val newName: String
get() = name.text.toString().trim { it <= ' ' } get() = name.text.toString().trim { it <= ' ' }

@ -28,13 +28,14 @@ class CaldavAccountSettingsActivity : BaseCaldavAccountSettingsActivity(), Toolb
private suspend fun addAccount(principal: String) { private suspend fun addAccount(principal: String) {
hideProgressIndicator() hideProgressIndicator()
Timber.d("Found principal: %s", principal) Timber.d("Found principal: %s", principal)
val newAccount = CaldavAccount() val newAccount = CaldavAccount().apply {
newAccount.name = newName name = newName
newAccount.url = principal url = principal
newAccount.username = newUsername username = newUsername
newAccount.password = encryption.encrypt(newPassword!!) password = encryption.encrypt(newPassword!!)
newAccount.uuid = UUIDHelper.newUUID() uuid = UUIDHelper.newUUID()
newAccount.id = caldavDao.insert(newAccount) id = caldavDao.insert(this)
}
firebase.logEvent( firebase.logEvent(
R.string.event_sync_add_account, R.string.event_sync_add_account,
R.string.param_type to Constants.SYNC_TYPE_CALDAV R.string.param_type to Constants.SYNC_TYPE_CALDAV

@ -170,30 +170,32 @@ class CaldavClient(
val xmlPullParserFactory = XmlPullParserFactory.newInstance() val xmlPullParserFactory = XmlPullParserFactory.newInstance()
val xml = xmlPullParserFactory.newSerializer() val xml = xmlPullParserFactory.newSerializer()
val stringWriter = StringWriter() val stringWriter = StringWriter()
xml.setOutput(stringWriter) with(xml) {
xml.startDocument("UTF-8", null) setOutput(stringWriter)
xml.setPrefix("", NS_WEBDAV) startDocument("UTF-8", null)
xml.setPrefix("CAL", NS_CALDAV) setPrefix("", NS_WEBDAV)
xml.startTag(NS_WEBDAV, "propertyupdate") setPrefix("CAL", NS_CALDAV)
xml.startTag(NS_WEBDAV, "set") startTag(NS_WEBDAV, "propertyupdate")
xml.startTag(NS_WEBDAV, "prop") startTag(NS_WEBDAV, "set")
setDisplayName(xml, displayName) startTag(NS_WEBDAV, "prop")
setDisplayName(this, displayName)
if (color != 0) { if (color != 0) {
setColor(xml, color) setColor(xml, color)
} }
xml.endTag(NS_WEBDAV, "prop") endTag(NS_WEBDAV, "prop")
xml.endTag(NS_WEBDAV, "set") endTag(NS_WEBDAV, "set")
if (color == 0) { if (color == 0) {
xml.startTag(NS_WEBDAV, "remove") startTag(NS_WEBDAV, "remove")
xml.startTag(NS_WEBDAV, "prop") startTag(NS_WEBDAV, "prop")
xml.startTag(NS_APPLE_ICAL, "calendar-color") startTag(NS_APPLE_ICAL, "calendar-color")
xml.endTag(NS_APPLE_ICAL, "calendar-color") endTag(NS_APPLE_ICAL, "calendar-color")
xml.endTag(NS_WEBDAV, "prop") endTag(NS_WEBDAV, "prop")
xml.endTag(NS_WEBDAV, "remove") endTag(NS_WEBDAV, "remove")
}
endTag(NS_WEBDAV, "propertyupdate")
endDocument()
flush()
} }
xml.endTag(NS_WEBDAV, "propertyupdate")
xml.endDocument()
xml.flush()
return stringWriter.toString() return stringWriter.toString()
} }
@ -202,33 +204,35 @@ class CaldavClient(
val xmlPullParserFactory = XmlPullParserFactory.newInstance() val xmlPullParserFactory = XmlPullParserFactory.newInstance()
val xml = xmlPullParserFactory.newSerializer() val xml = xmlPullParserFactory.newSerializer()
val stringWriter = StringWriter() val stringWriter = StringWriter()
xml.setOutput(stringWriter) with(xml) {
xml.startDocument("UTF-8", null) setOutput(stringWriter)
xml.setPrefix("", NS_WEBDAV) startDocument("UTF-8", null)
xml.setPrefix("CAL", NS_CALDAV) setPrefix("", NS_WEBDAV)
xml.startTag(NS_WEBDAV, "mkcol") setPrefix("CAL", NS_CALDAV)
xml.startTag(NS_WEBDAV, "set") startTag(NS_WEBDAV, "mkcol")
xml.startTag(NS_WEBDAV, "prop") startTag(NS_WEBDAV, "set")
xml.startTag(NS_WEBDAV, "resourcetype") startTag(NS_WEBDAV, "prop")
xml.startTag(NS_WEBDAV, "collection") startTag(NS_WEBDAV, "resourcetype")
xml.endTag(NS_WEBDAV, "collection") startTag(NS_WEBDAV, "collection")
xml.startTag(NS_CALDAV, "calendar") endTag(NS_WEBDAV, "collection")
xml.endTag(NS_CALDAV, "calendar") startTag(NS_CALDAV, "calendar")
xml.endTag(NS_WEBDAV, "resourcetype") endTag(NS_CALDAV, "calendar")
endTag(NS_WEBDAV, "resourcetype")
setDisplayName(xml, displayName) setDisplayName(xml, displayName)
if (color != 0) { if (color != 0) {
setColor(xml, color) setColor(xml, color)
} }
xml.startTag(NS_CALDAV, "supported-calendar-component-set") startTag(NS_CALDAV, "supported-calendar-component-set")
xml.startTag(NS_CALDAV, "comp") startTag(NS_CALDAV, "comp")
xml.attribute(null, "name", "VTODO") attribute(null, "name", "VTODO")
xml.endTag(NS_CALDAV, "comp") endTag(NS_CALDAV, "comp")
xml.endTag(NS_CALDAV, "supported-calendar-component-set") endTag(NS_CALDAV, "supported-calendar-component-set")
xml.endTag(NS_WEBDAV, "prop") endTag(NS_WEBDAV, "prop")
xml.endTag(NS_WEBDAV, "set") endTag(NS_WEBDAV, "set")
xml.endTag(NS_WEBDAV, "mkcol") endTag(NS_WEBDAV, "mkcol")
xml.endDocument() endDocument()
xml.flush() flush()
}
return stringWriter.toString() return stringWriter.toString()
} }

@ -80,17 +80,20 @@ public class CaldavConverter {
} }
public static int toRemote(int remotePriority, int localPriority) { public static int toRemote(int remotePriority, int localPriority) {
if (localPriority == Priority.NONE) { switch (localPriority) {
case Priority.NONE:
return 0; return 0;
}
if (localPriority == Priority.MEDIUM) { case Priority.MEDIUM:
return 5; return 5;
}
if (localPriority == Priority.HIGH) { case Priority.HIGH:
return remotePriority < 5 ? Math.max(1, remotePriority) : 1; return remotePriority < 5 ? Math.max(1, remotePriority) : 1;
}
default:
return remotePriority > 5 ? Math.min(9, remotePriority) : 9; return remotePriority > 5 ? Math.min(9, remotePriority) : 9;
} }
}
public static at.bitfire.ical4android.Task toCaldav(CaldavTask caldavTask, Task task) { public static at.bitfire.ical4android.Task toCaldav(CaldavTask caldavTask, Task task) {
at.bitfire.ical4android.Task remote = null; at.bitfire.ical4android.Task remote = null;

@ -23,10 +23,9 @@ object GeoUtils {
return if (string.numDecimalPlaces() < 4) string else "${string}%" return if (string.numDecimalPlaces() < 4) string else "${string}%"
} }
fun Geo.equalish(other: Geo?): Boolean { fun Geo.equalish(other: Geo?): Boolean =
return latitude.truncate() == other?.latitude?.truncate() latitude.truncate() == other?.latitude?.truncate()
&& longitude.truncate() == other.longitude?.truncate() && longitude.truncate() == other.longitude?.truncate()
}
private fun String.numDecimalPlaces(): Int { private fun String.numDecimalPlaces(): Int {
val index = indexOf(".") val index = indexOf(".")

@ -18,7 +18,7 @@ class PatchableDavResource(client: OkHttpClient, url: HttpUrl) : DavResource(cli
*/ */
@Throws(IOException::class, HttpException::class) @Throws(IOException::class, HttpException::class)
fun propPatch(xmlBody: String?, callback: (response: Response) -> Unit) { fun propPatch(xmlBody: String?, callback: (response: Response) -> Unit) {
val rqBody = if (xmlBody != null) RequestBody.create(MIME_XML, xmlBody) else null val rqBody = xmlBody?.let { RequestBody.create(MIME_XML, it) }
followRedirects { followRedirects {
httpClient.newCall(Request.Builder() httpClient.newCall(Request.Builder()

@ -60,7 +60,7 @@ class iCalendar @Inject constructor(
return null return null
} }
fun Task.getParents(): List<RelatedTo> = relatedTo.filter(IS_PARENT) private fun Task.getParents(): List<RelatedTo> = relatedTo.filter(IS_PARENT)
fun Task.getParent(): String? { fun Task.getParent(): String? {
return relatedTo.find(IS_PARENT)?.value return relatedTo.find(IS_PARENT)?.value
@ -68,12 +68,10 @@ class iCalendar @Inject constructor(
fun Task.setParent(value: String?) { fun Task.setParent(value: String?) {
val parents = getParents() val parents = getParents()
if (value.isNullOrBlank()) { when {
relatedTo.removeAll(parents) value.isNullOrBlank() -> relatedTo.removeAll(parents)
} else { parents.isEmpty() -> relatedTo.add(RelatedTo(value))
if (parents.isEmpty()) { else -> {
relatedTo.add(RelatedTo(value))
} else {
if (parents.size > 1) { if (parents.size > 1) {
relatedTo.removeAll(parents.drop(1)) relatedTo.removeAll(parents.drop(1))
} }

@ -113,17 +113,19 @@ class CaldavAccount : Parcelable {
override fun describeContents() = 0 override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) { override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeLong(id) with(dest) {
dest.writeString(uuid) writeLong(id)
dest.writeString(name) writeString(uuid)
dest.writeString(url) writeString(name)
dest.writeString(username) writeString(url)
dest.writeString(password) writeString(username)
dest.writeString(error) writeString(password)
ParcelCompat.writeBoolean(dest, isSuppressRepeatingTasks) writeString(error)
dest.writeInt(accountType) ParcelCompat.writeBoolean(this, isSuppressRepeatingTasks)
dest.writeString(encryptionKey) writeInt(accountType)
ParcelCompat.writeBoolean(dest, isCollapsed) writeString(encryptionKey)
ParcelCompat.writeBoolean(this, isCollapsed)
}
} }
override fun equals(other: Any?): Boolean { override fun equals(other: Any?): Boolean {
@ -189,13 +191,9 @@ class CaldavAccount : Parcelable {
fun String?.openTaskType(): String? = this?.split(":")?.get(0) fun String?.openTaskType(): String? = this?.split(":")?.get(0)
@JvmField val CREATOR: Parcelable.Creator<CaldavAccount> = object : Parcelable.Creator<CaldavAccount> { @JvmField val CREATOR: Parcelable.Creator<CaldavAccount> = object : Parcelable.Creator<CaldavAccount> {
override fun createFromParcel(source: Parcel): CaldavAccount? { override fun createFromParcel(source: Parcel): CaldavAccount = CaldavAccount(source)
return CaldavAccount(source)
}
override fun newArray(size: Int): Array<CaldavAccount?> { override fun newArray(size: Int): Array<CaldavAccount?> = arrayOfNulls(size)
return arrayOfNulls(size)
}
} }
} }
} }

@ -74,15 +74,17 @@ class CaldavCalendar : Parcelable {
override fun describeContents() = 0 override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) { override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeLong(id) with(dest) {
dest.writeString(account) writeLong(id)
dest.writeString(uuid) writeString(account)
dest.writeString(name) writeString(uuid)
dest.writeInt(color) writeString(name)
dest.writeString(ctag) writeInt(color)
dest.writeString(url) writeString(ctag)
dest.writeInt(getIcon()!!) writeString(url)
dest.writeInt(order) writeInt(getIcon()!!)
writeInt(order)
}
} }
override fun equals(other: Any?): Boolean { override fun equals(other: Any?): Boolean {
@ -115,22 +117,17 @@ class CaldavCalendar : Parcelable {
return result return result
} }
override fun toString(): String { override fun toString(): String =
return "CaldavCalendar(id=$id, account=$account, uuid=$uuid, name=$name, color=$color, ctag=$ctag, url=$url, icon=$icon, order=$order)" "CaldavCalendar(id=$id, account=$account, uuid=$uuid, name=$name, color=$color, ctag=$ctag, url=$url, icon=$icon, order=$order)"
}
companion object { companion object {
@JvmField val TABLE = Table("caldav_lists") @JvmField val TABLE = Table("caldav_lists")
@JvmField val UUID = TABLE.column("cdl_uuid") @JvmField val UUID = TABLE.column("cdl_uuid")
@JvmField val NAME = TABLE.column("cdl_name") @JvmField val NAME = TABLE.column("cdl_name")
@JvmField val CREATOR: Parcelable.Creator<CaldavCalendar> = object : Parcelable.Creator<CaldavCalendar> { @JvmField val CREATOR: Parcelable.Creator<CaldavCalendar> = object : Parcelable.Creator<CaldavCalendar> {
override fun createFromParcel(source: Parcel): CaldavCalendar? { override fun createFromParcel(source: Parcel): CaldavCalendar = CaldavCalendar(source)
return CaldavCalendar(source)
}
override fun newArray(size: Int): Array<CaldavCalendar?> { override fun newArray(size: Int): Array<CaldavCalendar?> = arrayOfNulls(size)
return arrayOfNulls(size)
}
} }
} }
} }

@ -64,9 +64,8 @@ class CaldavTask {
fun isDeleted() = deleted > 0 fun isDeleted() = deleted > 0
override fun toString(): String { override fun toString(): String =
return "CaldavTask(id=$id, task=$task, calendar=$calendar, `object`=$`object`, remoteId=$remoteId, etag=$etag, lastSync=$lastSync, deleted=$deleted, vtodo=$vtodo, remoteParent=$remoteParent, order=$order)" "CaldavTask(id=$id, task=$task, calendar=$calendar, `object`=$`object`, remoteId=$remoteId, etag=$etag, lastSync=$lastSync, deleted=$deleted, vtodo=$vtodo, remoteParent=$remoteParent, order=$order)"
}
companion object { companion object {
const val KEY = "caldav" const val KEY = "caldav"

@ -20,7 +20,5 @@ class CaldavTaskContainer {
val sortOrder: Long val sortOrder: Long
get() = caldavTask.order ?: DateTime(task.creationDate).toAppleEpoch() get() = caldavTask.order ?: DateTime(task.creationDate).toAppleEpoch()
override fun toString(): String { override fun toString(): String = "CaldavTaskContainer{task=$task, caldavTask=$caldavTask}"
return "CaldavTaskContainer{task=$task, caldavTask=$caldavTask}"
}
} }

@ -20,19 +20,11 @@ class ContentProviderDaoBlocking @Inject constructor(private val dao: ContentPro
dao.tagDataOrderedByName() dao.tagDataOrderedByName()
} }
fun getTasks(): Cursor { fun getTasks(): Cursor = dao.getTasks()
return dao.getTasks()
}
fun getLists(): Cursor { fun getLists(): Cursor = dao.getLists()
return dao.getLists()
}
fun getGoogleTaskLists(): Cursor { fun getGoogleTaskLists(): Cursor = dao.getGoogleTaskLists()
return dao.getGoogleTaskLists()
}
fun rawQuery(query: SupportSQLiteQuery): Cursor { fun rawQuery(query: SupportSQLiteQuery): Cursor = dao.rawQuery(query)
return dao.rawQuery(query)
}
} }

@ -36,10 +36,8 @@ class Filter {
@ColumnInfo(name = "f_order") @ColumnInfo(name = "f_order")
var order = NO_ORDER var order = NO_ORDER
fun getSql(): String {
// TODO: replace dirty hack for missing column // TODO: replace dirty hack for missing column
return sql!!.replace("tasks.userId=0", "1") fun getSql(): String = sql!!.replace("tasks.userId=0", "1")
}
fun setSql(sql: String?) { fun setSql(sql: String?) {
this.sql = sql this.sql = sql
@ -48,17 +46,13 @@ class Filter {
val valuesAsMap: Map<String, Any>? val valuesAsMap: Map<String, Any>?
get() = if (Strings.isNullOrEmpty(values)) null else AndroidUtilities.mapFromSerializedString(values) get() = if (Strings.isNullOrEmpty(values)) null else AndroidUtilities.mapFromSerializedString(values)
fun getColor(): Int? { fun getColor(): Int = color ?: 0
return (if (color == null) 0 else color)!!
}
fun setColor(color: Int?) { fun setColor(color: Int?) {
this.color = color this.color = color
} }
fun getIcon(): Int? { fun getIcon(): Int = icon ?: FILTER
return (if (icon == null) FILTER else icon!!)
}
fun setIcon(icon: Int?) { fun setIcon(icon: Int?) {
this.icon = icon this.icon = icon
@ -92,7 +86,6 @@ class Filter {
return result return result
} }
override fun toString(): String { override fun toString(): String =
return "Filter(id=$id, title=$title, sql=$sql, values=$values, criterion=$criterion, color=$color, icon=$icon, order=$order)" "Filter(id=$id, title=$title, sql=$sql, values=$values, criterion=$criterion, color=$color, icon=$icon, order=$order)"
}
} }

@ -78,12 +78,14 @@ class Geofence : Serializable, Parcelable {
override fun describeContents() = 0 override fun describeContents() = 0
override fun writeToParcel(out: Parcel, flags: Int) { override fun writeToParcel(out: Parcel, flags: Int) {
out.writeLong(id) with(out) {
out.writeLong(task) writeLong(id)
out.writeString(place) writeLong(task)
out.writeInt(radius) writeString(place)
out.writeInt(if (isArrival) 1 else 0) writeInt(radius)
out.writeInt(if (isDeparture) 1 else 0) writeInt(if (isArrival) 1 else 0)
writeInt(if (isDeparture) 1 else 0)
}
} }
override fun equals(other: Any?): Boolean { override fun equals(other: Any?): Boolean {
@ -110,9 +112,8 @@ class Geofence : Serializable, Parcelable {
return result return result
} }
override fun toString(): String { override fun toString(): String =
return "Geofence(id=$id, task=$task, place=$place, radius=$radius, isArrival=$isArrival, isDeparture=$isDeparture)" "Geofence(id=$id, task=$task, place=$place, radius=$radius, isArrival=$isArrival, isDeparture=$isDeparture)"
}
companion object { companion object {
const val TABLE_NAME = "geofences" const val TABLE_NAME = "geofences"
@ -120,13 +121,9 @@ class Geofence : Serializable, Parcelable {
@JvmField val TASK = TABLE.column("task") @JvmField val TASK = TABLE.column("task")
@JvmField val PLACE = TABLE.column("place") @JvmField val PLACE = TABLE.column("place")
@JvmField val CREATOR: Parcelable.Creator<Geofence> = object : Parcelable.Creator<Geofence> { @JvmField val CREATOR: Parcelable.Creator<Geofence> = object : Parcelable.Creator<Geofence> {
override fun createFromParcel(source: Parcel): Geofence? { override fun createFromParcel(source: Parcel): Geofence = Geofence(source)
return Geofence(source)
}
override fun newArray(size: Int): Array<Geofence?> { override fun newArray(size: Int): Array<Geofence?> = arrayOfNulls(size)
return arrayOfNulls(size)
}
} }
} }
} }

@ -92,9 +92,8 @@ class GoogleTask {
return result return result
} }
override fun toString(): String { override fun toString(): String =
return "GoogleTask(id=$id, task=$task, remoteId='$remoteId', listId='$listId', parent=$parent, remoteParent=$remoteParent, isMoved=$isMoved, order=$order, remoteOrder=$remoteOrder, lastSync=$lastSync, deleted=$deleted)" "GoogleTask(id=$id, task=$task, remoteId='$remoteId', listId='$listId', parent=$parent, remoteParent=$remoteParent, isMoved=$isMoved, order=$order, remoteOrder=$remoteOrder, lastSync=$lastSync, deleted=$deleted)"
}
val isNew: Boolean val isNew: Boolean
get() = id == 0L get() = id == 0L

@ -47,11 +47,13 @@ class GoogleTaskAccount : Parcelable {
override fun describeContents() = 0 override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) { override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeLong(id) with(dest) {
dest.writeString(account) writeLong(id)
dest.writeString(error) writeString(account)
dest.writeString(etag) writeString(error)
ParcelCompat.writeBoolean(dest, isCollapsed) writeString(etag)
ParcelCompat.writeBoolean(this, isCollapsed)
}
} }
override fun equals(other: Any?): Boolean { override fun equals(other: Any?): Boolean {
@ -76,19 +78,14 @@ class GoogleTaskAccount : Parcelable {
return result return result
} }
override fun toString(): String { override fun toString(): String =
return "GoogleTaskAccount(id=$id, account=$account, error=$error, etag=$etag, isCollapsed=$isCollapsed)" "GoogleTaskAccount(id=$id, account=$account, error=$error, etag=$etag, isCollapsed=$isCollapsed)"
}
companion object { companion object {
@JvmField val CREATOR: Parcelable.Creator<GoogleTaskAccount> = object : Parcelable.Creator<GoogleTaskAccount> { @JvmField val CREATOR: Parcelable.Creator<GoogleTaskAccount> = object : Parcelable.Creator<GoogleTaskAccount> {
override fun createFromParcel(source: Parcel): GoogleTaskAccount? { override fun createFromParcel(source: Parcel): GoogleTaskAccount = GoogleTaskAccount(source)
return GoogleTaskAccount(source)
}
override fun newArray(size: Int): Array<GoogleTaskAccount?> { override fun newArray(size: Int): Array<GoogleTaskAccount?> = arrayOfNulls(size)
return arrayOfNulls(size)
}
} }
} }
} }

@ -52,17 +52,13 @@ class GoogleTaskList : Parcelable {
icon = parcel.readInt() icon = parcel.readInt()
} }
fun getColor(): Int? { fun getColor(): Int = color ?: 0
return (if (color == null) 0 else color)!!
}
fun setColor(color: Int?) { fun setColor(color: Int?) {
this.color = color this.color = color
} }
fun getIcon(): Int? { fun getIcon(): Int = icon ?: LIST
return (if (icon == null) LIST else icon!!)
}
fun setIcon(icon: Int?) { fun setIcon(icon: Int?) {
this.icon = icon this.icon = icon
@ -71,14 +67,16 @@ class GoogleTaskList : Parcelable {
override fun describeContents() = 0 override fun describeContents() = 0
override fun writeToParcel(parcel: Parcel, i: Int) { override fun writeToParcel(parcel: Parcel, i: Int) {
parcel.writeLong(id) with(parcel) {
parcel.writeString(account) writeLong(id)
parcel.writeString(remoteId) writeString(account)
parcel.writeString(title) writeString(remoteId)
parcel.writeInt(order) writeString(title)
parcel.writeLong(lastSync) writeInt(order)
parcel.writeInt(getColor()!!) writeLong(lastSync)
parcel.writeInt(getIcon()!!) writeInt(getColor())
writeInt(getIcon())
}
} }
override fun equals(other: Any?): Boolean { override fun equals(other: Any?): Boolean {
@ -109,22 +107,17 @@ class GoogleTaskList : Parcelable {
return result return result
} }
override fun toString(): String { override fun toString(): String =
return "GoogleTaskList(id=$id, account=$account, remoteId=$remoteId, title=$title, remoteOrder=$order, lastSync=$lastSync, color=$color, icon=$icon)" "GoogleTaskList(id=$id, account=$account, remoteId=$remoteId, title=$title, remoteOrder=$order, lastSync=$lastSync, color=$color, icon=$icon)"
}
companion object { companion object {
@JvmField val TABLE = Table("google_task_lists") @JvmField val TABLE = Table("google_task_lists")
@JvmField val REMOTE_ID = TABLE.column("gtl_remote_id") @JvmField val REMOTE_ID = TABLE.column("gtl_remote_id")
@JvmField val NAME = TABLE.column("gtl_title") @JvmField val NAME = TABLE.column("gtl_title")
@JvmField val CREATOR: Parcelable.Creator<GoogleTaskList> = object : Parcelable.Creator<GoogleTaskList> { @JvmField val CREATOR: Parcelable.Creator<GoogleTaskList> = object : Parcelable.Creator<GoogleTaskList> {
override fun createFromParcel(parcel: Parcel): GoogleTaskList? { override fun createFromParcel(parcel: Parcel): GoogleTaskList = GoogleTaskList(parcel)
return GoogleTaskList(parcel)
}
override fun newArray(size: Int): Array<GoogleTaskList?> { override fun newArray(size: Int): Array<GoogleTaskList?> = arrayOfNulls(size)
return arrayOfNulls(size)
}
} }
} }
} }

@ -82,19 +82,13 @@ class Location : Serializable, Parcelable {
return result return result
} }
override fun toString(): String { override fun toString(): String = "Location(geofence=$geofence, place=$place)"
return "Location(geofence=$geofence, place=$place)"
}
companion object { companion object {
@JvmField val CREATOR: Parcelable.Creator<Location> = object : Parcelable.Creator<Location> { @JvmField val CREATOR: Parcelable.Creator<Location> = object : Parcelable.Creator<Location> {
override fun createFromParcel(`in`: Parcel): Location? { override fun createFromParcel(`in`: Parcel): Location = Location(`in`)
return Location(`in`)
}
override fun newArray(size: Int): Array<Location?> { override fun newArray(size: Int): Array<Location?> = arrayOfNulls(size)
return arrayOfNulls(size)
}
} }
} }
} }

@ -17,7 +17,6 @@ class MergedGeofence {
val longitude: Double val longitude: Double
get() = place.longitude get() = place.longitude
override fun toString(): String { override fun toString(): String =
return "MergedGeofence(place=$place, arrival=$arrival, departure=$departure, radius=$radius)" "MergedGeofence(place=$place, arrival=$arrival, departure=$departure, radius=$radius)"
}
} }

@ -90,9 +90,7 @@ class Place : Serializable, Parcelable {
order = parcel.readInt() order = parcel.readInt()
} }
fun getIcon(): Int? { fun getIcon(): Int = if (icon == -1) PLACE else icon
return if (icon == -1) PLACE else icon
}
fun setIcon(icon: Int) { fun setIcon(icon: Int) {
this.icon = icon this.icon = icon
@ -128,17 +126,19 @@ class Place : Serializable, Parcelable {
override fun describeContents() = 0 override fun describeContents() = 0
override fun writeToParcel(out: Parcel, flags: Int) { override fun writeToParcel(out: Parcel, flags: Int) {
out.writeLong(id) with(out) {
out.writeString(uid) writeLong(id)
out.writeString(name) writeString(uid)
out.writeString(address) writeString(name)
out.writeString(phone) writeString(address)
out.writeString(url) writeString(phone)
out.writeDouble(latitude) writeString(url)
out.writeDouble(longitude) writeDouble(latitude)
out.writeInt(color) writeDouble(longitude)
out.writeInt(icon) writeInt(color)
out.writeInt(order) writeInt(icon)
writeInt(order)
}
} }
override fun equals(other: Any?): Boolean { override fun equals(other: Any?): Boolean {
@ -175,9 +175,8 @@ class Place : Serializable, Parcelable {
return result return result
} }
override fun toString(): String { override fun toString(): String =
return "Place(id=$id, uid=$uid, name=$name, address=$address, phone=$phone, url=$url, latitude=$latitude, longitude=$longitude, color=$color, icon=$icon, order=$order)" "Place(id=$id, uid=$uid, name=$name, address=$address, phone=$phone, url=$url, latitude=$latitude, longitude=$longitude, color=$color, icon=$icon, order=$order)"
}
companion object { companion object {
const val KEY = "place" const val KEY = "place"
@ -187,13 +186,9 @@ class Place : Serializable, Parcelable {
@JvmField val NAME = TABLE.column("name") @JvmField val NAME = TABLE.column("name")
@JvmField val ADDRESS = TABLE.column("address") @JvmField val ADDRESS = TABLE.column("address")
@JvmField val CREATOR: Parcelable.Creator<Place> = object : Parcelable.Creator<Place> { @JvmField val CREATOR: Parcelable.Creator<Place> = object : Parcelable.Creator<Place> {
override fun createFromParcel(source: Parcel): Place? { override fun createFromParcel(source: Parcel): Place = Place(source)
return Place(source)
}
override fun newArray(size: Int): Array<Place?> { override fun newArray(size: Int): Array<Place?> = arrayOfNulls(size)
return arrayOfNulls(size)
}
} }
private val pattern = Pattern.compile("(\\d+):(\\d+):(\\d+\\.\\d+)") private val pattern = Pattern.compile("(\\d+):(\\d+):(\\d+\\.\\d+)")
private val COORDS = Pattern.compile("^\\d+°\\d+'\\d+\\.\\d+\"[NS] \\d+°\\d+'\\d+\\.\\d+\"[EW]$") private val COORDS = Pattern.compile("^\\d+°\\d+'\\d+\\.\\d+\"[NS] \\d+°\\d+'\\d+\\.\\d+\"[EW]$")
@ -212,42 +207,36 @@ class Place : Serializable, Parcelable {
} }
} }
@JvmStatic fun newPlace(geo: Geo): Place { @JvmStatic fun newPlace(geo: Geo): Place = newPlace().apply {
val place = newPlace() latitude = geo.latitude.toDouble()
place.latitude = geo.latitude.toDouble() longitude = geo.longitude.toDouble()
place.longitude = geo.longitude.toDouble()
return place
} }
@JvmStatic fun newPlace(mapPosition: MapPosition?): Place? { @JvmStatic fun newPlace(mapPosition: MapPosition?): Place? {
if (mapPosition == null) { if (mapPosition == null) {
return null return null
} }
val place = newPlace()
place.latitude = mapPosition.latitude return newPlace().apply {
place.longitude = mapPosition.longitude latitude = mapPosition.latitude
return place longitude = mapPosition.longitude
}
} }
@JvmStatic fun newPlace(feature: CarmenFeature): Place { @JvmStatic fun newPlace(feature: CarmenFeature): Place = newPlace().apply {
val address = feature.placeName()
val types = feature.placeType() val types = feature.placeType()
val place = newPlace()
place.name = if (types != null && types.contains(GeocodingCriteria.TYPE_ADDRESS)) { name = if (types != null && types.contains(GeocodingCriteria.TYPE_ADDRESS)) {
"${feature.address()} ${feature.text()}" "${feature.address()} ${feature.text()}"
} else { } else {
feature.text() feature.text()
} }
place.address = address
place.latitude = feature.center()!!.latitude()
place.longitude = feature.center()!!.longitude()
return place
}
@JvmStatic fun newPlace(): Place { address = feature.placeName()
val place = Place() latitude = feature.center()!!.latitude()
place.uid = UUIDHelper.newUUID() longitude = feature.center()!!.longitude()
return place
} }
@JvmStatic fun newPlace(): Place = Place().apply { uid = UUIDHelper.newUUID() }
} }
} }

@ -28,7 +28,5 @@ class PlaceUsage {
return result return result
} }
override fun toString(): String { override fun toString(): String = "PlaceUsage(place=$place, count=$count)"
return "PlaceUsage(place=$place, count=$count)"
}
} }

@ -26,7 +26,6 @@ class SubsetCaldav {
return result return result
} }
override fun toString(): String { override fun toString(): String =
return "SubsetCaldav(cd_id=$cd_id, cd_calendar=$cd_calendar, cd_remote_parent=$cd_remote_parent, cd_order=$cd_order)" "SubsetCaldav(cd_id=$cd_id, cd_calendar=$cd_calendar, cd_remote_parent=$cd_remote_parent, cd_order=$cd_order)"
}
} }

@ -49,9 +49,7 @@ class Tag {
xmlReader.readString("task_uid") { taskUid: String -> setTaskUid(taskUid) } xmlReader.readString("task_uid") { taskUid: String -> setTaskUid(taskUid) }
} }
fun getTaskUid(): String { fun getTaskUid(): String = taskUid!!
return taskUid!!
}
fun setTaskUid(taskUid: String) { fun setTaskUid(taskUid: String) {
this.taskUid = taskUid this.taskUid = taskUid

@ -55,26 +55,24 @@ class TagData : Parcelable {
@SuppressLint("ParcelClassLoader") @SuppressLint("ParcelClassLoader")
@Ignore @Ignore
private constructor(parcel: Parcel) { private constructor(parcel: Parcel) {
id = parcel.readValue(null) as Long? with(parcel) {
remoteId = parcel.readString() id = readValue(null) as Long?
name = parcel.readString() remoteId = readString()
color = parcel.readInt() name = readString()
tagOrdering = parcel.readString() color = readInt()
icon = parcel.readInt() tagOrdering = readString()
order = parcel.readInt() icon = readInt()
order = readInt()
} }
fun getColor(): Int? {
return (if (color == null) 0 else color)!!
} }
fun getColor(): Int = color ?: 0
fun setColor(color: Int?) { fun setColor(color: Int?) {
this.color = color this.color = color
} }
fun getIcon(): Int? { fun getIcon(): Int = icon ?: LABEL
return (if (icon == null) LABEL else icon!!)
}
fun setIcon(icon: Int?) { fun setIcon(icon: Int?) {
this.icon = icon this.icon = icon
@ -83,13 +81,15 @@ class TagData : Parcelable {
override fun describeContents() = 0 override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) { override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeValue(id) with(dest) {
dest.writeString(remoteId) writeValue(id)
dest.writeString(name) writeString(remoteId)
dest.writeInt(color!!) writeString(name)
dest.writeString(tagOrdering) writeInt(color!!)
dest.writeInt(getIcon()!!) writeString(tagOrdering)
dest.writeInt(order) writeInt(getIcon())
writeInt(order)
}
} }
override fun equals(other: Any?): Boolean { override fun equals(other: Any?): Boolean {
@ -118,19 +118,14 @@ class TagData : Parcelable {
return result return result
} }
override fun toString(): String { override fun toString(): String =
return "TagData(id=$id, remoteId=$remoteId, name=$name, color=$color, tagOrdering=$tagOrdering, icon=$icon, order=$order)" "TagData(id=$id, remoteId=$remoteId, name=$name, color=$color, tagOrdering=$tagOrdering, icon=$icon, order=$order)"
}
companion object { companion object {
@JvmField val CREATOR: Parcelable.Creator<TagData> = object : Parcelable.Creator<TagData> { @JvmField val CREATOR: Parcelable.Creator<TagData> = object : Parcelable.Creator<TagData> {
override fun createFromParcel(source: Parcel): TagData? { override fun createFromParcel(source: Parcel): TagData = TagData(source)
return TagData(source)
}
override fun newArray(size: Int): Array<TagData?> { override fun newArray(size: Int): Array<TagData?> = arrayOfNulls(size)
return arrayOfNulls(size)
}
} }
} }
} }

@ -25,13 +25,9 @@ abstract class TagDataDao {
* If a tag already exists in the database that case insensitively matches the given tag, return * If a tag already exists in the database that case insensitively matches the given tag, return
* that. Otherwise, return the argument * that. Otherwise, return the argument
*/ */
suspend fun getTagWithCase(tag: String): String? { suspend fun getTagWithCase(tag: String): String? = getTagByName(tag)?.name ?: tag
return getTagByName(tag)?.name ?: tag
}
suspend fun searchTags(query: String): List<TagData> { suspend fun searchTags(query: String): List<TagData> = searchTagsInternal("%$query%").sort()
return searchTagsInternal("%$query%").sort()
}
@Query("SELECT * FROM tagdata WHERE name LIKE :query AND name NOT NULL AND name != ''") @Query("SELECT * FROM tagdata WHERE name LIKE :query AND name NOT NULL AND name != ''")
protected abstract suspend fun searchTagsInternal(query: String): List<TagData> protected abstract suspend fun searchTagsInternal(query: String): List<TagData>

@ -50,9 +50,7 @@ class TaskAttachment {
setUri(Uri.fromFile(File(uri!!)).toString()) setUri(Uri.fromFile(File(uri!!)).toString())
} }
fun parseUri(): Uri? { fun parseUri(): Uri? = if (Strings.isNullOrEmpty(uri)) null else Uri.parse(uri)
return if (Strings.isNullOrEmpty(uri)) null else Uri.parse(uri)
}
companion object { companion object {
const val KEY = "attachment" const val KEY = "attachment"

@ -99,8 +99,8 @@ abstract class TaskDao(private val database: Database) {
return fetchTasks(callback, getSubtaskInfo()) return fetchTasks(callback, getSubtaskInfo())
} }
open suspend fun fetchTasks(callback: suspend (SubtaskInfo) -> List<String>, subtasks: SubtaskInfo): List<TaskContainer> { open suspend fun fetchTasks(callback: suspend (SubtaskInfo) -> List<String>, subtasks: SubtaskInfo): List<TaskContainer> =
return database.withTransaction { database.withTransaction {
val start = if (BuildConfig.DEBUG) DateUtilities.now() else 0 val start = if (BuildConfig.DEBUG) DateUtilities.now() else 0
val queries = callback.invoke(subtasks) val queries = callback.invoke(subtasks)
val last = queries.size - 1 val last = queries.size - 1
@ -111,13 +111,11 @@ abstract class TaskDao(private val database: Database) {
Timber.v("%sms: %s", DateUtilities.now() - start, queries.joinToString(";\n")) Timber.v("%sms: %s", DateUtilities.now() - start, queries.joinToString(";\n"))
result result
} }
}
suspend fun fetchTasks(preferences: Preferences, filter: Filter): List<TaskContainer> { suspend fun fetchTasks(preferences: Preferences, filter: Filter): List<TaskContainer> =
return fetchTasks { fetchTasks {
TaskListQuery.getQuery(preferences, filter, it) TaskListQuery.getQuery(preferences, filter, it)
} }
}
@RawQuery @RawQuery
internal abstract suspend fun query(query: SimpleSQLiteQuery): Int internal abstract suspend fun query(query: SimpleSQLiteQuery): Int
@ -154,9 +152,7 @@ SELECT EXISTS(SELECT 1 FROM tasks WHERE parent > 0 AND deleted = 0) AS hasSubtas
@Query("UPDATE tasks SET lastNotified = :timestamp WHERE _id = :id AND lastNotified != :timestamp") @Query("UPDATE tasks SET lastNotified = :timestamp WHERE _id = :id AND lastNotified != :timestamp")
abstract suspend fun setLastNotified(id: Long, timestamp: Long): Int abstract suspend fun setLastNotified(id: Long, timestamp: Long): Int
suspend fun getChildren(id: Long): List<Long> { suspend fun getChildren(id: Long): List<Long> = getChildren(listOf(id))
return getChildren(listOf(id))
}
@Query("WITH RECURSIVE " @Query("WITH RECURSIVE "
+ " recursive_tasks (task) AS ( " + " recursive_tasks (task) AS ( "
@ -225,9 +221,7 @@ SELECT EXISTS(SELECT 1 FROM tasks WHERE parent > 0 AND deleted = 0) AS hasSubtas
return count return count
} }
suspend fun fetchFiltered(filter: Filter): List<Task> { suspend fun fetchFiltered(filter: Filter): List<Task> = fetchFiltered(filter.getSqlQuery())
return fetchFiltered(filter.getSqlQuery())
}
suspend fun fetchFiltered(queryTemplate: String): List<Task> { suspend fun fetchFiltered(queryTemplate: String): List<Task> {
val query = getQuery(queryTemplate, Task.FIELDS) val query = getQuery(queryTemplate, Task.FIELDS)
@ -252,21 +246,18 @@ WHERE gt_id IS NULL
object TaskCriteria { object TaskCriteria {
/** @return tasks that have not yet been completed or deleted /** @return tasks that have not yet been completed or deleted
*/ */
@JvmStatic fun activeAndVisible(): Criterion { @JvmStatic fun activeAndVisible(): Criterion = Criterion.and(
return Criterion.and(
Task.COMPLETION_DATE.lte(0), Task.COMPLETION_DATE.lte(0),
Task.DELETION_DATE.lte(0), Task.DELETION_DATE.lte(0),
Task.HIDE_UNTIL.lte(Functions.now())) Task.HIDE_UNTIL.lte(Functions.now()))
} }
}
companion object { companion object {
fun getQuery(queryTemplate: String, vararg fields: Field): SimpleSQLiteQuery { fun getQuery(queryTemplate: String, vararg fields: Field): SimpleSQLiteQuery =
return SimpleSQLiteQuery( SimpleSQLiteQuery(
com.todoroo.andlib.sql.Query.select(*fields) com.todoroo.andlib.sql.Query.select(*fields)
.withQueryTemplate(PermaSql.replacePlaceholdersForQuery(queryTemplate)) .withQueryTemplate(PermaSql.replacePlaceholdersForQuery(queryTemplate))
.from(Task.TABLE) .from(Task.TABLE)
.toString()) .toString())
} }
}
} }

@ -36,15 +36,13 @@ object TaskListQuery {
preferences: QueryPreferences, preferences: QueryPreferences,
filter: Filter, filter: Filter,
subtasks: SubtaskInfo subtasks: SubtaskInfo
): MutableList<String> { ): MutableList<String> = when {
return if (filter.supportsManualSort() && preferences.isManualSort) { filter.supportsManualSort() && preferences.isManualSort ->
getRecursiveQuery(filter, preferences, subtasks) getRecursiveQuery(filter, preferences, subtasks)
} else if (filter.supportsAstridSorting() && preferences.isAstridSort) { filter.supportsAstridSorting() && preferences.isAstridSort ->
getNonRecursiveQuery(filter, preferences) getNonRecursiveQuery(filter, preferences)
} else if (filter.supportsSubtasks() && subtasks.usesSubtasks() && !preferences.usePagedQueries()) { filter.supportsSubtasks() && subtasks.usesSubtasks() && !preferences.usePagedQueries() ->
getRecursiveQuery(filter, preferences, subtasks) getRecursiveQuery(filter, preferences, subtasks)
} else { else -> getNonRecursiveQuery(filter, preferences)
getNonRecursiveQuery(filter, preferences)
}
} }
} }

@ -55,12 +55,14 @@ class UserActivity : Parcelable {
@Ignore @Ignore
private constructor(parcel: Parcel) { private constructor(parcel: Parcel) {
id = parcel.readLong() with(parcel) {
remoteId = parcel.readString() id = readLong()
message = parcel.readString() remoteId = readString()
picture = parcel.readString() message = readString()
targetId = parcel.readString() picture = readString()
created = parcel.readLong() targetId = readString()
created = readLong()
}
} }
fun setPicture(uri: Uri?) { fun setPicture(uri: Uri?) {
@ -77,12 +79,14 @@ class UserActivity : Parcelable {
override fun describeContents() = 0 override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) { override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeLong(id!!) with(dest) {
dest.writeString(remoteId) writeLong(id!!)
dest.writeString(message) writeString(remoteId)
dest.writeString(picture) writeString(message)
dest.writeString(targetId) writeString(picture)
dest.writeLong(created!!) writeString(targetId)
writeLong(created!!)
}
} }
companion object { companion object {
@ -90,13 +94,9 @@ class UserActivity : Parcelable {
@JvmField val TASK = TABLE.column("target_id") @JvmField val TASK = TABLE.column("target_id")
@JvmField val MESSAGE = TABLE.column("message") @JvmField val MESSAGE = TABLE.column("message")
@JvmField val CREATOR: Parcelable.Creator<UserActivity> = object : Parcelable.Creator<UserActivity> { @JvmField val CREATOR: Parcelable.Creator<UserActivity> = object : Parcelable.Creator<UserActivity> {
override fun createFromParcel(source: Parcel): UserActivity? { override fun createFromParcel(source: Parcel): UserActivity = UserActivity(source)
return UserActivity(source)
}
override fun newArray(size: Int): Array<UserActivity?> { override fun newArray(size: Int): Array<UserActivity?> = arrayOfNulls(size)
return arrayOfNulls(size)
}
} }
private fun getLegacyPictureUri(value: String?): Uri? { private fun getLegacyPictureUri(value: String?): Uri? {

@ -9,9 +9,8 @@ object DateTimeUtils {
@JvmStatic @JvmStatic
fun newDateUtc( fun newDateUtc(
year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int): DateTime { year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int): DateTime =
return DateTime(year, month, day, hour, minute, second, 0, TimeZone.getTimeZone("GMT")) DateTime(year, month, day, hour, minute, second, 0, TimeZone.getTimeZone("GMT"))
}
@JvmStatic @JvmStatic
fun newDateTime(): DateTime = DateTime() fun newDateTime(): DateTime = DateTime()

@ -392,9 +392,7 @@ object Migrations {
MIGRATION_75_76 MIGRATION_75_76
) )
private fun noop(from: Int, to: Int): Migration { private fun noop(from: Int, to: Int): Migration = object : Migration(from, to) {
return object : Migration(from, to) {
override fun migrate(database: SupportSQLiteDatabase) {} override fun migrate(database: SupportSQLiteDatabase) {}
} }
}
} }

@ -20,15 +20,13 @@ object QueryUtils {
fun showHiddenAndCompleted(query: String): String = showCompleted(showHidden(query)) fun showHiddenAndCompleted(query: String): String = showCompleted(showHidden(query))
@JvmStatic @JvmStatic
fun showRecentlyCompleted(query: String): String { fun showRecentlyCompleted(query: String): String = UNCOMPLETED
return UNCOMPLETED
.matcher(query) .matcher(query)
.replaceAll( .replaceAll(
or( or(
Task.COMPLETION_DATE.lte(0), Task.COMPLETION_DATE.lte(0),
Task.COMPLETION_DATE.gte(DateUtilities.now() - 59999)) Task.COMPLETION_DATE.gte(DateUtilities.now() - 59999))
.toString()) .toString())
}
fun removeOrder(query: String): String = ORDER.matcher(query).replaceAll("") fun removeOrder(query: String): String = ORDER.matcher(query).replaceAll("")
} }

@ -78,10 +78,9 @@ class AddAttachmentDialog : DialogFragment() {
const val REQUEST_AUDIO = 12123 const val REQUEST_AUDIO = 12123
private const val FRAG_TAG_RECORD_AUDIO = "frag_tag_record_audio" private const val FRAG_TAG_RECORD_AUDIO = "frag_tag_record_audio"
fun newAddAttachmentDialog(target: FilesControlSet?): AddAttachmentDialog { fun newAddAttachmentDialog(target: FilesControlSet?): AddAttachmentDialog =
val dialog = AddAttachmentDialog() AddAttachmentDialog().apply {
dialog.setTargetFragment(target, 0) setTargetFragment(target, 0)
return dialog
} }
} }
} }

@ -39,12 +39,9 @@ class ColorPickerAdapter(
} }
private class DiffCallback : DiffUtil.ItemCallback<Pickable>() { private class DiffCallback : DiffUtil.ItemCallback<Pickable>() {
override fun areItemsTheSame(oldItem: Pickable, newItem: Pickable): Boolean { override fun areItemsTheSame(oldItem: Pickable, newItem: Pickable): Boolean =
return oldItem == newItem oldItem == newItem
}
override fun areContentsTheSame(oldItem: Pickable, newItem: Pickable): Boolean { override fun areContentsTheSame(oldItem: Pickable, newItem: Pickable): Boolean = true
return true
}
} }
} }

@ -20,17 +20,20 @@ class ExportTasksDialog : DialogFragment() {
@Inject lateinit var tasksJsonExporter: TasksJsonExporter @Inject lateinit var tasksJsonExporter: TasksJsonExporter
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val progressDialog = dialogBuilder.newProgressDialog() val progressDialog = dialogBuilder.newProgressDialog().apply {
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL) setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
progressDialog.progress = 0 progress = 0
progressDialog.setCancelable(false) setCancelable(false)
progressDialog.isIndeterminate = false isIndeterminate = false
}
progressDialog.show() progressDialog.show()
isCancelable = false isCancelable = false
lifecycleScope.launch(NonCancellable) { lifecycleScope.launch(NonCancellable) {
tasksJsonExporter.exportTasks( tasksJsonExporter.exportTasks(
activity, TasksJsonExporter.ExportType.EXPORT_TYPE_MANUAL, progressDialog) activity, TasksJsonExporter.ExportType.EXPORT_TYPE_MANUAL, progressDialog)
} }
return progressDialog return progressDialog
} }

@ -30,10 +30,12 @@ class ImportTasksDialog : DialogFragment() {
val arguments = requireArguments() val arguments = requireArguments()
val data = arguments.getParcelable<Uri>(EXTRA_URI) val data = arguments.getParcelable<Uri>(EXTRA_URI)
val extension = arguments.getString(EXTRA_EXTENSION) val extension = arguments.getString(EXTRA_EXTENSION)
val progressDialog = dialogBuilder.newProgressDialog() val progressDialog = dialogBuilder.newProgressDialog().apply {
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER) setProgressStyle(ProgressDialog.STYLE_SPINNER)
progressDialog.setCancelable(false) setCancelable(false)
progressDialog.isIndeterminate = true isIndeterminate = true
}
progressDialog.show() progressDialog.show()
isCancelable = false isCancelable = false
when (extension) { when (extension) {

@ -119,19 +119,17 @@ class NewFilterDialog : DialogFragment() {
dismiss() dismiss()
} }
private fun newMultiSelect(criteria: CustomFilterCriterion, index: Int, type: Int): CriterionInstance { private fun newMultiSelect(criteria: CustomFilterCriterion, index: Int, type: Int): CriterionInstance =
val criterion = CriterionInstance() CriterionInstance().apply {
criterion.criterion = criteria criterion = criteria
criterion.selectedIndex = index selectedIndex = index
criterion.type = type this.type = type
return criterion
} }
private fun newText(criteria: CustomFilterCriterion, text: String, type: Int): CriterionInstance { private fun newText(criteria: CustomFilterCriterion, text: String, type: Int): CriterionInstance =
val criterion = CriterionInstance() CriterionInstance().apply {
criterion.criterion = criteria criterion = criteria
criterion.selectedText = text selectedText = text
criterion.type = type this.type = type
return criterion
} }
} }

@ -39,8 +39,7 @@ class DriveInvoker(
suspend fun delete(file: File) { suspend fun delete(file: File) {
try { try {
execute(service.files().delete(file.id)) execute(service.files().delete(file.id))
} catch (ignored: HttpNotFoundException) { } catch (ignored: HttpNotFoundException) {}
}
} }
@Throws(IOException::class) @Throws(IOException::class)

@ -80,9 +80,8 @@ class EtebaseAccountSettingsActivity : BaseCaldavAccountSettingsActivity(), Tool
binding.urlLayout.visibility = if (binding.showAdvanced.isChecked) View.VISIBLE else View.GONE binding.urlLayout.visibility = if (binding.showAdvanced.isChecked) View.VISIBLE else View.GONE
} }
override fun needsValidation(): Boolean { override fun needsValidation(): Boolean =
return super.needsValidation() || isNullOrEmpty(caldavAccount!!.encryptionKey) super.needsValidation() || isNullOrEmpty(caldavAccount!!.encryptionKey)
}
override suspend fun addAccount(url: String, username: String, password: String) = override suspend fun addAccount(url: String, username: String, password: String) =
addAccountViewModel.addAccount(url, username, password) addAccountViewModel.addAccount(url, username, password)

@ -83,9 +83,9 @@ class EtebaseClient(
} }
} }
private fun updateMtime(meta: ItemMetadata, mtime: Long = currentTimeMillis()): ItemMetadata { private fun updateMtime(meta: ItemMetadata, mtime: Long = currentTimeMillis()): ItemMetadata =
meta.mtime = mtime meta.also {
return meta it.mtime = mtime
} }
suspend fun updateCache(collection: Collection, items: List<Item>) { suspend fun updateCache(collection: Collection, items: List<Item>) {

@ -35,13 +35,11 @@ class EtebaseClientProvider @Inject constructor(
private val caldavDao: CaldavDao private val caldavDao: CaldavDao
) { ) {
@Throws(NoSuchAlgorithmException::class, KeyManagementException::class) @Throws(NoSuchAlgorithmException::class, KeyManagementException::class)
suspend fun forAccount(account: CaldavAccount): EtebaseClient { suspend fun forAccount(account: CaldavAccount): EtebaseClient = forUrl(
return forUrl(
account.url!!, account.url!!,
account.username!!, account.username!!,
null, null,
account.getPassword(encryption)) account.getPassword(encryption))
}
@Throws(KeyManagementException::class, NoSuchAlgorithmException::class) @Throws(KeyManagementException::class, NoSuchAlgorithmException::class)
suspend fun forUrl(url: String, username: String, password: String?, session: String? = null, foreground: Boolean = false): EtebaseClient = withContext(Dispatchers.IO) { suspend fun forUrl(url: String, username: String, password: String?, session: String? = null, foreground: Boolean = false): EtebaseClient = withContext(Dispatchers.IO) {

@ -86,14 +86,12 @@ class EtebaseSynchronizer @Inject constructor(
calendar.uuid = UUIDHelper.newUUID() calendar.uuid = UUIDHelper.newUUID()
calendar.color = color calendar.color = color
caldavDao.insert(calendar) caldavDao.insert(calendar)
} else { } else if (calendar.name != meta.name || calendar.color != color) {
if (calendar.name != meta.name || calendar.color != color) {
calendar.name = meta.name calendar.name = meta.name
calendar.color = color calendar.color = color
caldavDao.update(calendar) caldavDao.update(calendar)
localBroadcastManager.broadcastRefreshList() localBroadcastManager.broadcastRefreshList()
} }
}
sync(client, calendar, collection) sync(client, calendar, collection)
} }
setError(account, "") setError(account, "")

@ -27,35 +27,36 @@ import java.util.*
object FileHelper { object FileHelper {
const val MAX_FILENAME_LENGTH = 40 const val MAX_FILENAME_LENGTH = 40
fun newFilePickerIntent(activity: Activity?, initial: Uri?, vararg mimeTypes: String?): Intent { fun newFilePickerIntent(activity: Activity?, initial: Uri?, vararg mimeTypes: String?): Intent =
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT) Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
intent.putExtra("android.content.extra.SHOW_ADVANCED", true) putExtra("android.content.extra.SHOW_ADVANCED", true)
intent.putExtra("android.content.extra.FANCY", true) putExtra("android.content.extra.FANCY", true)
intent.putExtra("android.content.extra.SHOW_FILESIZE", true) putExtra("android.content.extra.SHOW_FILESIZE", true)
intent.addCategory(Intent.CATEGORY_OPENABLE) addCategory(Intent.CATEGORY_OPENABLE)
setInitialUri(activity, intent, initial) setInitialUri(activity, this, initial)
if (mimeTypes.size == 1) { if (mimeTypes.size == 1) {
intent.type = mimeTypes[0] type = mimeTypes[0]
} else { } else {
intent.type = "*/*" type = "*/*"
if (mimeTypes.size > 1) { if (mimeTypes.size > 1) {
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes) putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes)
} }
} }
return intent
} }
fun newDirectoryPicker(fragment: Fragment, rc: Int, initial: Uri?) { fun newDirectoryPicker(fragment: Fragment, rc: Int, initial: Uri?) {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE) val intent = Intent(Intent.ACTION_OPEN_DOCUMENT_TREE).apply {
intent.addFlags( addFlags(
Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION
or Intent.FLAG_GRANT_WRITE_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
or Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_READ_URI_PERMISSION
or Intent.FLAG_GRANT_PREFIX_URI_PERMISSION) or Intent.FLAG_GRANT_PREFIX_URI_PERMISSION)
intent.putExtra("android.content.extra.SHOW_ADVANCED", true) putExtra("android.content.extra.SHOW_ADVANCED", true)
intent.putExtra("android.content.extra.FANCY", true) putExtra("android.content.extra.FANCY", true)
intent.putExtra("android.content.extra.SHOW_FILESIZE", true) putExtra("android.content.extra.SHOW_FILESIZE", true)
setInitialUri(fragment.context, intent, initial) setInitialUri(fragment.context, this, initial)
}
fragment.startActivityForResult(intent, rc) fragment.startActivityForResult(intent, rc)
} }
@ -120,9 +121,10 @@ object FileHelper {
} }
} }
val extension = MimeTypeMap.getFileExtensionFromUrl(uri.path) val extension = MimeTypeMap.getFileExtensionFromUrl(uri.path)
return if (!isNullOrEmpty(extension)) { return if (!isNullOrEmpty(extension))
extension extension
} else Files.getFileExtension(getFilename(context, uri)!!) else
Files.getFileExtension(getFilename(context, uri)!!)
} }
fun getMimeType(context: Context, uri: Uri): String? { fun getMimeType(context: Context, uri: Uri): String? {
@ -179,8 +181,7 @@ object FileHelper {
return copyToUri(context, destination, input, Files.getNameWithoutExtension(filename!!)) return copyToUri(context, destination, input, Files.getNameWithoutExtension(filename!!))
} }
fun copyToUri(context: Context, destination: Uri, input: Uri, basename: String): Uri { fun copyToUri(context: Context, destination: Uri, input: Uri, basename: String): Uri = try {
return try {
val output = newFile( val output = newFile(
context, context,
destination, destination,
@ -192,7 +193,6 @@ object FileHelper {
} catch (e: IOException) { } catch (e: IOException) {
throw IllegalStateException(e) throw IllegalStateException(e)
} }
}
fun copyStream(context: Context, input: Uri?, output: Uri?) { fun copyStream(context: Context, input: Uri?, output: Uri?) {
val contentResolver = context.contentResolver val contentResolver = context.contentResolver
@ -245,8 +245,9 @@ object FileHelper {
if (uri == null) { if (uri == null) {
return "" return ""
} }
return if (uri.scheme == ContentResolver.SCHEME_FILE) { return if (uri.scheme == ContentResolver.SCHEME_FILE)
File(uri.path).absolutePath File(uri.path).absolutePath
} else uri.toString() else
uri.toString()
} }
} }

@ -41,9 +41,7 @@ import java.util.*
* Collections.sort(your list, new AlphanumComparator()); * Collections.sort(your list, new AlphanumComparator());
*/ */
class AlphanumComparator<T>(private val getTitle: (T) -> String?) : Comparator<T> { class AlphanumComparator<T>(private val getTitle: (T) -> String?) : Comparator<T> {
private fun isDigit(ch: Char): Boolean { private fun isDigit(ch: Char): Boolean = ch.toInt() in 48..57
return ch.toInt() in 48..57
}
/** Length of string is passed in for improved efficiency (only need to calculate it once) * */ /** Length of string is passed in for improved efficiency (only need to calculate it once) * */
private fun getChunk(s: String, slength: Int, marker: Int): String { private fun getChunk(s: String, slength: Int, marker: Int): String {

@ -24,8 +24,7 @@ class FilterCriteriaProvider @Inject constructor(
private val caldavDao: CaldavDao) { private val caldavDao: CaldavDao) {
private val r = context.resources private val r = context.resources
suspend fun getFilterCriteria(identifier: String): CustomFilterCriterion { suspend fun getFilterCriteria(identifier: String): CustomFilterCriterion = when (identifier) {
return when (identifier) {
IDENTIFIER_UNIVERSE -> startingUniverse IDENTIFIER_UNIVERSE -> startingUniverse
IDENTIFIER_TITLE -> taskTitleContainsFilter IDENTIFIER_TITLE -> taskTitleContainsFilter
IDENTIFIER_IMPORTANCE -> priorityFilter IDENTIFIER_IMPORTANCE -> priorityFilter
@ -41,7 +40,6 @@ class FilterCriteriaProvider @Inject constructor(
IDENTIFIER_SUBTASK -> subtaskFilter IDENTIFIER_SUBTASK -> subtaskFilter
else -> throw RuntimeException("Unknown identifier: $identifier") else -> throw RuntimeException("Unknown identifier: $identifier")
} }
}
val startingUniverse: CustomFilterCriterion val startingUniverse: CustomFilterCriterion
get() = MultipleSelectCriterion( get() = MultipleSelectCriterion(
@ -55,20 +53,22 @@ class FilterCriteriaProvider @Inject constructor(
suspend fun all(): List<CustomFilterCriterion> { suspend fun all(): List<CustomFilterCriterion> {
val result: MutableList<CustomFilterCriterion> = ArrayList() val result: MutableList<CustomFilterCriterion> = ArrayList()
result.add(tagFilter()) with(result) {
result.add(tagNameContainsFilter) add(tagFilter())
result.add(dueDateFilter) add(tagNameContainsFilter)
result.add(priorityFilter) add(dueDateFilter)
result.add(taskTitleContainsFilter) add(priorityFilter)
add(taskTitleContainsFilter)
if (googleTaskListDao.getAccounts().isNotEmpty()) { if (googleTaskListDao.getAccounts().isNotEmpty()) {
result.add(gtasksFilterCriteria()) add(gtasksFilterCriteria())
}
add(caldavFilterCriteria())
add(recurringFilter)
add(completedFilter)
add(hiddenFilter)
add(parentFilter)
add(subtaskFilter)
} }
result.add(caldavFilterCriteria())
result.add(recurringFilter)
result.add(completedFilter)
result.add(hiddenFilter)
result.add(parentFilter)
result.add(subtaskFilter)
return result return result
} }

@ -197,9 +197,8 @@ class FilterProvider @Inject constructor(
Intent(context, HelpAndFeedback::class.java), Intent(context, HelpAndFeedback::class.java),
0)) 0))
private suspend fun googleTaskFilters(showCreate: Boolean = true): List<FilterListItem> { private suspend fun googleTaskFilters(showCreate: Boolean = true): List<FilterListItem> =
return googleTaskListDao.getAccounts().flatMap { googleTaskFilter(it, showCreate) } googleTaskListDao.getAccounts().flatMap { googleTaskFilter(it, showCreate) }
}
private suspend fun googleTaskFilter(account: GoogleTaskAccount, showCreate: Boolean): List<FilterListItem> = private suspend fun googleTaskFilter(account: GoogleTaskAccount, showCreate: Boolean): List<FilterListItem> =
listOf( listOf(
@ -275,12 +274,12 @@ class FilterProvider @Inject constructor(
} }
private suspend fun <T> Collection<T>.plusAllIf(predicate: Boolean, item: suspend () -> Iterable<T>): List<T> = private suspend fun <T> Collection<T>.plusAllIf(predicate: Boolean, item: suspend () -> Iterable<T>): List<T> =
plus(if (predicate) item.invoke() else emptyList()) plus(if (predicate) item() else emptyList())
private fun <T> Iterable<T>.plusIf(predicate: Boolean, item: () -> T): List<T> = private fun <T> Iterable<T>.plusIf(predicate: Boolean, item: () -> T): List<T> =
if (predicate) plus(item.invoke()) else this.toList() if (predicate) plus(item()) else toList()
private fun <T> Iterable<T>.filterIf(predicate: Boolean, predicate2: (T) -> Boolean): List<T> = private fun <T> Iterable<T>.filterIf(predicate: Boolean, predicate2: (T) -> Boolean): List<T> =
if (predicate) filter(predicate2) else this.toList() if (predicate) filter(predicate2) else toList()
} }
} }

@ -15,23 +15,18 @@ class NotificationsFilter : Filter {
private constructor() private constructor()
override fun supportsHiddenTasks(): Boolean { override fun supportsHiddenTasks(): Boolean = false
return false
}
companion object { companion object {
@JvmField val CREATOR: Parcelable.Creator<NotificationsFilter> = object : Parcelable.Creator<NotificationsFilter> { @JvmField val CREATOR: Parcelable.Creator<NotificationsFilter> = object : Parcelable.Creator<NotificationsFilter> {
/** {@inheritDoc} */ /** {@inheritDoc} */
override fun createFromParcel(source: Parcel): NotificationsFilter { override fun createFromParcel(source: Parcel): NotificationsFilter =
val item = NotificationsFilter() NotificationsFilter().apply {
item.readFromParcel(source) readFromParcel(source)
return item
} }
/** {@inheritDoc} */ /** {@inheritDoc} */
override fun newArray(size: Int): Array<NotificationsFilter?> { override fun newArray(size: Int): Array<NotificationsFilter?> = arrayOfNulls(size)
return arrayOfNulls(size)
}
} }
private val queryTemplate: QueryTemplate private val queryTemplate: QueryTemplate

@ -39,8 +39,7 @@ class TaskEditControlSetFragmentManager @Inject constructor(
return fragments return fragments
} }
private fun createFragment(fragmentId: Int): TaskEditControlFragment { private fun createFragment(fragmentId: Int): TaskEditControlFragment = when (fragmentId) {
return when (fragmentId) {
DeadlineControlSet.TAG -> DeadlineControlSet() DeadlineControlSet.TAG -> DeadlineControlSet()
PriorityControlSet.TAG -> PriorityControlSet() PriorityControlSet.TAG -> PriorityControlSet()
DescriptionControlSet.TAG -> DescriptionControlSet() DescriptionControlSet.TAG -> DescriptionControlSet()
@ -57,7 +56,6 @@ class TaskEditControlSetFragmentManager @Inject constructor(
SubtaskControlSet.TAG -> SubtaskControlSet() SubtaskControlSet.TAG -> SubtaskControlSet()
else -> throw RuntimeException("Unsupported fragment") else -> throw RuntimeException("Unsupported fragment")
} }
}
init { init {
displayOrder = BeastModePreferences.constructOrderedControlList(preferences, context) displayOrder = BeastModePreferences.constructOrderedControlList(preferences, context)

@ -45,9 +45,7 @@ class GoogleAccountManager @Inject constructor(
accountList.find { name.equals(it.name, ignoreCase = true) } accountList.find { name.equals(it.name, ignoreCase = true) }
} }
fun canAccessAccount(name: String): Boolean { fun canAccessAccount(name: String): Boolean = getAccount(name) != null
return getAccount(name) != null
}
suspend fun getAccessToken(name: String?, scope: String): String? { suspend fun getAccessToken(name: String?, scope: String): String? {
val account = name?.let { getAccount(it) } val account = name?.let { getAccount(it) }
@ -74,13 +72,11 @@ class GoogleAccountManager @Inject constructor(
} }
} }
suspend fun getTasksAuthToken(activity: Activity, accountName: String): Bundle? { suspend fun getTasksAuthToken(activity: Activity, accountName: String): Bundle? =
return getToken(TasksScopes.TASKS, activity, accountName) getToken(TasksScopes.TASKS, activity, accountName)
}
suspend fun getDriveAuthToken(activity: Activity, accountName: String): Bundle? { suspend fun getDriveAuthToken(activity: Activity, accountName: String): Bundle? =
return getToken(DriveScopes.DRIVE_FILE, activity, accountName) getToken(DriveScopes.DRIVE_FILE, activity, accountName)
}
@SuppressLint("CheckResult") @SuppressLint("CheckResult")
private suspend fun getToken(scope: String, activity: Activity, accountName: String): Bundle? { private suspend fun getToken(scope: String, activity: Activity, accountName: String): Bundle? {

@ -395,14 +395,12 @@ class GoogleTaskSynchronizer @Inject constructor(
} }
} }
fun truncate(string: String?, max: Int): String? { fun truncate(string: String?, max: Int): String? =
return if (string == null || string.length <= max) string else string.substring(0, max) if (string == null || string.length <= max) string else string.substring(0, max)
}
fun getTruncatedValue(currentValue: String?, newValue: String?, maxLength: Int): String? { fun getTruncatedValue(currentValue: String?, newValue: String?, maxLength: Int): String? =
return if (isNullOrEmpty(newValue) if (isNullOrEmpty(newValue)
|| newValue!!.length < maxLength || isNullOrEmpty(currentValue) || newValue!!.length < maxLength || isNullOrEmpty(currentValue)
|| !currentValue!!.startsWith(newValue)) newValue else currentValue || !currentValue!!.startsWith(newValue)) newValue else currentValue
} }
}
} }

@ -100,7 +100,6 @@ abstract class InjectingPreferenceFragment : PreferenceFragmentCompat() {
requireActivity().recreate() requireActivity().recreate()
} }
protected fun findPreference(@StringRes prefId: Int): Preference { protected fun findPreference(@StringRes prefId: Int): Preference =
return findPreference(getString(prefId))!! findPreference(getString(prefId))!!
}
} }

@ -44,7 +44,6 @@ internal class ProductionModule {
googleTaskListDao: GoogleTaskListDao, googleTaskListDao: GoogleTaskListDao,
caldavDao: CaldavDao, caldavDao: CaldavDao,
openTaskDao: OpenTaskDao openTaskDao: OpenTaskDao
): WorkManager { ): WorkManager =
return WorkManagerImpl(context, preferences, googleTaskListDao, caldavDao, openTaskDao) WorkManagerImpl(context, preferences, googleTaskListDao, caldavDao, openTaskDao)
}
} }

@ -50,11 +50,9 @@ class NotificationQueue @Inject constructor(private val preferences: Preferences
@get:Synchronized @get:Synchronized
val overdueJobs: List<NotificationQueueEntry> val overdueJobs: List<NotificationQueueEntry>
get() { get() = jobs.keySet()
return jobs.keySet()
.headSet(DateTime().startOfMinute().plusMinutes(1).millis) .headSet(DateTime().startOfMinute().plusMinutes(1).millis)
.flatMap { jobs[it] } .flatMap { jobs[it] }
}
@Synchronized @Synchronized
fun scheduleNext() = scheduleNext(false) fun scheduleNext() = scheduleNext(false)

@ -37,8 +37,7 @@ class LocalePickerDialog : DialogFragment() {
companion object { companion object {
const val EXTRA_LOCALE = "extra_locale" const val EXTRA_LOCALE = "extra_locale"
fun newLocalePickerDialog(): LocalePickerDialog {
return LocalePickerDialog() fun newLocalePickerDialog(): LocalePickerDialog = LocalePickerDialog()
}
} }
} }

@ -92,10 +92,8 @@ class LocationPermissionDialog : DialogFragment() {
fun newLocationPermissionDialog( fun newLocationPermissionDialog(
targetFragment: Fragment, targetFragment: Fragment,
rc: Int rc: Int
): LocationPermissionDialog { ): LocationPermissionDialog = LocationPermissionDialog().apply {
val dialog = LocationPermissionDialog() setTargetFragment(targetFragment, rc)
dialog.setTargetFragment(targetFragment, rc)
return dialog
} }
} }
} }

@ -205,9 +205,7 @@ class LocationPickerActivity : InjectingAppCompatActivity(), Toolbar.OnMenuItemC
super.onBackPressed() super.onBackPressed()
} }
private fun closeSearch(): Boolean { private fun closeSearch(): Boolean = search.isActionViewExpanded && search.collapseActionView()
return search.isActionViewExpanded && search.collapseActionView()
}
override fun onPlaceSelected(place: Place) { override fun onPlaceSelected(place: Place) {
returnPlace(place) returnPlace(place)
@ -356,14 +354,11 @@ class LocationPickerActivity : InjectingAppCompatActivity(), Toolbar.OnMenuItemC
viewModel.saveState(outState) viewModel.saveState(outState)
} }
override fun onMenuItemClick(item: MenuItem): Boolean { override fun onMenuItemClick(item: MenuItem): Boolean =
return if (item.itemId == R.id.menu_search) { if (item.itemId == R.id.menu_search) {
searchPlace() searchPlace()
true true
} else { } else false
false
}
}
override fun picked(place: Place) { override fun picked(place: Place) {
returnPlace(place) returnPlace(place)
@ -375,9 +370,7 @@ class LocationPickerActivity : InjectingAppCompatActivity(), Toolbar.OnMenuItemC
startActivity(intent) startActivity(intent)
} }
override fun onQueryTextSubmit(query: String): Boolean { override fun onQueryTextSubmit(query: String): Boolean = false
return false
}
override fun onQueryTextChange(query: String): Boolean { override fun onQueryTextChange(query: String): Boolean {
searchSubject.onNext(query) searchSubject.onNext(query)

@ -24,9 +24,8 @@ class Notification {
@ColumnInfo(name = "location") @ColumnInfo(name = "location")
var location: Long? = null var location: Long? = null
override fun toString(): String { override fun toString(): String =
return "Notification(uid=$uid, taskId=$taskId, timestamp=$timestamp, type=$type, location=$location)" "Notification(uid=$uid, taskId=$taskId, timestamp=$timestamp, type=$type, location=$location)"
}
companion object { companion object {
const val TABLE_NAME = "notification" const val TABLE_NAME = "notification"

@ -99,13 +99,14 @@ class NotificationManager @Inject constructor(
val existingNotifications = notificationDao.getAllOrdered() val existingNotifications = notificationDao.getAllOrdered()
notificationDao.insertAll(newNotifications) notificationDao.insertAll(newNotifications)
val totalCount = existingNotifications.size + newNotifications.size val totalCount = existingNotifications.size + newNotifications.size
if (totalCount == 0) { when {
cancelSummaryNotification() totalCount == 0 -> cancelSummaryNotification()
} else if (totalCount == 1) { totalCount == 1 -> {
val notifications = existingNotifications + newNotifications val notifications = existingNotifications + newNotifications
createNotifications(notifications, alert, nonstop, fiveTimes, false) createNotifications(notifications, alert, nonstop, fiveTimes, false)
cancelSummaryNotification() cancelSummaryNotification()
} else if (preferences.bundleNotifications()) { }
preferences.bundleNotifications() -> {
updateSummary( updateSummary(
notify = false, notify = false,
nonStop = false, nonStop = false,
@ -130,8 +131,8 @@ class NotificationManager @Inject constructor(
useGroupKey = true) useGroupKey = true)
updateSummary(alert, nonstop, fiveTimes, newNotifications) updateSummary(alert, nonstop, fiveTimes, newNotifications)
} }
} else { }
createNotifications(newNotifications, alert, nonstop, fiveTimes, false) else -> createNotifications(newNotifications, alert, nonstop, fiveTimes, false)
} }
localBroadcastManager.broadcastRefresh() localBroadcastManager.broadcastRefresh()
} }

@ -230,9 +230,7 @@ class OpenTasksSynchronizer @Inject constructor(
rrule.recur.until = DateTime(task.repeatUntil).toUTC().toDateTime() rrule.recur.until = DateTime(task.repeatUntil).toUTC().toDateTime()
} }
RRule(rrule.value.sanitizeRRule()).value RRule(rrule.value.sanitizeRRule()).value
} else { } else null)
null
})
values.put(Tasks.IS_ALLDAY, if (task.hasDueDate() && !task.hasDueTime()) 1 else 0) values.put(Tasks.IS_ALLDAY, if (task.hasDueDate() && !task.hasDueTime()) 1 else 0)
values.put(Tasks.DUE, when { values.put(Tasks.DUE, when {
task.hasDueTime() -> newDateTime(task.dueDate).toDateTime().time task.hasDueTime() -> newDateTime(task.dueDate).toDateTime().time
@ -245,9 +243,7 @@ class OpenTasksSynchronizer @Inject constructor(
values.put(Tasks.PERCENT_COMPLETE, if (task.isCompleted) 100 else null) values.put(Tasks.PERCENT_COMPLETE, if (task.isCompleted) 100 else null)
values.put(Tasks.TZ, if (task.hasDueTime() || task.isCompleted) { values.put(Tasks.TZ, if (task.hasDueTime() || task.isCompleted) {
TimeZone.getDefault().id TimeZone.getDefault().id
} else { } else null)
null
})
values.put(Tasks.PARENT_ID, null as Long?) values.put(Tasks.PARENT_ID, null as Long?)
val existing = cr.query( val existing = cr.query(
Tasks.getContentUri(openTaskDao.authority), Tasks.getContentUri(openTaskDao.authority),

@ -52,7 +52,7 @@ abstract class BasePreferences : ThemedInjectingAppCompatActivity(),
private fun setupMenu() = setupMenu(supportFragmentManager.findFragmentById(R.id.settings)) private fun setupMenu() = setupMenu(supportFragmentManager.findFragmentById(R.id.settings))
private fun setupMenu(fragment: Fragment?) { private fun setupMenu(fragment: Fragment?) {
this.menu = if (fragment is InjectingPreferenceFragment) fragment.getMenu() else 0 menu = if (fragment is InjectingPreferenceFragment) fragment.getMenu() else 0
toolbar.menu.clear() toolbar.menu.clear()
if (menu > 0) { if (menu > 0) {
toolbar.inflateMenu(menu) toolbar.inflateMenu(menu)
@ -79,8 +79,7 @@ abstract class BasePreferences : ThemedInjectingAppCompatActivity(),
override fun onPreferenceStartFragment( override fun onPreferenceStartFragment(
caller: PreferenceFragmentCompat, caller: PreferenceFragmentCompat,
pref: Preference pref: Preference
): Boolean { ): Boolean = startPreference(
return startPreference(
caller, caller,
supportFragmentManager supportFragmentManager
.fragmentFactory .fragmentFactory
@ -88,7 +87,6 @@ abstract class BasePreferences : ThemedInjectingAppCompatActivity(),
.apply { arguments = pref.extras }, .apply { arguments = pref.extras },
pref.title pref.title
) )
}
fun startPreference( fun startPreference(
caller: PreferenceFragmentCompat, caller: PreferenceFragmentCompat,
@ -105,12 +103,9 @@ abstract class BasePreferences : ThemedInjectingAppCompatActivity(),
return true return true
} }
override fun onMenuItemClick(item: MenuItem?): Boolean { override fun onMenuItemClick(item: MenuItem?): Boolean =
return if (item?.itemId == R.id.menu_help_and_feedback) { if (item?.itemId == R.id.menu_help_and_feedback) {
startActivity(Intent(this, HelpAndFeedback::class.java)) startActivity(Intent(this, HelpAndFeedback::class.java))
true true
} else { } else false
false
}
}
} }

@ -56,13 +56,12 @@ class DefaultFilterProvider @Inject constructor(
fun setDefaultOpenFilter(filter: Filter) = fun setDefaultOpenFilter(filter: Filter) =
setFilterPreference(filter, R.string.p_default_open_filter) setFilterPreference(filter, R.string.p_default_open_filter)
suspend fun getStartupFilter(): Filter { suspend fun getStartupFilter(): Filter =
return if (preferences.getBoolean(R.string.p_open_last_viewed_list, true)) { if (preferences.getBoolean(R.string.p_open_last_viewed_list, true)) {
getLastViewedFilter() getLastViewedFilter()
} else { } else {
getDefaultOpenFilter() getDefaultOpenFilter()
} }
}
@Deprecated("use coroutines") @Deprecated("use coroutines")
fun getFilterFromPreferenceBlocking(prefString: String?) = runBlocking { fun getFilterFromPreferenceBlocking(prefString: String?) = runBlocking {

@ -48,27 +48,24 @@ class MainPreferences : BasePreferences() {
} }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_CALDAV_SETTINGS) { when (requestCode) {
if (resultCode == RESULT_OK) { REQUEST_CALDAV_SETTINGS -> if (resultCode == RESULT_OK) {
syncAdapters.sync(true) syncAdapters.sync(true)
workManager.updateBackgroundSync() workManager.updateBackgroundSync()
} }
} else if (requestCode == REQUEST_GOOGLE_TASKS) { REQUEST_GOOGLE_TASKS -> if (resultCode == Activity.RESULT_OK) {
if (resultCode == Activity.RESULT_OK) {
syncAdapters.sync(true) syncAdapters.sync(true)
workManager.updateBackgroundSync() workManager.updateBackgroundSync()
} else { } else {
data?.getStringExtra(GtasksLoginActivity.EXTRA_ERROR)?.let { toaster.longToast(it) } data?.getStringExtra(GtasksLoginActivity.EXTRA_ERROR)?.let { toaster.longToast(it) }
} }
} else if (requestCode == REQUEST_TASKS_ORG) { REQUEST_TASKS_ORG -> if (resultCode == Activity.RESULT_OK) {
if (resultCode == Activity.RESULT_OK) {
syncAdapters.sync(true) syncAdapters.sync(true)
workManager.updateBackgroundSync() workManager.updateBackgroundSync()
} else { } else {
data?.getStringExtra(SignInActivity.EXTRA_ERROR)?.let { toaster.longToast(it) } data?.getStringExtra(SignInActivity.EXTRA_ERROR)?.let { toaster.longToast(it) }
} }
} else { else -> super.onActivityResult(requestCode, resultCode, data)
super.onActivityResult(requestCode, resultCode, data)
} }
} }

@ -41,13 +41,9 @@ class Preferences @JvmOverloads constructor(
fun showBackupWarnings() = !getBoolean(R.string.p_backups_ignore_warnings, false) fun showBackupWarnings() = !getBoolean(R.string.p_backups_ignore_warnings, false)
fun addTasksToTop(): Boolean { fun addTasksToTop(): Boolean = getBoolean(R.string.p_add_to_top, true)
return getBoolean(R.string.p_add_to_top, true)
}
fun backButtonSavesTask(): Boolean { fun backButtonSavesTask(): Boolean = getBoolean(R.string.p_back_button_saves_task, false)
return getBoolean(R.string.p_back_button_saves_task, false)
}
val isCurrentlyQuietHours: Boolean val isCurrentlyQuietHours: Boolean
get() { get() {
@ -84,9 +80,7 @@ class Preferences @JvmOverloads constructor(
return time return time
} }
private fun quietHoursEnabled(): Boolean { private fun quietHoursEnabled(): Boolean = getBoolean(R.string.p_rmd_enable_quiet, false)
return getBoolean(R.string.p_rmd_enable_quiet, false)
}
val defaultDueTime: Int val defaultDueTime: Int
get() = getInt(R.string.p_rmd_time, TimeUnit.HOURS.toMillis(18).toInt()) get() = getInt(R.string.p_rmd_time, TimeUnit.HOURS.toMillis(18).toInt())
@ -190,13 +184,10 @@ class Preferences @JvmOverloads constructor(
setDefaults() setDefaults()
} }
fun getStringValue(key: String?): String? { fun getStringValue(key: String?): String? = prefs.getString(key, null)
return prefs.getString(key, null)
}
fun getStringValue(keyResource: Int): String? { fun getStringValue(keyResource: Int): String? =
return prefs.getString(context.getString(keyResource), null) prefs.getString(context.getString(keyResource), null)
}
val defaultReminders: Int val defaultReminders: Int
get() = getIntegerFromString( get() = getIntegerFromString(
@ -251,18 +242,15 @@ class Preferences @JvmOverloads constructor(
editor.apply() editor.apply()
} }
fun getBoolean(key: String?, defValue: Boolean): Boolean { fun getBoolean(key: String?, defValue: Boolean): Boolean = try {
return try {
prefs.getBoolean(key, defValue) prefs.getBoolean(key, defValue)
} catch (e: ClassCastException) { } catch (e: ClassCastException) {
Timber.e(e) Timber.e(e)
defValue defValue
} }
}
fun getBoolean(keyResources: Int, defValue: Boolean): Boolean { fun getBoolean(keyResources: Int, defValue: Boolean): Boolean =
return getBoolean(context.getString(keyResources), defValue) getBoolean(context.getString(keyResources), defValue)
}
fun setBoolean(keyResource: Int, value: Boolean) { fun setBoolean(keyResource: Int, value: Boolean) {
setBoolean(context.getString(keyResource), value) setBoolean(context.getString(keyResource), value)
@ -274,13 +262,10 @@ class Preferences @JvmOverloads constructor(
editor.apply() editor.apply()
} }
fun getInt(resourceId: Int, defValue: Int): Int { fun getInt(resourceId: Int, defValue: Int): Int =
return getInt(context.getString(resourceId), defValue) getInt(context.getString(resourceId), defValue)
}
fun getInt(key: String?, defValue: Int): Int { fun getInt(key: String?, defValue: Int): Int = prefs.getInt(key, defValue)
return prefs.getInt(key, defValue)
}
fun setInt(resourceId: Int, value: Int) { fun setInt(resourceId: Int, value: Int) {
setInt(context.getString(resourceId), value) setInt(context.getString(resourceId), value)
@ -292,13 +277,10 @@ class Preferences @JvmOverloads constructor(
editor.apply() editor.apply()
} }
fun getLong(resourceId: Int, defValue: Long): Long { fun getLong(resourceId: Int, defValue: Long): Long =
return getLong(context.getString(resourceId), defValue) getLong(context.getString(resourceId), defValue)
}
fun getLong(key: String?, defValue: Long): Long { fun getLong(key: String?, defValue: Long): Long = prefs.getLong(key, defValue)
return prefs.getLong(key, defValue)
}
fun setLong(resourceId: Int, value: Long) { fun setLong(resourceId: Int, value: Long) {
setLong(context.getString(resourceId), value) setLong(context.getString(resourceId), value)
@ -404,14 +386,13 @@ class Preferences @JvmOverloads constructor(
return DocumentFile.fromFile(cacheDir!!).uri return DocumentFile.fromFile(cacheDir!!).uri
} }
private fun hasWritePermission(context: Context, uri: Uri): Boolean { private fun hasWritePermission(context: Context, uri: Uri): Boolean =
return (PackageManager.PERMISSION_GRANTED (PackageManager.PERMISSION_GRANTED
== context.checkUriPermission( == context.checkUriPermission(
uri, uri,
Binder.getCallingPid(), Binder.getCallingPid(),
Binder.getCallingUid(), Binder.getCallingUid(),
Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)) Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION))
}
val notificationDefaults: Int val notificationDefaults: Int
get() { get() {
@ -431,13 +412,9 @@ class Preferences @JvmOverloads constructor(
editor.apply() editor.apply()
} }
fun bundleNotifications(): Boolean { fun bundleNotifications(): Boolean = getBoolean(R.string.p_bundle_notifications, true)
return getBoolean(R.string.p_bundle_notifications, true)
}
fun usePersistentReminders(): Boolean { fun usePersistentReminders(): Boolean = getBoolean(R.string.p_rmd_persistent, true)
return getBoolean(R.string.p_rmd_persistent, true)
}
var isSyncOngoing: Boolean var isSyncOngoing: Boolean
get() = syncFlags.any { getBoolean(it, false) } get() = syncFlags.any { getBoolean(it, false) }
@ -445,9 +422,7 @@ class Preferences @JvmOverloads constructor(
syncFlags.forEach { setBoolean(it, value) } syncFlags.forEach { setBoolean(it, value) }
} }
fun useGooglePlaces(): Boolean { fun useGooglePlaces(): Boolean = getInt(R.string.p_place_provider, 0) == 1
return getInt(R.string.p_place_provider, 0) == 1
}
fun <T> getPrefs(c: Class<T>): Map<String, T> { fun <T> getPrefs(c: Class<T>): Map<String, T> {
val result: MutableMap<String, T> = HashMap() val result: MutableMap<String, T> = HashMap()
@ -498,9 +473,8 @@ class Preferences @JvmOverloads constructor(
get() = getBoolean(R.string.p_tag_chips, true) get() = getBoolean(R.string.p_tag_chips, true)
set(value) = setBoolean(R.string.p_tag_chips, value) set(value) = setBoolean(R.string.p_tag_chips, value)
fun alreadyNotified(account: String?, scope: String?): Boolean { fun alreadyNotified(account: String?, scope: String?): Boolean =
return getBoolean(context.getString(R.string.p_notified_oauth_error, account, scope), false) getBoolean(context.getString(R.string.p_notified_oauth_error, account, scope), false)
}
fun setAlreadyNotified(account: String?, scope: String?, value: Boolean) { fun setAlreadyNotified(account: String?, scope: String?, value: Boolean) {
setBoolean(context.getString(R.string.p_notified_oauth_error, account, scope), value) setBoolean(context.getString(R.string.p_notified_oauth_error, account, scope), value)
@ -509,19 +483,17 @@ class Preferences @JvmOverloads constructor(
val defaultThemeColor: Int val defaultThemeColor: Int
get() = getInt(R.string.p_theme_color, ColorProvider.BLUE_500) get() = getInt(R.string.p_theme_color, ColorProvider.BLUE_500)
override fun usePagedQueries(): Boolean { override fun usePagedQueries(): Boolean = getBoolean(R.string.p_use_paged_queries, false)
return getBoolean(R.string.p_use_paged_queries, false)
}
fun showGroupHeaders(): Boolean { fun showGroupHeaders(): Boolean =
return !usePagedQueries() && !getBoolean(R.string.p_disable_sort_groups, false) !usePagedQueries() && !getBoolean(R.string.p_disable_sort_groups, false)
}
companion object { companion object {
private const val PREF_SORT_SORT = "sort_sort" // $NON-NLS-1$ private const val PREF_SORT_SORT = "sort_sort" // $NON-NLS-1$
private fun getSharedPreferencesName(context: Context): String {
return context.packageName + "_preferences" private fun getSharedPreferencesName(context: Context): String =
} context.packageName + "_preferences"
private val syncFlags = listOf( private val syncFlags = listOf(
R.string.p_sync_ongoing_google_tasks, R.string.p_sync_ongoing_google_tasks,
R.string.p_sync_ongoing_caldav, R.string.p_sync_ongoing_caldav,

@ -132,40 +132,32 @@ class DateAndTime : InjectingPreferenceFragment(), Preference.OnPreferenceChange
private fun updateStartOfWeek(value: String) { private fun updateStartOfWeek(value: String) {
val preference = getStartOfWeekPreference() val preference = getStartOfWeekPreference()
val index = preference.findIndexOfValue(value) val index = preference.findIndexOfValue(value)
val summary: String? = getWeekdayEntries()?.get(index) val summary: String? = getWeekdayEntries().get(index)
preference.summary = summary preference.summary = summary
} }
private fun getStartOfWeekPreference(): ListPreference { private fun getStartOfWeekPreference(): ListPreference =
return findPreference(R.string.p_start_of_week) as ListPreference findPreference(R.string.p_start_of_week) as ListPreference
}
private fun getWeekdayDisplayName(dayOfWeek: DayOfWeek): String { private fun getWeekdayDisplayName(dayOfWeek: DayOfWeek): String =
return dayOfWeek.getDisplayName(TextStyle.FULL, locale.locale) dayOfWeek.getDisplayName(TextStyle.FULL, locale.locale)
}
private fun getMorningPreference(): TimePreference { private fun getMorningPreference(): TimePreference =
return getTimePreference(R.string.p_date_shortcut_morning) getTimePreference(R.string.p_date_shortcut_morning)
}
private fun getAfternoonPreference(): TimePreference { private fun getAfternoonPreference(): TimePreference =
return getTimePreference(R.string.p_date_shortcut_afternoon) getTimePreference(R.string.p_date_shortcut_afternoon)
}
private fun getEveningPreference(): TimePreference { private fun getEveningPreference(): TimePreference =
return getTimePreference(R.string.p_date_shortcut_evening) getTimePreference(R.string.p_date_shortcut_evening)
}
private fun getNightPreference(): TimePreference { private fun getNightPreference(): TimePreference =
return getTimePreference(R.string.p_date_shortcut_night) getTimePreference(R.string.p_date_shortcut_night)
}
private fun getTimePreference(resId: Int): TimePreference { private fun getTimePreference(resId: Int): TimePreference =
return findPreference(resId) as TimePreference findPreference(resId) as TimePreference
}
private fun getWeekdayEntries(): Array<String?>? { private fun getWeekdayEntries(): Array<String?> = arrayOf(
return arrayOf(
getString(R.string.use_locale_default), getString(R.string.use_locale_default),
getWeekdayDisplayName(DayOfWeek.SUNDAY), getWeekdayDisplayName(DayOfWeek.SUNDAY),
getWeekdayDisplayName(DayOfWeek.MONDAY), getWeekdayDisplayName(DayOfWeek.MONDAY),
@ -175,5 +167,4 @@ class DateAndTime : InjectingPreferenceFragment(), Preference.OnPreferenceChange
getWeekdayDisplayName(DayOfWeek.FRIDAY), getWeekdayDisplayName(DayOfWeek.FRIDAY),
getWeekdayDisplayName(DayOfWeek.SATURDAY) getWeekdayDisplayName(DayOfWeek.SATURDAY)
) )
}
} }

@ -209,12 +209,13 @@ class LookAndFeel : InjectingPreferenceFragment() {
placeProviderPreference.summary = choices[placeProvider] placeProviderPreference.summary = choices[placeProvider]
} }
private fun getPlaceProvider(): Int { private fun getPlaceProvider(): Int =
return if (playServices.isPlayServicesAvailable && inventory.hasPro) preferences.getInt( if (playServices.isPlayServicesAvailable && inventory.hasPro)
preferences.getInt(
R.string.p_place_provider, R.string.p_place_provider,
0 0
) else 0 )
} else 0
private fun setBaseTheme(index: Int) { private fun setBaseTheme(index: Int) {
activity?.intent?.removeExtra(EXTRA_THEME_OVERRIDE) activity?.intent?.removeExtra(EXTRA_THEME_OVERRIDE)
@ -228,15 +229,15 @@ class LookAndFeel : InjectingPreferenceFragment() {
} }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_PURCHASE) { when (requestCode) {
REQUEST_PURCHASE -> {
val index = if (inventory.hasPro) { val index = if (inventory.hasPro) {
data?.getIntExtra(ThemePickerDialog.EXTRA_SELECTED, DEFAULT_BASE_THEME) data?.getIntExtra(ThemePickerDialog.EXTRA_SELECTED, DEFAULT_BASE_THEME)
?: themeBase.index ?: themeBase.index
} else { } else preferences.themeBase
preferences.themeBase
}
setBaseTheme(index) setBaseTheme(index)
} else if (requestCode == REQUEST_THEME_PICKER) { }
REQUEST_THEME_PICKER -> {
val index = data?.getIntExtra(ThemePickerDialog.EXTRA_SELECTED, DEFAULT_BASE_THEME) val index = data?.getIntExtra(ThemePickerDialog.EXTRA_SELECTED, DEFAULT_BASE_THEME)
?: preferences.themeBase ?: preferences.themeBase
if (resultCode == RESULT_OK) { if (resultCode == RESULT_OK) {
@ -249,19 +250,21 @@ class LookAndFeel : InjectingPreferenceFragment() {
} else { } else {
setBaseTheme(index) setBaseTheme(index)
} }
} else if (requestCode == REQUEST_COLOR_PICKER) { }
REQUEST_COLOR_PICKER -> {
if (resultCode == RESULT_OK) { if (resultCode == RESULT_OK) {
val color = data?.getIntExtra( val color = data?.getIntExtra(
ColorWheelPicker.EXTRA_SELECTED, ColorWheelPicker.EXTRA_SELECTED,
themeColor.primaryColor themeColor.primaryColor
) ) ?: themeColor.primaryColor
?: themeColor.primaryColor
if (preferences.defaultThemeColor != color) { if (preferences.defaultThemeColor != color) {
preferences.setInt(R.string.p_theme_color, color) preferences.setInt(R.string.p_theme_color, color)
recreate() recreate()
} }
} }
} else if (requestCode == REQUEST_ACCENT_PICKER) { }
REQUEST_ACCENT_PICKER -> {
if (resultCode == RESULT_OK) { if (resultCode == RESULT_OK) {
val index = data!!.getIntExtra(ColorPalettePicker.EXTRA_SELECTED, 0) val index = data!!.getIntExtra(ColorPalettePicker.EXTRA_SELECTED, 0)
if (preferences.getInt(R.string.p_theme_accent, -1) != index) { if (preferences.getInt(R.string.p_theme_accent, -1) != index) {
@ -269,14 +272,16 @@ class LookAndFeel : InjectingPreferenceFragment() {
recreate() recreate()
} }
} }
} else if (requestCode == REQUEST_LAUNCHER_PICKER) { }
REQUEST_LAUNCHER_PICKER -> {
if (resultCode == RESULT_OK) { if (resultCode == RESULT_OK) {
val index = data!!.getIntExtra(ColorPalettePicker.EXTRA_SELECTED, 0) val index = data!!.getIntExtra(ColorPalettePicker.EXTRA_SELECTED, 0)
setLauncherIcon(index) setLauncherIcon(index)
preferences.setInt(R.string.p_theme_launcher, index) preferences.setInt(R.string.p_theme_launcher, index)
updateLauncherPreference() updateLauncherPreference()
} }
} else if (requestCode == REQUEST_DEFAULT_LIST) { }
REQUEST_DEFAULT_LIST -> {
if (resultCode == RESULT_OK) { if (resultCode == RESULT_OK) {
val filter: Filter = val filter: Filter =
data!!.getParcelableExtra(FilterSelectionActivity.EXTRA_FILTER)!! data!!.getParcelableExtra(FilterSelectionActivity.EXTRA_FILTER)!!
@ -284,7 +289,8 @@ class LookAndFeel : InjectingPreferenceFragment() {
findPreference(R.string.p_default_open_filter).summary = filter.listingTitle findPreference(R.string.p_default_open_filter).summary = filter.listingTitle
localBroadcastManager.broadcastRefresh() localBroadcastManager.broadcastRefresh()
} }
} else if (requestCode == REQUEST_LOCALE) { }
REQUEST_LOCALE -> {
if (resultCode == RESULT_OK) { if (resultCode == RESULT_OK) {
val newValue: Locale = val newValue: Locale =
data!!.getSerializableExtra(LocalePickerDialog.EXTRA_LOCALE) as Locale data!!.getSerializableExtra(LocalePickerDialog.EXTRA_LOCALE) as Locale
@ -299,10 +305,12 @@ class LookAndFeel : InjectingPreferenceFragment() {
showRestartDialog() showRestartDialog()
} }
} }
} else { }
else -> {
super.onActivityResult(requestCode, resultCode, data) super.onActivityResult(requestCode, resultCode, data)
} }
} }
}
private fun updateLocale() { private fun updateLocale() {
val languagePreference = findPreference(R.string.p_language) val languagePreference = findPreference(R.string.p_language)

@ -172,8 +172,8 @@ class Notifications : InjectingPreferenceFragment() {
return true return true
} }
override fun onPreferenceTreeClick(preference: Preference?): Boolean { override fun onPreferenceTreeClick(preference: Preference?): Boolean =
return if (preference!!.key == getString(R.string.p_rmd_ringtone)) { if (preference!!.key == getString(R.string.p_rmd_ringtone)) {
val intent = Intent(RingtoneManager.ACTION_RINGTONE_PICKER) val intent = Intent(RingtoneManager.ACTION_RINGTONE_PICKER)
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION) intent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION)
intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true) intent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true)
@ -203,23 +203,18 @@ class Notifications : InjectingPreferenceFragment() {
} else { } else {
super.onPreferenceTreeClick(preference) super.onPreferenceTreeClick(preference)
} }
}
private fun getQuietStartPreference(): TimePreference? { private fun getQuietStartPreference(): TimePreference? =
return getTimePreference(R.string.p_rmd_quietStart) getTimePreference(R.string.p_rmd_quietStart)
}
private fun getQuietEndPreference(): TimePreference? { private fun getQuietEndPreference(): TimePreference? =
return getTimePreference(R.string.p_rmd_quietEnd) getTimePreference(R.string.p_rmd_quietEnd)
}
private fun getDefaultRemindTimePreference(): TimePreference? { private fun getDefaultRemindTimePreference(): TimePreference? =
return getTimePreference(R.string.p_rmd_time) getTimePreference(R.string.p_rmd_time)
}
private fun getTimePreference(resId: Int): TimePreference? { private fun getTimePreference(resId: Int): TimePreference? =
return findPreference(getString(resId)) as TimePreference? findPreference(getString(resId)) as TimePreference?
}
private fun initializeTimePreference(preference: TimePreference, requestCode: Int) { private fun initializeTimePreference(preference: TimePreference, requestCode: Int) {
preference.onPreferenceClickListener = Preference.OnPreferenceClickListener { preference.onPreferenceClickListener = Preference.OnPreferenceClickListener {
@ -256,8 +251,8 @@ class Notifications : InjectingPreferenceFragment() {
} }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_CODE_ALERT_RINGTONE) { when (requestCode) {
if (resultCode == RESULT_OK && data != null) { REQUEST_CODE_ALERT_RINGTONE -> if (resultCode == RESULT_OK && data != null) {
val ringtone: Uri? = val ringtone: Uri? =
data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI) data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI)
if (ringtone != null) { if (ringtone != null) {
@ -267,36 +262,30 @@ class Notifications : InjectingPreferenceFragment() {
} }
initializeRingtonePreference() initializeRingtonePreference()
} }
} else if (requestCode == REQUEST_QUIET_START) { REQUEST_QUIET_START -> if (resultCode == RESULT_OK) {
if (resultCode == RESULT_OK) {
getQuietStartPreference()!!.handleTimePickerActivityIntent(data) getQuietStartPreference()!!.handleTimePickerActivityIntent(data)
} }
} else if (requestCode == REQUEST_QUIET_END) { REQUEST_QUIET_END -> if (resultCode == RESULT_OK) {
if (resultCode == RESULT_OK) {
getQuietEndPreference()!!.handleTimePickerActivityIntent(data) getQuietEndPreference()!!.handleTimePickerActivityIntent(data)
} }
} else if (requestCode == REQUEST_DEFAULT_REMIND) { REQUEST_DEFAULT_REMIND -> if (resultCode == RESULT_OK) {
if (resultCode == RESULT_OK) {
getDefaultRemindTimePreference()!!.handleTimePickerActivityIntent(data) getDefaultRemindTimePreference()!!.handleTimePickerActivityIntent(data)
} }
} else if (requestCode == REQUEST_BADGE_LIST) { REQUEST_BADGE_LIST -> if (resultCode == RESULT_OK) {
if (resultCode == RESULT_OK) {
val filter: Filter = val filter: Filter =
data!!.getParcelableExtra(FilterSelectionActivity.EXTRA_FILTER)!! data!!.getParcelableExtra(FilterSelectionActivity.EXTRA_FILTER)!!
defaultFilterProvider.setBadgeFilter(filter) defaultFilterProvider.setBadgeFilter(filter)
findPreference(R.string.p_badge_list).summary = filter.listingTitle findPreference(R.string.p_badge_list).summary = filter.listingTitle
localBroadcastManager.broadcastRefresh() localBroadcastManager.broadcastRefresh()
} }
} else if (requestCode == REQUEST_CODE_TTS_CHECK) { REQUEST_CODE_TTS_CHECK -> if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) { // success, create the TTS instance
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) { // success, create the TTS instance
voiceOutputAssistant.initTTS() voiceOutputAssistant.initTTS()
} else { // missing data, install it } else { // missing data, install it
val installIntent = Intent() val installIntent = Intent()
installIntent.action = TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA installIntent.action = TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA
startActivity(installIntent) startActivity(installIntent)
} }
} else { else -> super.onActivityResult(requestCode, resultCode, data)
super.onActivityResult(requestCode, resultCode, data)
} }
} }
} }

@ -144,15 +144,14 @@ class ScrollableWidget : InjectingPreferenceFragment() {
} }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_FILTER) { when (requestCode) {
if (resultCode == Activity.RESULT_OK) { REQUEST_FILTER -> if (resultCode == Activity.RESULT_OK) {
val filter: Filter = val filter: Filter =
data!!.getParcelableExtra(FilterSelectionActivity.EXTRA_FILTER)!! data!!.getParcelableExtra(FilterSelectionActivity.EXTRA_FILTER)!!
widgetPreferences.setFilter(defaultFilterProvider.getFilterPreferenceValue(filter)) widgetPreferences.setFilter(defaultFilterProvider.getFilterPreferenceValue(filter))
updateFilter() updateFilter()
} }
} else if (requestCode == REQUEST_THEME_SELECTION) { REQUEST_THEME_SELECTION -> if (resultCode == Activity.RESULT_OK) {
if (resultCode == Activity.RESULT_OK) {
widgetPreferences.setTheme( widgetPreferences.setTheme(
data?.getIntExtra( data?.getIntExtra(
ColorPalettePicker.EXTRA_SELECTED, ColorPalettePicker.EXTRA_SELECTED,
@ -161,20 +160,15 @@ class ScrollableWidget : InjectingPreferenceFragment() {
) )
updateTheme() updateTheme()
} }
} else if (requestCode == REQUEST_COLOR_SELECTION) { REQUEST_COLOR_SELECTION -> if (resultCode == Activity.RESULT_OK) {
if (resultCode == Activity.RESULT_OK) {
widgetPreferences.color = data!!.getIntExtra( widgetPreferences.color = data!!.getIntExtra(
ColorWheelPicker.EXTRA_SELECTED, ColorWheelPicker.EXTRA_SELECTED,
0 0
) )
updateColor() updateColor()
} }
} else if (requestCode == REQUEST_SORT) { REQUEST_SORT -> if (resultCode == Activity.RESULT_OK) updateSort()
if (resultCode == Activity.RESULT_OK) { else -> super.onActivityResult(requestCode, resultCode, data)
updateSort()
}
} else {
super.onActivityResult(requestCode, resultCode, data)
} }
} }
@ -217,9 +211,8 @@ class ScrollableWidget : InjectingPreferenceFragment() {
}) })
} }
private suspend fun getFilter(): Filter { private suspend fun getFilter(): Filter =
return defaultFilterProvider.getFilterFromPreference(widgetPreferences.filterId) defaultFilterProvider.getFilterFromPreference(widgetPreferences.filterId)
}
private fun setupSlider(resId: Int, defValue: Int): SeekBarPreference { private fun setupSlider(resId: Int, defValue: Int): SeekBarPreference {
val preference = findPreference(resId) as SeekBarPreference val preference = findPreference(resId) as SeekBarPreference

@ -119,7 +119,8 @@ class TaskDefaults : InjectingPreferenceFragment() {
} }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_DEFAULT_LIST) { when (requestCode) {
REQUEST_DEFAULT_LIST -> {
val list: Filter? = data!!.getParcelableExtra(ListPicker.EXTRA_SELECTED_FILTER) val list: Filter? = data!!.getParcelableExtra(ListPicker.EXTRA_SELECTED_FILTER)
if (list is GtasksFilter || list is CaldavFilter) { if (list is GtasksFilter || list is CaldavFilter) {
defaultFilterProvider.defaultList = list defaultFilterProvider.defaultList = list
@ -127,8 +128,8 @@ class TaskDefaults : InjectingPreferenceFragment() {
throw RuntimeException("Unhandled filter type") throw RuntimeException("Unhandled filter type")
} }
updateRemoteListSummary() updateRemoteListSummary()
} else if (requestCode == REQUEST_CALENDAR_SELECTION) { }
if (resultCode == RESULT_OK) { REQUEST_CALENDAR_SELECTION -> if (resultCode == RESULT_OK) {
preferences.setString( preferences.setString(
R.string.gcal_p_default, R.string.gcal_p_default,
data!!.getStringExtra(CalendarPicker.EXTRA_CALENDAR_ID) data!!.getStringExtra(CalendarPicker.EXTRA_CALENDAR_ID)
@ -136,20 +137,17 @@ class TaskDefaults : InjectingPreferenceFragment() {
defaultCalendarPref.summary = defaultCalendarPref.summary =
data.getStringExtra(CalendarPicker.EXTRA_CALENDAR_NAME) data.getStringExtra(CalendarPicker.EXTRA_CALENDAR_NAME)
} }
} else if (requestCode == REQUEST_RECURRENCE) { REQUEST_RECURRENCE -> if (resultCode == RESULT_OK) {
if (resultCode == RESULT_OK) {
preferences.setString( preferences.setString(
R.string.p_default_recurrence, R.string.p_default_recurrence,
data?.getStringExtra(EXTRA_RRULE) data?.getStringExtra(EXTRA_RRULE)
) )
updateRecurrence() updateRecurrence()
} }
} else if (requestCode == REQUEST_LOCATION) { REQUEST_LOCATION ->
if (resultCode == RESULT_OK) { if (resultCode == RESULT_OK)
setDefaultLocation(data?.getParcelableExtra(EXTRA_PLACE)) setDefaultLocation(data?.getParcelableExtra(EXTRA_PLACE))
} REQUEST_TAGS -> if (resultCode == RESULT_OK) {
} else if (requestCode == REQUEST_TAGS) {
if (resultCode == RESULT_OK) {
preferences.setString( preferences.setString(
R.string.p_default_tags, R.string.p_default_tags,
data?.getParcelableArrayListExtra<TagData>(EXTRA_SELECTED) data?.getParcelableArrayListExtra<TagData>(EXTRA_SELECTED)
@ -158,8 +156,7 @@ class TaskDefaults : InjectingPreferenceFragment() {
) )
updateTags() updateTags()
} }
} else { else -> super.onActivityResult(requestCode, resultCode, data)
super.onActivityResult(requestCode, resultCode, data)
} }
} }

@ -64,18 +64,16 @@ class TaskerListNotification : InjectingPreferenceFragment() {
} }
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_SELECT_FILTER) { when (requestCode) {
if (resultCode == RESULT_OK) { REQUEST_SELECT_FILTER -> if (resultCode == RESULT_OK) {
filter = data!!.getParcelableExtra(FilterSelectionActivity.EXTRA_FILTER)!! filter = data!!.getParcelableExtra(FilterSelectionActivity.EXTRA_FILTER)!!
refreshPreferences() refreshPreferences()
} }
} else if (requestCode == REQUEST_SUBSCRIPTION) { REQUEST_SUBSCRIPTION -> if (!inventory.purchasedTasker()) {
if (!inventory.purchasedTasker()) {
cancelled = true cancelled = true
requireActivity().finish() requireActivity().finish()
} }
} else { else -> super.onActivityResult(requestCode, resultCode, data)
super.onActivityResult(requestCode, resultCode, data)
} }
} }

@ -15,6 +15,8 @@ import org.tasks.data.TaskDao
import org.tasks.dialogs.MyTimePickerDialog import org.tasks.dialogs.MyTimePickerDialog
import org.tasks.injection.InjectingAppCompatActivity import org.tasks.injection.InjectingAppCompatActivity
import org.tasks.notifications.NotificationManager import org.tasks.notifications.NotificationManager
import org.tasks.reminders.SnoozeActivity.Companion.EXTRA_TASK_IDS
import org.tasks.reminders.SnoozeActivity.Companion.FLAGS
import org.tasks.themes.ThemeAccent import org.tasks.themes.ThemeAccent
import org.tasks.time.DateTime import org.tasks.time.DateTime
import java.util.* import java.util.*
@ -107,18 +109,16 @@ class SnoozeActivity : InjectingAppCompatActivity(), SnoozeCallback, DialogInter
private const val FRAG_TAG_SNOOZE_DIALOG = "frag_tag_snooze_dialog" private const val FRAG_TAG_SNOOZE_DIALOG = "frag_tag_snooze_dialog"
private const val EXTRA_PICKING_DATE_TIME = "extra_picking_date_time" private const val EXTRA_PICKING_DATE_TIME = "extra_picking_date_time"
private const val REQUEST_DATE_TIME = 10101 private const val REQUEST_DATE_TIME = 10101
fun newIntent(context: Context?, id: Long?): Intent { fun newIntent(context: Context?, id: Long?): Intent =
val intent = Intent(context, SnoozeActivity::class.java) Intent(context, SnoozeActivity::class.java).apply {
intent.flags = FLAGS flags = FLAGS
intent.putExtra(EXTRA_TASK_ID, id) putExtra(EXTRA_TASK_ID, id)
return intent
} }
fun newIntent(context: Context?, ids: List<Long?>?): Intent { fun newIntent(context: Context?, ids: List<Long?>?): Intent =
val intent = Intent(context, SnoozeActivity::class.java) Intent(context, SnoozeActivity::class.java).apply {
intent.flags = FLAGS flags = FLAGS
intent.putExtra(EXTRA_TASK_IDS, ArrayList<Any?>(ids!!)) putExtra(EXTRA_TASK_IDS, ArrayList<Any?>(ids!!))
return intent
} }
} }
} }

@ -43,11 +43,9 @@ class CalendarNotificationIntentService : RecurringIntervalIntentService() {
} }
override fun intervalMillis() = override fun intervalMillis() =
if (preferences.getBoolean(R.string.p_calendar_reminders, false)) { if (preferences.getBoolean(R.string.p_calendar_reminders, false))
TimeUnit.HOURS.toMillis(12) TimeUnit.HOURS.toMillis(12)
} else { else 0
0
}
class Broadcast : BroadcastReceiver() { class Broadcast : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) { override fun onReceive(context: Context, intent: Intent) {

@ -85,10 +85,9 @@ class AddAccountDialog : DialogFragment() {
} }
companion object { companion object {
fun newAccountDialog(targetFragment: Fragment, rc: Int): AddAccountDialog { fun newAccountDialog(targetFragment: Fragment, rc: Int): AddAccountDialog =
val dialog = AddAccountDialog() AddAccountDialog().apply {
dialog.setTargetFragment(targetFragment, rc) setTargetFragment(targetFragment, rc)
return dialog
} }
} }
} }

@ -31,13 +31,11 @@ internal class TagRecyclerAdapter(
holder.bind(tagData, getColor(tagData), getIcon(tagData), viewModel.getState(tagData)) holder.bind(tagData, getColor(tagData), getIcon(tagData), viewModel.getState(tagData))
} }
override fun getItemCount(): Int { override fun getItemCount(): Int = differ.currentList.size
return differ.currentList.size
}
private fun getColor(tagData: TagData): Int { private fun getColor(tagData: TagData): Int {
if (tagData.getColor() != 0) { if (tagData.getColor() != 0) {
val themeColor = colorProvider.getThemeColor(tagData.getColor()!!, true) val themeColor = colorProvider.getThemeColor(tagData.getColor(), true)
if (inventory.purchasedThemes() || themeColor.isFree) { if (inventory.purchasedThemes() || themeColor.isFree) {
return themeColor.primaryColor return themeColor.primaryColor
} }
@ -45,9 +43,8 @@ internal class TagRecyclerAdapter(
return context.getColor(R.color.icon_tint_with_alpha) return context.getColor(R.color.icon_tint_with_alpha)
} }
private fun getIcon(tagData: TagData): Int? { private fun getIcon(tagData: TagData): Int? =
return if (tagData.getIcon()!! < 1000 || inventory.hasPro) getIconResId(tagData.getIcon()!!) else null if (tagData.getIcon() < 1000 || inventory.hasPro) getIconResId(tagData.getIcon()) else null
}
fun submitList(tagData: List<TagData>?) { fun submitList(tagData: List<TagData>?) {
differ.submitList(tagData) differ.submitList(tagData)

@ -38,8 +38,8 @@ class HeaderViewHolder(
} }
} }
private fun getHeader(sortMode: Int, alwaysDisplayFullDate: Boolean, group: Long): String { private fun getHeader(sortMode: Int, alwaysDisplayFullDate: Boolean, group: Long): String =
return when { when {
sortMode == SortHelper.SORT_IMPORTANCE -> context.getString(priorityToString(group.toInt())) sortMode == SortHelper.SORT_IMPORTANCE -> context.getString(priorityToString(group.toInt()))
group == 0L -> context.getString(if (sortMode == SortHelper.SORT_DUE) { group == 0L -> context.getString(if (sortMode == SortHelper.SORT_DUE) {
R.string.no_due_date R.string.no_due_date
@ -52,7 +52,6 @@ class HeaderViewHolder(
context.getString(R.string.sort_modified_group, getDateString(group, alwaysDisplayFullDate)) context.getString(R.string.sort_modified_group, getDateString(group, alwaysDisplayFullDate))
else -> getDateString(group, alwaysDisplayFullDate, false) else -> getDateString(group, alwaysDisplayFullDate, false)
} }
}
private fun getDateString(value: Long, alwaysDisplayFullDate: Boolean, lowercase: Boolean = true) = private fun getDateString(value: Long, alwaysDisplayFullDate: Boolean, lowercase: Boolean = true) =
DateUtilities.getRelativeDay(context, value, locale, FormatStyle.FULL, alwaysDisplayFullDate, lowercase) DateUtilities.getRelativeDay(context, value, locale, FormatStyle.FULL, alwaysDisplayFullDate, lowercase)

@ -229,14 +229,10 @@ class TaskViewHolder internal constructor(
} }
@OnClick(R.id.rowBody) @OnClick(R.id.rowBody)
fun onRowBodyClick() { fun onRowBodyClick() = callback.onClick(this)
callback.onClick(this)
}
@OnLongClick(R.id.rowBody) @OnLongClick(R.id.rowBody)
fun onRowBodyLongClick(): Boolean { fun onRowBodyLongClick(): Boolean = callback.onLongPress(this)
return callback.onLongPress(this)
}
@OnClick(R.id.completeBox) @OnClick(R.id.completeBox)
fun onCompleteBoxClick() { fun onCompleteBoxClick() {

@ -24,20 +24,15 @@ object DateTimeUtils {
MILLIS_PROVIDER = SYSTEM_MILLIS_PROVIDER MILLIS_PROVIDER = SYSTEM_MILLIS_PROVIDER
} }
fun printTimestamp(timestamp: Long): String { fun printTimestamp(timestamp: Long): String =
return if (BuildConfig.DEBUG) Date(timestamp).toString() else timestamp.toString() if (BuildConfig.DEBUG) Date(timestamp).toString() else timestamp.toString()
}
@SuppressLint("DefaultLocale") @SuppressLint("DefaultLocale")
fun printDuration(millis: Long): String { fun printDuration(millis: Long): String = if (BuildConfig.DEBUG) {
return if (BuildConfig.DEBUG) {
val seconds = millis / 1000 val seconds = millis / 1000
String.format( String.format(
"%dh %dm %ds", seconds / 3600L, (seconds % 3600L / 60L).toInt(), (seconds % 60L).toInt()) "%dh %dm %ds", seconds / 3600L, (seconds % 3600L / 60L).toInt(), (seconds % 60L).toInt())
} else { } else millis.toString()
millis.toString()
}
}
fun Long.startOfDay(): Long = if (this > 0) toDateTime().startOfDay().millis else 0 fun Long.startOfDay(): Long = if (this > 0) toDateTime().startOfDay().millis else 0

@ -96,12 +96,10 @@ class CalendarControlSet : TaskEditControlFragment() {
if (viewModel.eventUri.isNullOrBlank()) { if (viewModel.eventUri.isNullOrBlank()) {
CalendarPicker.newCalendarPicker(this, REQUEST_CODE_PICK_CALENDAR, calendarName) CalendarPicker.newCalendarPicker(this, REQUEST_CODE_PICK_CALENDAR, calendarName)
.show(parentFragmentManager, FRAG_TAG_CALENDAR_PICKER) .show(parentFragmentManager, FRAG_TAG_CALENDAR_PICKER)
} else { } else if (permissionRequestor.requestCalendarPermissions(REQUEST_CODE_OPEN_EVENT)) {
if (permissionRequestor.requestCalendarPermissions(REQUEST_CODE_OPEN_EVENT)) {
openCalendarEvent() openCalendarEvent()
} }
} }
}
private fun openCalendarEvent() { private fun openCalendarEvent() {
val cr = activity.contentResolver val cr = activity.contentResolver

@ -44,17 +44,11 @@ class ChipListCache @Inject internal constructor(
localBroadcastManager.broadcastRefresh() localBroadcastManager.broadcastRefresh()
} }
fun getGoogleTaskList(googleTaskList: String?): Filter? { fun getGoogleTaskList(googleTaskList: String?): Filter? = googleTaskLists[googleTaskList]
return googleTaskLists[googleTaskList]
}
fun getCaldavList(caldav: String?): Filter? { fun getCaldavList(caldav: String?): Filter? = caldavCalendars[caldav]
return caldavCalendars[caldav]
}
fun getTag(tag: String?): TagFilter? { fun getTag(tag: String?): TagFilter? = tagDatas[tag]
return tagDatas[tag]
}
init { init {
googleTaskListDao.subscribeToLists().observeForever { updated: List<GoogleTaskList> -> updateGoogleTaskLists(updated) } googleTaskListDao.subscribeToLists().observeForever { updated: List<GoogleTaskList> -> updateGoogleTaskLists(updated) }

@ -102,9 +102,8 @@ class ChipProvider @Inject constructor(
showIcon = true) showIcon = true)
} }
private fun newChip(filter: Filter?, defIcon: Int): Chip? { private fun newChip(filter: Filter?, defIcon: Int): Chip? =
return newChip(filter, defIcon, showText, showIcon) newChip(filter, defIcon, showText, showIcon)
}
fun newChip(filter: Filter?, defIcon: Int, showText: Boolean, showIcon: Boolean): Chip? { fun newChip(filter: Filter?, defIcon: Int, showText: Boolean, showIcon: Boolean): Chip? {
if (filter == null) { if (filter == null) {

@ -32,7 +32,7 @@ class EmptyTaskEditFragment : Fragment() {
override fun onCreateView( override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View? { ): View {
val binding = FragmentTaskEditEmptyBinding.inflate(inflater) val binding = FragmentTaskEditEmptyBinding.inflate(inflater)
val tint = arguments?.getParcelable<Filter>(EXTRA_FILTER)?.tint val tint = arguments?.getParcelable<Filter>(EXTRA_FILTER)?.tint

@ -219,8 +219,7 @@ class SubtaskControlSet : TaskEditControlFragment(), SubtaskViewHolder.Callbacks
companion object { companion object {
const val TAG = R.string.TEA_ctrl_subtask_pref const val TAG = R.string.TEA_ctrl_subtask_pref
private fun getQueryTemplate(task: Task): QueryTemplate { private fun getQueryTemplate(task: Task): QueryTemplate = QueryTemplate()
return QueryTemplate()
.join( .join(
Join.left( Join.left(
GoogleTask.TABLE, GoogleTask.TABLE,
@ -233,5 +232,4 @@ class SubtaskControlSet : TaskEditControlFragment(), SubtaskViewHolder.Callbacks
activeAndVisible(), activeAndVisible(),
Criterion.or(Task.PARENT.eq(task.id), GoogleTask.TASK.gt(0)))) Criterion.or(Task.PARENT.eq(task.id), GoogleTask.TASK.gt(0))))
} }
}
} }

@ -448,8 +448,6 @@ class TaskEditViewModel @ViewModelInject constructor(
} }
companion object { companion object {
fun String?.stripCarriageReturns(): String? { fun String?.stripCarriageReturns(): String? = this?.replace("\\r\\n?".toRegex(), "\n")
return this?.replace("\\r\\n?".toRegex(), "\n")
}
} }
} }

@ -109,36 +109,25 @@ internal class ScrollableViewsFactory(
return tasks.size return tasks.size
} }
override fun getViewAt(position: Int): RemoteViews? { override fun getViewAt(position: Int): RemoteViews? =
return if (tasks.isHeader(position)) buildHeader(position) else buildUpdate(position) if (tasks.isHeader(position)) buildHeader(position) else buildUpdate(position)
}
override fun getLoadingView(): RemoteViews { override fun getLoadingView(): RemoteViews = newRemoteView()
return newRemoteView()
}
override fun getViewTypeCount(): Int { override fun getViewTypeCount(): Int = 2
return 2
}
override fun getItemId(position: Int) = getTask(position)?.id ?: 0 override fun getItemId(position: Int) = getTask(position)?.id ?: 0
override fun hasStableIds(): Boolean { override fun hasStableIds(): Boolean = true
return true
}
private fun getCheckbox(task: Task): Bitmap { private fun getCheckbox(task: Task): Bitmap = checkBoxProvider.getWidgetCheckBox(task)
return checkBoxProvider.getWidgetCheckBox(task)
}
private fun newRemoteView(): RemoteViews { private fun newRemoteView(): RemoteViews = RemoteViews(
return RemoteViews(
BuildConfig.APPLICATION_ID, BuildConfig.APPLICATION_ID,
if (isDark) R.layout.widget_row_dark else R.layout.widget_row_light if (isDark) R.layout.widget_row_dark else R.layout.widget_row_light
) )
}
private fun buildHeader(position: Int): RemoteViews? { private fun buildHeader(position: Int): RemoteViews {
val row = RemoteViews( val row = RemoteViews(
BuildConfig.APPLICATION_ID, BuildConfig.APPLICATION_ID,
if (isDark) R.layout.widget_header_dark else R.layout.widget_header_light if (isDark) R.layout.widget_header_dark else R.layout.widget_header_light
@ -177,8 +166,7 @@ internal class ScrollableViewsFactory(
return row return row
} }
private fun getHeader(sortMode: Int, group: Long): String { private fun getHeader(sortMode: Int, group: Long): String = when {
return when {
sortMode == SortHelper.SORT_IMPORTANCE -> context.getString(priorityToString(group.toInt())) sortMode == SortHelper.SORT_IMPORTANCE -> context.getString(priorityToString(group.toInt()))
group == 0L -> context.getString(if (sortMode == SortHelper.SORT_DUE) { group == 0L -> context.getString(if (sortMode == SortHelper.SORT_DUE) {
R.string.no_due_date R.string.no_due_date
@ -191,7 +179,6 @@ internal class ScrollableViewsFactory(
context.getString(R.string.sort_modified_group, getDateString(group)) context.getString(R.string.sort_modified_group, getDateString(group))
else -> getDateString(group, false) else -> getDateString(group, false)
} }
}
private fun getDateString(value: Long, lowercase: Boolean = true) = private fun getDateString(value: Long, lowercase: Boolean = true) =
DateUtilities.getRelativeDay(context, value, locale.locale, FormatStyle.MEDIUM, showFullDate, lowercase) DateUtilities.getRelativeDay(context, value, locale.locale, FormatStyle.MEDIUM, showFullDate, lowercase)

@ -132,9 +132,7 @@ class ShortcutConfigActivity : ThemedInjectingAppCompatActivity(), ColorPaletteP
private val themeIndex: Int private val themeIndex: Int
get() = if (selectedTheme >= 0 && selectedTheme < ThemeColor.LAUNCHER_COLORS.size) selectedTheme else 7 get() = if (selectedTheme >= 0 && selectedTheme < ThemeColor.LAUNCHER_COLORS.size) selectedTheme else 7
private fun getShortcutName(): String { private fun getShortcutName(): String = shortcutName.text.toString().trim { it <= ' ' }
return shortcutName.text.toString().trim { it <= ' ' }
}
private fun save() { private fun save() {
val filterId = defaultFilterProvider.getFilterPreferenceValue(selectedFilter!!) val filterId = defaultFilterProvider.getFilterPreferenceValue(selectedFilter!!)

@ -130,10 +130,9 @@ class TasksWidget : AppWidgetProvider() {
return context.getColor(background) return context.getColor(background)
} }
private fun getPendingIntentTemplate(context: Context): PendingIntent { private fun getPendingIntentTemplate(context: Context): PendingIntent =
return PendingIntent.getActivity( PendingIntent.getActivity(
context, 0, Intent(context, WidgetClickActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT) context, 0, Intent(context, WidgetClickActivity::class.java), PendingIntent.FLAG_UPDATE_CURRENT)
}
private fun getOpenListIntent(context: Context, filter: Filter, widgetId: Int): PendingIntent { private fun getOpenListIntent(context: Context, filter: Filter, widgetId: Int): PendingIntent {
val intent = TaskIntents.getTaskListIntent(context, filter) val intent = TaskIntents.getTaskListIntent(context, filter)

Loading…
Cancel
Save