#751 - Support GIFs inserted from keyboard

This commit is contained in:
Moez Bhatti
2018-04-30 17:44:21 -04:00
parent 4176cf7299
commit 923e620238
8 changed files with 122 additions and 27 deletions
@@ -20,12 +20,18 @@ package common.widget
import android.content.Context import android.content.Context
import android.graphics.Typeface import android.graphics.Typeface
import android.os.Build
import android.os.Bundle
import android.support.v13.view.inputmethod.EditorInfoCompat
import android.support.v13.view.inputmethod.InputConnectionCompat
import android.util.AttributeSet import android.util.AttributeSet
import android.view.KeyEvent import android.view.KeyEvent
import android.view.inputmethod.EditorInfo import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection import android.view.inputmethod.InputConnection
import android.view.inputmethod.InputConnectionWrapper import android.view.inputmethod.InputConnectionWrapper
import android.view.inputmethod.InputContentInfo
import android.widget.EditText import android.widget.EditText
import com.google.android.mms.ContentType
import com.moez.QKSMS.R import com.moez.QKSMS.R
import com.uber.autodispose.android.scope import com.uber.autodispose.android.scope
import com.uber.autodispose.kotlin.autoDisposable import com.uber.autodispose.kotlin.autoDisposable
@@ -42,8 +48,10 @@ import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.PublishSubject import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject import io.reactivex.subjects.Subject
import util.Preferences import util.Preferences
import util.tryOrNull
import javax.inject.Inject import javax.inject.Inject
/** /**
* Custom implementation of EditText to allow for dynamic text colors * Custom implementation of EditText to allow for dynamic text colors
* *
@@ -71,6 +79,8 @@ class QkEditText @JvmOverloads constructor(context: Context, attrs: AttributeSet
@Inject lateinit var prefs: Preferences @Inject lateinit var prefs: Preferences
val backspaces: Subject<Unit> = PublishSubject.create() val backspaces: Subject<Unit> = PublishSubject.create()
val inputContentSelected: Subject<InputContentInfo> = PublishSubject.create()
var supportsInputContent: Boolean = false
private var textColorObservable: Observable<Int>? = null private var textColorObservable: Observable<Int>? = null
private var textColorHintObservable: Observable<Int>? = null private var textColorHintObservable: Observable<Int>? = null
@@ -176,8 +186,35 @@ class QkEditText @JvmOverloads constructor(context: Context, attrs: AttributeSet
.subscribe() .subscribe()
} }
override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection { override fun onCreateInputConnection(editorInfo: EditorInfo): InputConnection {
return object : InputConnectionWrapper(super.onCreateInputConnection(outAttrs), true) {
val inputConnection = super.onCreateInputConnection(editorInfo)
if (supportsInputContent) {
EditorInfoCompat.setContentMimeTypes(editorInfo, arrayOf(
ContentType.IMAGE_JPEG,
ContentType.IMAGE_JPG,
ContentType.IMAGE_PNG,
ContentType.IMAGE_GIF))
}
return object : InputConnectionWrapper(inputConnection, true) {
override fun commitContent(inputContentInfo: InputContentInfo, flags: Int, opts: Bundle?): Boolean {
val grantReadPermission = flags and InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION != 0
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1 && grantReadPermission) {
return tryOrNull {
inputContentInfo.requestPermission()
inputContentSelected.onNext(inputContentInfo)
true
} ?: false
}
return true
}
override fun sendKeyEvent(event: KeyEvent): Boolean { override fun sendKeyEvent(event: KeyEvent): Boolean {
if (event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_DEL) { if (event.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_DEL) {
@@ -188,11 +225,12 @@ class QkEditText @JvmOverloads constructor(context: Context, attrs: AttributeSet
override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean { override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean {
// magic: in latest Android, deleteSurroundingText(1, 0) will be called for backspace
return if (beforeLength == 1 && afterLength == 0) { return if (beforeLength == 1 && afterLength == 0) {
sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL)) && sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL)) sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
} else super.deleteSurroundingText(beforeLength, afterLength) && sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL))
} else {
super.deleteSurroundingText(beforeLength, afterLength)
}
} }
} }
@@ -0,0 +1,45 @@
/*
* Copyright (C) 2017 Moez Bhatti <moez.bhatti@gmail.com>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package feature.compose
import android.content.Context
import android.net.Uri
import android.os.Build
import android.view.inputmethod.InputContentInfo
import com.google.android.mms.ContentType
data class Attachment(private val uri: Uri? = null, private val inputContent: InputContentInfo? = null) {
fun getUri(): Uri? {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1) {
inputContent?.contentUri ?: uri
} else {
uri
}
}
fun isGif(context: Context): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1 && inputContent != null) {
inputContent.description.hasMimeType(ContentType.IMAGE_GIF)
} else {
context.contentResolver.getType(uri) == ContentType.IMAGE_GIF
}
}
}
@@ -19,13 +19,14 @@
package feature.compose package feature.compose
import android.content.Context import android.content.Context
import android.net.Uri
import android.support.v7.widget.RecyclerView import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater import android.view.LayoutInflater
import android.view.ViewGroup import android.view.ViewGroup
import com.bumptech.glide.Glide import com.bumptech.glide.Glide
import com.jakewharton.rxbinding2.view.clicks import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.R import com.moez.QKSMS.R
import common.base.QkAdapter
import common.base.QkViewHolder
import common.util.Colors import common.util.Colors
import common.util.extensions.setBackgroundTint import common.util.extensions.setBackgroundTint
import common.util.extensions.setTint import common.util.extensions.setTint
@@ -34,16 +35,14 @@ import io.reactivex.rxkotlin.plusAssign
import io.reactivex.subjects.PublishSubject import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject import io.reactivex.subjects.Subject
import kotlinx.android.synthetic.main.attachment_list_item.view.* import kotlinx.android.synthetic.main.attachment_list_item.view.*
import common.base.QkAdapter
import common.base.QkViewHolder
import javax.inject.Inject import javax.inject.Inject
class AttachmentAdapter @Inject constructor( class AttachmentAdapter @Inject constructor(
private val context: Context, private val context: Context,
private val colors: Colors private val colors: Colors
) : QkAdapter<Uri>() { ) : QkAdapter<Attachment>() {
val attachmentDeleted: Subject<Uri> = PublishSubject.create() val attachmentDeleted: Subject<Attachment> = PublishSubject.create()
private val disposables = CompositeDisposable() private val disposables = CompositeDisposable()
@@ -67,14 +66,14 @@ class AttachmentAdapter @Inject constructor(
} }
override fun onBindViewHolder(holder: QkViewHolder, position: Int) { override fun onBindViewHolder(holder: QkViewHolder, position: Int) {
val uri = getItem(position) val attachment = getItem(position)
val view = holder.itemView val view = holder.itemView
view.clicks().subscribe { view.clicks().subscribe {
attachmentDeleted.onNext(uri) attachmentDeleted.onNext(attachment)
} }
Glide.with(context).load(uri).into(view.thumbnail) Glide.with(context).load(attachment.getUri()).into(view.thumbnail)
} }
} }
@@ -20,7 +20,6 @@ package feature.compose
import android.content.res.ColorStateList import android.content.res.ColorStateList
import android.graphics.PorterDuff import android.graphics.PorterDuff
import android.net.Uri
import android.os.Bundle import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.LinearLayoutManager
import android.view.Menu import android.view.Menu
@@ -64,11 +63,12 @@ class ComposeActivity : QkThemedActivity<ComposeViewModel>(), ComposeView {
override val messageLongClickIntent: Subject<Message> by lazy { messageAdapter.longClicks } override val messageLongClickIntent: Subject<Message> by lazy { messageAdapter.longClicks }
override val cancelSendingIntent: Subject<Message> by lazy { messageAdapter.cancelSending } override val cancelSendingIntent: Subject<Message> by lazy { messageAdapter.cancelSending }
override val menuItemIntent: Subject<Int> by lazy { dialog.adapter.menuItemClicks } override val menuItemIntent: Subject<Int> by lazy { dialog.adapter.menuItemClicks }
override val attachmentDeletedIntent: Subject<Uri> by lazy { attachmentAdapter.attachmentDeleted } override val attachmentDeletedIntent: Subject<Attachment> by lazy { attachmentAdapter.attachmentDeleted }
override val textChangedIntent by lazy { message.textChanges() } override val textChangedIntent by lazy { message.textChanges() }
override val attachIntent by lazy { attach.clicks() } override val attachIntent by lazy { attach.clicks() }
override val cameraIntent by lazy { camera.clicks() } override val cameraIntent by lazy { camera.clicks() }
override val galleryIntent by lazy { gallery.clicks() } override val galleryIntent by lazy { gallery.clicks() }
override val inputContentIntent by lazy { message.inputContentSelected }
override val sendIntent by lazy { send.clicks() } override val sendIntent by lazy { send.clicks() }
@Inject lateinit var chipsAdapter: ChipsAdapter @Inject lateinit var chipsAdapter: ChipsAdapter
@@ -105,6 +105,7 @@ class ComposeActivity : QkThemedActivity<ComposeViewModel>(), ComposeView {
attachments.adapter = attachmentAdapter attachments.adapter = attachmentAdapter
messageBackground.backgroundTintMode = PorterDuff.Mode.MULTIPLY messageBackground.backgroundTintMode = PorterDuff.Mode.MULTIPLY
message.supportsInputContent = true
val states = arrayOf( val states = arrayOf(
intArrayOf(android.R.attr.state_enabled), intArrayOf(android.R.attr.state_enabled),
@@ -18,7 +18,6 @@
*/ */
package feature.compose package feature.compose
import android.net.Uri
import io.realm.RealmResults import io.realm.RealmResults
import model.Contact import model.Contact
import model.Conversation import model.Conversation
@@ -33,7 +32,7 @@ data class ComposeState(
val selectedContacts: List<Contact> = ArrayList(), val selectedContacts: List<Contact> = ArrayList(),
val title: String = "", val title: String = "",
val messages: Pair<Conversation, RealmResults<Message>>? = null, val messages: Pair<Conversation, RealmResults<Message>>? = null,
val attachments: List<Uri> = ArrayList(), val attachments: List<Attachment> = ArrayList(),
val attaching: Boolean = false, val attaching: Boolean = false,
val remaining: String = "", val remaining: String = "",
val canSend: Boolean = false val canSend: Boolean = false
@@ -18,7 +18,7 @@
*/ */
package feature.compose package feature.compose
import android.net.Uri import android.view.inputmethod.InputContentInfo
import common.MenuItem import common.MenuItem
import common.base.QkView import common.base.QkView
import io.reactivex.Observable import io.reactivex.Observable
@@ -41,11 +41,12 @@ interface ComposeView : QkView<ComposeState> {
val messageLongClickIntent: Subject<Message> val messageLongClickIntent: Subject<Message>
val cancelSendingIntent: Subject<Message> val cancelSendingIntent: Subject<Message>
val menuItemIntent: Subject<Int> val menuItemIntent: Subject<Int>
val attachmentDeletedIntent: Subject<Uri> val attachmentDeletedIntent: Subject<Attachment>
val textChangedIntent: Observable<CharSequence> val textChangedIntent: Observable<CharSequence>
val attachIntent: Observable<Unit> val attachIntent: Observable<Unit>
val cameraIntent: Observable<*> val cameraIntent: Observable<*>
val galleryIntent: Observable<*> val galleryIntent: Observable<*>
val inputContentIntent: Observable<InputContentInfo>
val sendIntent: Observable<Unit> val sendIntent: Observable<Unit>
fun showMenu(menuItems: List<MenuItem>) fun showMenu(menuItems: List<MenuItem>)
@@ -82,7 +82,7 @@ class ComposeViewModel(intent: Intent) : QkViewModel<ComposeView, ComposeState>(
@Inject lateinit var deleteMessage: DeleteMessage @Inject lateinit var deleteMessage: DeleteMessage
private var sharedText: String = "" private var sharedText: String = ""
private val attachments: Subject<List<Uri>> = BehaviorSubject.createDefault(ArrayList()) private val attachments: Subject<List<Attachment>> = BehaviorSubject.createDefault(ArrayList())
private val contacts: Observable<List<Contact>> by lazy { contactsRepo.getUnmanagedContacts().toObservable() } private val contacts: Observable<List<Contact>> by lazy { contactsRepo.getUnmanagedContacts().toObservable() }
private val contactsReducer: Subject<(List<Contact>) -> List<Contact>> = PublishSubject.create() private val contactsReducer: Subject<(List<Contact>) -> List<Contact>> = PublishSubject.create()
private val selectedContacts: Observable<List<Contact>> private val selectedContacts: Observable<List<Contact>>
@@ -103,7 +103,7 @@ class ComposeViewModel(intent: Intent) : QkViewModel<ComposeView, ComposeState>(
val sharedImages = mutableListOf<Uri>() val sharedImages = mutableListOf<Uri>()
intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)?.run { sharedImages += this } intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)?.run { sharedImages += this }
intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)?.run { sharedImages += this } intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)?.run { sharedImages += this }
attachments.onNext(sharedImages) attachments.onNext(sharedImages.map { uri -> Attachment(uri) })
val threadId = intent.extras?.getLong("threadId") ?: 0L val threadId = intent.extras?.getLong("threadId") ?: 0L
var address = "" var address = ""
@@ -358,6 +358,7 @@ class ComposeViewModel(intent: Intent) : QkViewModel<ComposeView, ComposeState>(
// Attach a photo from camera // Attach a photo from camera
view.cameraIntent view.cameraIntent
.flatMap { RxImagePicker.with(context).requestImage(Sources.CAMERA) } .flatMap { RxImagePicker.with(context).requestImage(Sources.CAMERA) }
.map { uri -> Attachment(uri) }
.withLatestFrom(attachments, { attachment, attachments -> attachments + attachment }) .withLatestFrom(attachments, { attachment, attachments -> attachments + attachment })
.doOnNext { attachments.onNext(it) } .doOnNext { attachments.onNext(it) }
.autoDisposable(view.scope()) .autoDisposable(view.scope())
@@ -366,6 +367,15 @@ class ComposeViewModel(intent: Intent) : QkViewModel<ComposeView, ComposeState>(
// Attach a photo from gallery // Attach a photo from gallery
view.galleryIntent view.galleryIntent
.flatMap { RxImagePicker.with(context).requestImage(Sources.GALLERY) } .flatMap { RxImagePicker.with(context).requestImage(Sources.GALLERY) }
.map { uri -> Attachment(uri) }
.withLatestFrom(attachments, { attachment, attachments -> attachments + attachment })
.doOnNext { attachments.onNext(it) }
.autoDisposable(view.scope())
.subscribe { newState { it.copy(attaching = false) } }
// Attach media from the keyboard
view.inputContentIntent
.map { inputContent -> Attachment(uri = null, inputContent = inputContent) }
.withLatestFrom(attachments, { attachment, attachments -> attachments + attachment }) .withLatestFrom(attachments, { attachment, attachments -> attachments + attachment })
.doOnNext { attachments.onNext(it) } .doOnNext { attachments.onNext(it) }
.autoDisposable(view.scope()) .autoDisposable(view.scope())
@@ -20,12 +20,12 @@ package interactor
import android.content.Context import android.content.Context
import android.graphics.Bitmap import android.graphics.Bitmap
import android.net.Uri
import com.google.android.mms.ContentType import com.google.android.mms.ContentType
import com.klinker.android.send_message.Message import com.klinker.android.send_message.Message
import com.klinker.android.send_message.Settings import com.klinker.android.send_message.Settings
import com.klinker.android.send_message.Transaction import com.klinker.android.send_message.Transaction
import com.mlsdev.rximagepicker.RxImageConverters import com.mlsdev.rximagepicker.RxImageConverters
import feature.compose.Attachment
import io.reactivex.Flowable import io.reactivex.Flowable
import repository.MessageRepository import repository.MessageRepository
import util.Preferences import util.Preferences
@@ -38,7 +38,7 @@ class SendMessage @Inject constructor(
private val messageRepo: MessageRepository private val messageRepo: MessageRepository
) : Interactor<SendMessage.Params>() { ) : Interactor<SendMessage.Params>() {
data class Params(val threadId: Long, val addresses: List<String>, val body: String, val attachments: List<Uri> = listOf()) data class Params(val threadId: Long, val addresses: List<String>, val body: String, val attachments: List<Attachment> = listOf())
override fun buildObservable(params: Params): Flowable<Unit> { override fun buildObservable(params: Params): Flowable<Unit> {
return Flowable.just(Unit) return Flowable.just(Unit)
@@ -54,7 +54,7 @@ class SendMessage @Inject constructor(
.doOnNext { messageRepo.markUnarchived(params.threadId) } .doOnNext { messageRepo.markUnarchived(params.threadId) }
} }
private fun sendMms(threadId: Long, addresses: List<String>, body: String, attachments: List<Uri>) { private fun sendMms(threadId: Long, addresses: List<String>, body: String, attachments: List<Attachment>) {
val settings = Settings() val settings = Settings()
val message = Message(body, addresses.toTypedArray()) val message = Message(body, addresses.toTypedArray())
@@ -62,7 +62,8 @@ class SendMessage @Inject constructor(
// in a lot of these messages failing to send // in a lot of these messages failing to send
// TODO Add support for GIF compression // TODO Add support for GIF compression
attachments attachments
.filter { uri -> context.contentResolver.getType(uri) == ContentType.IMAGE_GIF } .filter { attachment -> attachment.isGif(context) }
.map { attachment -> attachment.getUri() }
.map { uri -> context.contentResolver.openInputStream(uri) } .map { uri -> context.contentResolver.openInputStream(uri) }
.map { inputStream -> inputStream.readBytes() } .map { inputStream -> inputStream.readBytes() }
.forEach { bitmap -> message.addMedia(bitmap, ContentType.IMAGE_GIF) } .forEach { bitmap -> message.addMedia(bitmap, ContentType.IMAGE_GIF) }
@@ -70,7 +71,8 @@ class SendMessage @Inject constructor(
// Compress the images and add them as attachments // Compress the images and add them as attachments
var totalImageBytes = 0 var totalImageBytes = 0
attachments attachments
.filter { uri -> context.contentResolver.getType(uri) != ContentType.IMAGE_GIF } .filter { attachment -> !attachment.isGif(context) }
.map { attachment -> attachment.getUri() }
.map { uri -> RxImageConverters.uriToBitmap(context, uri).blockingFirst() } .map { uri -> RxImageConverters.uriToBitmap(context, uri).blockingFirst() }
.also { totalImageBytes = it.sumBy { it.allocationByteCount } } .also { totalImageBytes = it.sumBy { it.allocationByteCount } }
.map { bitmap -> .map { bitmap ->