Miscellaneous improvements

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

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

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

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

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

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

@ -12,24 +12,24 @@ public class XmlReader {
}
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);
}
public void readLong(String name, ValueWriter<Long> writer) {
Long value = readLong(name);
final Long value = readLong(name);
if (value != null) {
writer.write(value);
}
}
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);
}
public void readInteger(String name, ValueWriter<Integer> writer) {
Integer value = readInteger(name);
final Integer value = readInteger(name);
if (value != null) {
writer.write(value);
}
@ -40,14 +40,14 @@ public class XmlReader {
}
public void readString(String name, ValueWriter<String> writer) {
String value = readString(name);
final String value = readString(name);
if (value != null) {
writer.write(value);
}
}
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);
}

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

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

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

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

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

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

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

@ -80,16 +80,19 @@ public class CaldavConverter {
}
public static int toRemote(int remotePriority, int localPriority) {
if (localPriority == Priority.NONE) {
return 0;
}
if (localPriority == Priority.MEDIUM) {
return 5;
}
if (localPriority == Priority.HIGH) {
return remotePriority < 5 ? Math.max(1, remotePriority) : 1;
switch (localPriority) {
case Priority.NONE:
return 0;
case Priority.MEDIUM:
return 5;
case Priority.HIGH:
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) {

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

@ -18,7 +18,7 @@ class PatchableDavResource(client: OkHttpClient, url: HttpUrl) : DavResource(cli
*/
@Throws(IOException::class, HttpException::class)
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 {
httpClient.newCall(Request.Builder()

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

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

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

@ -64,9 +64,8 @@ class CaldavTask {
fun isDeleted() = deleted > 0
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)"
}
override fun toString(): String =
"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 {
const val KEY = "caldav"

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

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

@ -36,10 +36,8 @@ class Filter {
@ColumnInfo(name = "f_order")
var order = NO_ORDER
fun getSql(): String {
// TODO: replace dirty hack for missing column
return sql!!.replace("tasks.userId=0", "1")
}
// TODO: replace dirty hack for missing column
fun getSql(): String = sql!!.replace("tasks.userId=0", "1")
fun setSql(sql: String?) {
this.sql = sql
@ -48,17 +46,13 @@ class Filter {
val valuesAsMap: Map<String, Any>?
get() = if (Strings.isNullOrEmpty(values)) null else AndroidUtilities.mapFromSerializedString(values)
fun getColor(): Int? {
return (if (color == null) 0 else color)!!
}
fun getColor(): Int = color ?: 0
fun setColor(color: Int?) {
this.color = color
}
fun getIcon(): Int? {
return (if (icon == null) FILTER else icon!!)
}
fun getIcon(): Int = icon ?: FILTER
fun setIcon(icon: Int?) {
this.icon = icon
@ -92,7 +86,6 @@ class Filter {
return result
}
override fun toString(): String {
return "Filter(id=$id, title=$title, sql=$sql, values=$values, criterion=$criterion, color=$color, icon=$icon, order=$order)"
}
override fun toString(): String =
"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 writeToParcel(out: Parcel, flags: Int) {
out.writeLong(id)
out.writeLong(task)
out.writeString(place)
out.writeInt(radius)
out.writeInt(if (isArrival) 1 else 0)
out.writeInt(if (isDeparture) 1 else 0)
with(out) {
writeLong(id)
writeLong(task)
writeString(place)
writeInt(radius)
writeInt(if (isArrival) 1 else 0)
writeInt(if (isDeparture) 1 else 0)
}
}
override fun equals(other: Any?): Boolean {
@ -110,9 +112,8 @@ class Geofence : Serializable, Parcelable {
return result
}
override fun toString(): String {
return "Geofence(id=$id, task=$task, place=$place, radius=$radius, isArrival=$isArrival, isDeparture=$isDeparture)"
}
override fun toString(): String =
"Geofence(id=$id, task=$task, place=$place, radius=$radius, isArrival=$isArrival, isDeparture=$isDeparture)"
companion object {
const val TABLE_NAME = "geofences"
@ -120,13 +121,9 @@ class Geofence : Serializable, Parcelable {
@JvmField val TASK = TABLE.column("task")
@JvmField val PLACE = TABLE.column("place")
@JvmField val CREATOR: Parcelable.Creator<Geofence> = object : Parcelable.Creator<Geofence> {
override fun createFromParcel(source: Parcel): Geofence? {
return Geofence(source)
}
override fun createFromParcel(source: Parcel): Geofence = Geofence(source)
override fun newArray(size: Int): Array<Geofence?> {
return arrayOfNulls(size)
}
override fun newArray(size: Int): Array<Geofence?> = arrayOfNulls(size)
}
}
}

@ -92,9 +92,8 @@ class GoogleTask {
return result
}
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)"
}
override fun toString(): String =
"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
get() = id == 0L

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

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

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

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

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

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

@ -26,7 +26,6 @@ class SubsetCaldav {
return result
}
override fun toString(): String {
return "SubsetCaldav(cd_id=$cd_id, cd_calendar=$cd_calendar, cd_remote_parent=$cd_remote_parent, cd_order=$cd_order)"
}
override fun toString(): String =
"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) }
}
fun getTaskUid(): String {
return taskUid!!
}
fun getTaskUid(): String = taskUid!!
fun setTaskUid(taskUid: String) {
this.taskUid = taskUid

@ -55,26 +55,24 @@ class TagData : Parcelable {
@SuppressLint("ParcelClassLoader")
@Ignore
private constructor(parcel: Parcel) {
id = parcel.readValue(null) as Long?
remoteId = parcel.readString()
name = parcel.readString()
color = parcel.readInt()
tagOrdering = parcel.readString()
icon = parcel.readInt()
order = parcel.readInt()
with(parcel) {
id = readValue(null) as Long?
remoteId = readString()
name = readString()
color = readInt()
tagOrdering = readString()
icon = readInt()
order = readInt()
}
}
fun getColor(): Int? {
return (if (color == null) 0 else color)!!
}
fun getColor(): Int = color ?: 0
fun setColor(color: Int?) {
this.color = color
}
fun getIcon(): Int? {
return (if (icon == null) LABEL else icon!!)
}
fun getIcon(): Int = icon ?: LABEL
fun setIcon(icon: Int?) {
this.icon = icon
@ -83,13 +81,15 @@ class TagData : Parcelable {
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeValue(id)
dest.writeString(remoteId)
dest.writeString(name)
dest.writeInt(color!!)
dest.writeString(tagOrdering)
dest.writeInt(getIcon()!!)
dest.writeInt(order)
with(dest) {
writeValue(id)
writeString(remoteId)
writeString(name)
writeInt(color!!)
writeString(tagOrdering)
writeInt(getIcon())
writeInt(order)
}
}
override fun equals(other: Any?): Boolean {
@ -118,19 +118,14 @@ class TagData : Parcelable {
return result
}
override fun toString(): String {
return "TagData(id=$id, remoteId=$remoteId, name=$name, color=$color, tagOrdering=$tagOrdering, icon=$icon, order=$order)"
}
override fun toString(): String =
"TagData(id=$id, remoteId=$remoteId, name=$name, color=$color, tagOrdering=$tagOrdering, icon=$icon, order=$order)"
companion object {
@JvmField val CREATOR: Parcelable.Creator<TagData> = object : Parcelable.Creator<TagData> {
override fun createFromParcel(source: Parcel): TagData? {
return TagData(source)
}
override fun createFromParcel(source: Parcel): TagData = TagData(source)
override fun newArray(size: Int): Array<TagData?> {
return arrayOfNulls(size)
}
override fun newArray(size: Int): Array<TagData?> = 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
* that. Otherwise, return the argument
*/
suspend fun getTagWithCase(tag: String): String? {
return getTagByName(tag)?.name ?: tag
}
suspend fun getTagWithCase(tag: String): String? = getTagByName(tag)?.name ?: tag
suspend fun searchTags(query: String): List<TagData> {
return searchTagsInternal("%$query%").sort()
}
suspend fun searchTags(query: String): List<TagData> = searchTagsInternal("%$query%").sort()
@Query("SELECT * FROM tagdata WHERE name LIKE :query AND name NOT NULL AND name != ''")
protected abstract suspend fun searchTagsInternal(query: String): List<TagData>

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

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

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

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

@ -9,15 +9,14 @@ object DateTimeUtils {
@JvmStatic
fun newDateUtc(
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"))
}
year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int): DateTime =
DateTime(year, month, day, hour, minute, second, 0, TimeZone.getTimeZone("GMT"))
@JvmStatic
fun newDateTime(): DateTime = DateTime()
fun newDateTime(): DateTime = DateTime()
@JvmStatic
fun midnight(): Long = newDateTime().plusDays(1).startOfDay().millis
fun midnight(): Long = newDateTime().plusDays(1).startOfDay().millis
@JvmStatic
fun newDateTime(timestamp: Long): DateTime = DateTime(timestamp)

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

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

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

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

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

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

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

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

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

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

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

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

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

@ -41,9 +41,7 @@ import java.util.*
* Collections.sort(your list, new AlphanumComparator());
*/
class AlphanumComparator<T>(private val getTitle: (T) -> String?) : Comparator<T> {
private fun isDigit(ch: Char): Boolean {
return ch.toInt() in 48..57
}
private fun isDigit(ch: Char): Boolean = ch.toInt() in 48..57
/** 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 {

@ -24,23 +24,21 @@ class FilterCriteriaProvider @Inject constructor(
private val caldavDao: CaldavDao) {
private val r = context.resources
suspend fun getFilterCriteria(identifier: String): CustomFilterCriterion {
return when (identifier) {
IDENTIFIER_UNIVERSE -> startingUniverse
IDENTIFIER_TITLE -> taskTitleContainsFilter
IDENTIFIER_IMPORTANCE -> priorityFilter
IDENTIFIER_DUEDATE -> dueDateFilter
IDENTIFIER_GTASKS -> gtasksFilterCriteria()
IDENTIFIER_CALDAV -> caldavFilterCriteria()
IDENTIFIER_TAG_IS -> tagFilter()
IDENTIFIER_TAG_CONTAINS -> tagNameContainsFilter
IDENTIFIER_RECUR -> recurringFilter
IDENTIFIER_COMPLETED -> completedFilter
IDENTIFIER_HIDDEN -> hiddenFilter
IDENTIFIER_PARENT -> parentFilter
IDENTIFIER_SUBTASK -> subtaskFilter
else -> throw RuntimeException("Unknown identifier: $identifier")
}
suspend fun getFilterCriteria(identifier: String): CustomFilterCriterion = when (identifier) {
IDENTIFIER_UNIVERSE -> startingUniverse
IDENTIFIER_TITLE -> taskTitleContainsFilter
IDENTIFIER_IMPORTANCE -> priorityFilter
IDENTIFIER_DUEDATE -> dueDateFilter
IDENTIFIER_GTASKS -> gtasksFilterCriteria()
IDENTIFIER_CALDAV -> caldavFilterCriteria()
IDENTIFIER_TAG_IS -> tagFilter()
IDENTIFIER_TAG_CONTAINS -> tagNameContainsFilter
IDENTIFIER_RECUR -> recurringFilter
IDENTIFIER_COMPLETED -> completedFilter
IDENTIFIER_HIDDEN -> hiddenFilter
IDENTIFIER_PARENT -> parentFilter
IDENTIFIER_SUBTASK -> subtaskFilter
else -> throw RuntimeException("Unknown identifier: $identifier")
}
val startingUniverse: CustomFilterCriterion
@ -55,20 +53,22 @@ class FilterCriteriaProvider @Inject constructor(
suspend fun all(): List<CustomFilterCriterion> {
val result: MutableList<CustomFilterCriterion> = ArrayList()
result.add(tagFilter())
result.add(tagNameContainsFilter)
result.add(dueDateFilter)
result.add(priorityFilter)
result.add(taskTitleContainsFilter)
if (googleTaskListDao.getAccounts().isNotEmpty()) {
result.add(gtasksFilterCriteria())
with(result) {
add(tagFilter())
add(tagNameContainsFilter)
add(dueDateFilter)
add(priorityFilter)
add(taskTitleContainsFilter)
if (googleTaskListDao.getAccounts().isNotEmpty()) {
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
}

@ -197,9 +197,8 @@ class FilterProvider @Inject constructor(
Intent(context, HelpAndFeedback::class.java),
0))
private suspend fun googleTaskFilters(showCreate: Boolean = true): List<FilterListItem> {
return googleTaskListDao.getAccounts().flatMap { googleTaskFilter(it, showCreate) }
}
private suspend fun googleTaskFilters(showCreate: Boolean = true): List<FilterListItem> =
googleTaskListDao.getAccounts().flatMap { googleTaskFilter(it, showCreate) }
private suspend fun googleTaskFilter(account: GoogleTaskAccount, showCreate: Boolean): List<FilterListItem> =
listOf(
@ -275,12 +274,12 @@ class FilterProvider @Inject constructor(
}
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> =
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> =
if (predicate) filter(predicate2) else this.toList()
if (predicate) filter(predicate2) else toList()
}
}

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

@ -39,24 +39,22 @@ class TaskEditControlSetFragmentManager @Inject constructor(
return fragments
}
private fun createFragment(fragmentId: Int): TaskEditControlFragment {
return when (fragmentId) {
DeadlineControlSet.TAG -> DeadlineControlSet()
PriorityControlSet.TAG -> PriorityControlSet()
DescriptionControlSet.TAG -> DescriptionControlSet()
CalendarControlSet.TAG -> CalendarControlSet()
HideUntilControlSet.TAG -> HideUntilControlSet()
ReminderControlSet.TAG -> ReminderControlSet()
LocationControlSet.TAG -> LocationControlSet()
FilesControlSet.TAG -> FilesControlSet()
TimerControlSet.TAG -> TimerControlSet()
TagsControlSet.TAG -> TagsControlSet()
RepeatControlSet.TAG -> RepeatControlSet()
CommentBarFragment.TAG -> CommentBarFragment()
ListFragment.TAG -> ListFragment()
SubtaskControlSet.TAG -> SubtaskControlSet()
else -> throw RuntimeException("Unsupported fragment")
}
private fun createFragment(fragmentId: Int): TaskEditControlFragment = when (fragmentId) {
DeadlineControlSet.TAG -> DeadlineControlSet()
PriorityControlSet.TAG -> PriorityControlSet()
DescriptionControlSet.TAG -> DescriptionControlSet()
CalendarControlSet.TAG -> CalendarControlSet()
HideUntilControlSet.TAG -> HideUntilControlSet()
ReminderControlSet.TAG -> ReminderControlSet()
LocationControlSet.TAG -> LocationControlSet()
FilesControlSet.TAG -> FilesControlSet()
TimerControlSet.TAG -> TimerControlSet()
TagsControlSet.TAG -> TagsControlSet()
RepeatControlSet.TAG -> RepeatControlSet()
CommentBarFragment.TAG -> CommentBarFragment()
ListFragment.TAG -> ListFragment()
SubtaskControlSet.TAG -> SubtaskControlSet()
else -> throw RuntimeException("Unsupported fragment")
}
init {

@ -45,9 +45,7 @@ class GoogleAccountManager @Inject constructor(
accountList.find { name.equals(it.name, ignoreCase = true) }
}
fun canAccessAccount(name: String): Boolean {
return getAccount(name) != null
}
fun canAccessAccount(name: String): Boolean = getAccount(name) != null
suspend fun getAccessToken(name: String?, scope: String): String? {
val account = name?.let { getAccount(it) }
@ -74,13 +72,11 @@ class GoogleAccountManager @Inject constructor(
}
}
suspend fun getTasksAuthToken(activity: Activity, accountName: String): Bundle? {
return getToken(TasksScopes.TASKS, activity, accountName)
}
suspend fun getTasksAuthToken(activity: Activity, accountName: String): Bundle? =
getToken(TasksScopes.TASKS, activity, accountName)
suspend fun getDriveAuthToken(activity: Activity, accountName: String): Bundle? {
return getToken(DriveScopes.DRIVE_FILE, activity, accountName)
}
suspend fun getDriveAuthToken(activity: Activity, accountName: String): Bundle? =
getToken(DriveScopes.DRIVE_FILE, activity, accountName)
@SuppressLint("CheckResult")
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? {
return if (string == null || string.length <= max) string else string.substring(0, max)
}
fun truncate(string: String?, max: Int): String? =
if (string == null || string.length <= max) string else string.substring(0, max)
fun getTruncatedValue(currentValue: String?, newValue: String?, maxLength: Int): String? {
return if (isNullOrEmpty(newValue)
|| newValue!!.length < maxLength || isNullOrEmpty(currentValue)
|| !currentValue!!.startsWith(newValue)) newValue else currentValue
}
fun getTruncatedValue(currentValue: String?, newValue: String?, maxLength: Int): String? =
if (isNullOrEmpty(newValue)
|| newValue!!.length < maxLength || isNullOrEmpty(currentValue)
|| !currentValue!!.startsWith(newValue)) newValue else currentValue
}
}

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

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

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

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

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

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

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

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

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

@ -52,7 +52,7 @@ abstract class BasePreferences : ThemedInjectingAppCompatActivity(),
private fun setupMenu() = setupMenu(supportFragmentManager.findFragmentById(R.id.settings))
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()
if (menu > 0) {
toolbar.inflateMenu(menu)
@ -79,16 +79,14 @@ abstract class BasePreferences : ThemedInjectingAppCompatActivity(),
override fun onPreferenceStartFragment(
caller: PreferenceFragmentCompat,
pref: Preference
): Boolean {
return startPreference(
caller,
supportFragmentManager
.fragmentFactory
.instantiate(classLoader, pref.fragment)
.apply { arguments = pref.extras },
pref.title
)
}
): Boolean = startPreference(
caller,
supportFragmentManager
.fragmentFactory
.instantiate(classLoader, pref.fragment)
.apply { arguments = pref.extras },
pref.title
)
fun startPreference(
caller: PreferenceFragmentCompat,
@ -105,12 +103,9 @@ abstract class BasePreferences : ThemedInjectingAppCompatActivity(),
return true
}
override fun onMenuItemClick(item: MenuItem?): Boolean {
return if (item?.itemId == R.id.menu_help_and_feedback) {
startActivity(Intent(this, HelpAndFeedback::class.java))
true
} else {
false
}
}
override fun onMenuItemClick(item: MenuItem?): Boolean =
if (item?.itemId == R.id.menu_help_and_feedback) {
startActivity(Intent(this, HelpAndFeedback::class.java))
true
} else false
}

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

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

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

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

@ -209,12 +209,13 @@ class LookAndFeel : InjectingPreferenceFragment() {
placeProviderPreference.summary = choices[placeProvider]
}
private fun getPlaceProvider(): Int {
return if (playServices.isPlayServicesAvailable && inventory.hasPro) preferences.getInt(
R.string.p_place_provider,
0
) else 0
}
private fun getPlaceProvider(): Int =
if (playServices.isPlayServicesAvailable && inventory.hasPro)
preferences.getInt(
R.string.p_place_provider,
0
)
else 0
private fun setBaseTheme(index: Int) {
activity?.intent?.removeExtra(EXTRA_THEME_OVERRIDE)
@ -228,79 +229,86 @@ class LookAndFeel : InjectingPreferenceFragment() {
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_PURCHASE) {
val index = if (inventory.hasPro) {
data?.getIntExtra(ThemePickerDialog.EXTRA_SELECTED, DEFAULT_BASE_THEME)
?: themeBase.index
} else {
preferences.themeBase
when (requestCode) {
REQUEST_PURCHASE -> {
val index = if (inventory.hasPro) {
data?.getIntExtra(ThemePickerDialog.EXTRA_SELECTED, DEFAULT_BASE_THEME)
?: themeBase.index
} else preferences.themeBase
setBaseTheme(index)
}
setBaseTheme(index)
} else if (requestCode == REQUEST_THEME_PICKER) {
val index = data?.getIntExtra(ThemePickerDialog.EXTRA_SELECTED, DEFAULT_BASE_THEME)
?: preferences.themeBase
if (resultCode == RESULT_OK) {
if (inventory.purchasedThemes() || ThemeBase(index).isFree) {
setBaseTheme(index)
REQUEST_THEME_PICKER -> {
val index = data?.getIntExtra(ThemePickerDialog.EXTRA_SELECTED, DEFAULT_BASE_THEME)
?: preferences.themeBase
if (resultCode == RESULT_OK) {
if (inventory.purchasedThemes() || ThemeBase(index).isFree) {
setBaseTheme(index)
} else {
newPurchaseDialog(this, REQUEST_PURCHASE)
.show(parentFragmentManager, FRAG_TAG_PURCHASE_DIALOG)
}
} else {
newPurchaseDialog(this, REQUEST_PURCHASE)
.show(parentFragmentManager, FRAG_TAG_PURCHASE_DIALOG)
setBaseTheme(index)
}
} else {
setBaseTheme(index)
}
} else if (requestCode == REQUEST_COLOR_PICKER) {
if (resultCode == RESULT_OK) {
val color = data?.getIntExtra(
ColorWheelPicker.EXTRA_SELECTED,
themeColor.primaryColor
)
?: themeColor.primaryColor
if (preferences.defaultThemeColor != color) {
preferences.setInt(R.string.p_theme_color, color)
recreate()
REQUEST_COLOR_PICKER -> {
if (resultCode == RESULT_OK) {
val color = data?.getIntExtra(
ColorWheelPicker.EXTRA_SELECTED,
themeColor.primaryColor
) ?: themeColor.primaryColor
if (preferences.defaultThemeColor != color) {
preferences.setInt(R.string.p_theme_color, color)
recreate()
}
}
}
} else if (requestCode == REQUEST_ACCENT_PICKER) {
if (resultCode == RESULT_OK) {
val index = data!!.getIntExtra(ColorPalettePicker.EXTRA_SELECTED, 0)
if (preferences.getInt(R.string.p_theme_accent, -1) != index) {
preferences.setInt(R.string.p_theme_accent, index)
recreate()
REQUEST_ACCENT_PICKER -> {
if (resultCode == RESULT_OK) {
val index = data!!.getIntExtra(ColorPalettePicker.EXTRA_SELECTED, 0)
if (preferences.getInt(R.string.p_theme_accent, -1) != index) {
preferences.setInt(R.string.p_theme_accent, index)
recreate()
}
}
}
} else if (requestCode == REQUEST_LAUNCHER_PICKER) {
if (resultCode == RESULT_OK) {
val index = data!!.getIntExtra(ColorPalettePicker.EXTRA_SELECTED, 0)
setLauncherIcon(index)
preferences.setInt(R.string.p_theme_launcher, index)
updateLauncherPreference()
}
} else if (requestCode == REQUEST_DEFAULT_LIST) {
if (resultCode == RESULT_OK) {
val filter: Filter =
data!!.getParcelableExtra(FilterSelectionActivity.EXTRA_FILTER)!!
defaultFilterProvider.setDefaultOpenFilter(filter)
findPreference(R.string.p_default_open_filter).summary = filter.listingTitle
localBroadcastManager.broadcastRefresh()
REQUEST_LAUNCHER_PICKER -> {
if (resultCode == RESULT_OK) {
val index = data!!.getIntExtra(ColorPalettePicker.EXTRA_SELECTED, 0)
setLauncherIcon(index)
preferences.setInt(R.string.p_theme_launcher, index)
updateLauncherPreference()
}
}
} else if (requestCode == REQUEST_LOCALE) {
if (resultCode == RESULT_OK) {
val newValue: Locale =
data!!.getSerializableExtra(LocalePickerDialog.EXTRA_LOCALE) as Locale
val override: String? = newValue.languageOverride
if (isNullOrEmpty(override)) {
preferences.remove(R.string.p_language)
} else {
preferences.setString(R.string.p_language, override)
REQUEST_DEFAULT_LIST -> {
if (resultCode == RESULT_OK) {
val filter: Filter =
data!!.getParcelableExtra(FilterSelectionActivity.EXTRA_FILTER)!!
defaultFilterProvider.setDefaultOpenFilter(filter)
findPreference(R.string.p_default_open_filter).summary = filter.listingTitle
localBroadcastManager.broadcastRefresh()
}
updateLocale()
if (locale != newValue) {
showRestartDialog()
}
REQUEST_LOCALE -> {
if (resultCode == RESULT_OK) {
val newValue: Locale =
data!!.getSerializableExtra(LocalePickerDialog.EXTRA_LOCALE) as Locale
val override: String? = newValue.languageOverride
if (isNullOrEmpty(override)) {
preferences.remove(R.string.p_language)
} else {
preferences.setString(R.string.p_language, override)
}
updateLocale()
if (locale != newValue) {
showRestartDialog()
}
}
}
} else {
super.onActivityResult(requestCode, resultCode, data)
else -> {
super.onActivityResult(requestCode, resultCode, data)
}
}
}

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

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

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

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

@ -15,6 +15,8 @@ import org.tasks.data.TaskDao
import org.tasks.dialogs.MyTimePickerDialog
import org.tasks.injection.InjectingAppCompatActivity
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.time.DateTime
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 EXTRA_PICKING_DATE_TIME = "extra_picking_date_time"
private const val REQUEST_DATE_TIME = 10101
fun newIntent(context: Context?, id: Long?): Intent {
val intent = Intent(context, SnoozeActivity::class.java)
intent.flags = FLAGS
intent.putExtra(EXTRA_TASK_ID, id)
return intent
}
fun newIntent(context: Context?, id: Long?): Intent =
Intent(context, SnoozeActivity::class.java).apply {
flags = FLAGS
putExtra(EXTRA_TASK_ID, id)
}
fun newIntent(context: Context?, ids: List<Long?>?): Intent {
val intent = Intent(context, SnoozeActivity::class.java)
intent.flags = FLAGS
intent.putExtra(EXTRA_TASK_IDS, ArrayList<Any?>(ids!!))
return intent
}
fun newIntent(context: Context?, ids: List<Long?>?): Intent =
Intent(context, SnoozeActivity::class.java).apply {
flags = FLAGS
putExtra(EXTRA_TASK_IDS, ArrayList<Any?>(ids!!))
}
}
}

@ -43,11 +43,9 @@ class CalendarNotificationIntentService : RecurringIntervalIntentService() {
}
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)
} else {
0
}
else 0
class Broadcast : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {

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

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

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

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

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

@ -96,10 +96,8 @@ class CalendarControlSet : TaskEditControlFragment() {
if (viewModel.eventUri.isNullOrBlank()) {
CalendarPicker.newCalendarPicker(this, REQUEST_CODE_PICK_CALENDAR, calendarName)
.show(parentFragmentManager, FRAG_TAG_CALENDAR_PICKER)
} else {
if (permissionRequestor.requestCalendarPermissions(REQUEST_CODE_OPEN_EVENT)) {
openCalendarEvent()
}
} else if (permissionRequestor.requestCalendarPermissions(REQUEST_CODE_OPEN_EVENT)) {
openCalendarEvent()
}
}

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

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

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

@ -219,19 +219,17 @@ class SubtaskControlSet : TaskEditControlFragment(), SubtaskViewHolder.Callbacks
companion object {
const val TAG = R.string.TEA_ctrl_subtask_pref
private fun getQueryTemplate(task: Task): QueryTemplate {
return QueryTemplate()
.join(
Join.left(
GoogleTask.TABLE,
Criterion.and(
GoogleTask.PARENT.eq(task.id),
GoogleTask.TASK.eq(Task.ID),
GoogleTask.DELETED.eq(0))))
.where(
Criterion.and(
activeAndVisible(),
Criterion.or(Task.PARENT.eq(task.id), GoogleTask.TASK.gt(0))))
}
private fun getQueryTemplate(task: Task): QueryTemplate = QueryTemplate()
.join(
Join.left(
GoogleTask.TABLE,
Criterion.and(
GoogleTask.PARENT.eq(task.id),
GoogleTask.TASK.eq(Task.ID),
GoogleTask.DELETED.eq(0))))
.where(
Criterion.and(
activeAndVisible(),
Criterion.or(Task.PARENT.eq(task.id), GoogleTask.TASK.gt(0))))
}
}

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

@ -109,36 +109,25 @@ internal class ScrollableViewsFactory(
return tasks.size
}
override fun getViewAt(position: Int): RemoteViews? {
return if (tasks.isHeader(position)) buildHeader(position) else buildUpdate(position)
}
override fun getViewAt(position: Int): RemoteViews? =
if (tasks.isHeader(position)) buildHeader(position) else buildUpdate(position)
override fun getLoadingView(): RemoteViews {
return newRemoteView()
}
override fun getLoadingView(): RemoteViews = newRemoteView()
override fun getViewTypeCount(): Int {
return 2
}
override fun getViewTypeCount(): Int = 2
override fun getItemId(position: Int) = getTask(position)?.id ?: 0
override fun hasStableIds(): Boolean {
return true
}
override fun hasStableIds(): Boolean = true
private fun getCheckbox(task: Task): Bitmap {
return checkBoxProvider.getWidgetCheckBox(task)
}
private fun getCheckbox(task: Task): Bitmap = checkBoxProvider.getWidgetCheckBox(task)
private fun newRemoteView(): RemoteViews {
return RemoteViews(
BuildConfig.APPLICATION_ID,
if (isDark) R.layout.widget_row_dark else R.layout.widget_row_light
)
}
private fun newRemoteView(): RemoteViews = RemoteViews(
BuildConfig.APPLICATION_ID,
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(
BuildConfig.APPLICATION_ID,
if (isDark) R.layout.widget_header_dark else R.layout.widget_header_light
@ -177,20 +166,18 @@ internal class ScrollableViewsFactory(
return row
}
private fun getHeader(sortMode: Int, group: Long): String {
return when {
sortMode == SortHelper.SORT_IMPORTANCE -> context.getString(priorityToString(group.toInt()))
group == 0L -> context.getString(if (sortMode == SortHelper.SORT_DUE) {
R.string.no_due_date
} else {
R.string.no_date
})
sortMode == SortHelper.SORT_CREATED ->
context.getString(R.string.sort_created_group, getDateString(group))
sortMode == SortHelper.SORT_MODIFIED ->
context.getString(R.string.sort_modified_group, getDateString(group))
else -> getDateString(group, false)
}
private fun getHeader(sortMode: Int, group: Long): String = when {
sortMode == SortHelper.SORT_IMPORTANCE -> context.getString(priorityToString(group.toInt()))
group == 0L -> context.getString(if (sortMode == SortHelper.SORT_DUE) {
R.string.no_due_date
} else {
R.string.no_date
})
sortMode == SortHelper.SORT_CREATED ->
context.getString(R.string.sort_created_group, getDateString(group))
sortMode == SortHelper.SORT_MODIFIED ->
context.getString(R.string.sort_modified_group, getDateString(group))
else -> getDateString(group, false)
}
private fun getDateString(value: Long, lowercase: Boolean = true) =

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

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

Loading…
Cancel
Save