Removed most '!!'

This commit is contained in:
Christian Basler 2017-09-01 07:29:44 +02:00
parent a23ae14f1d
commit 696cd6c0a6
19 changed files with 103 additions and 100 deletions

View File

@ -94,9 +94,9 @@ abstract class AbstractItemListFragment<L, T> : ListFragment(), ListHolder<L> {
override fun onSaveInstanceState(outState: Bundle?) { override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState) super.onSaveInstanceState(outState)
if (activatedPosition != ListView.INVALID_POSITION) { if (outState != null && activatedPosition != ListView.INVALID_POSITION) {
// Serialize and persist the activated item position. // Serialize and persist the activated item position.
outState!!.putInt(STATE_ACTIVATED_POSITION, activatedPosition) outState.putInt(STATE_ACTIVATED_POSITION, activatedPosition)
} }
} }

View File

@ -68,11 +68,12 @@ class AddressListFragment : AbstractItemListFragment<Void, BitmessageAddress>()
v = convertView.tag as ViewHolder v = convertView.tag as ViewHolder
result = convertView result = convertView
} }
val item = getItem(position)!! getItem(position)?.let { item ->
v.avatar.setImageDrawable(Identicon(item)) v.avatar.setImageDrawable(Identicon(item))
v.name.text = item.toString() v.name.text = item.toString()
v.streamNumber.text = v.ctx.getString(R.string.stream_number, item.stream) v.streamNumber.text = v.ctx.getString(R.string.stream_number, item.stream)
v.subscribed.visibility = if (item.isSubscribed) View.VISIBLE else View.INVISIBLE v.subscribed.visibility = if (item.isSubscribed) View.VISIBLE else View.INVISIBLE
}
return result return result
} }
} }

View File

@ -37,14 +37,17 @@ class ComposeMessageActivity : AppCompatActivity() {
setContentView(R.layout.toolbar_layout) setContentView(R.layout.toolbar_layout)
setSupportActionBar(toolbar) setSupportActionBar(toolbar)
supportActionBar!!.setHomeAsUpIndicator(R.drawable.ic_action_close) supportActionBar?.apply {
supportActionBar!!.setDisplayHomeAsUpEnabled(true) setHomeAsUpIndicator(R.drawable.ic_action_close)
supportActionBar!!.setHomeButtonEnabled(false) setDisplayHomeAsUpEnabled(true)
setHomeButtonEnabled(false)
}
// Display the fragment as the main content. // Display the fragment as the main content.
val fragment = ComposeMessageFragment() val fragment = ComposeMessageFragment()
fragment.arguments = intent.extras fragment.arguments = intent.extras
supportFragmentManager.beginTransaction() supportFragmentManager
.beginTransaction()
.replace(R.id.content, fragment) .replace(R.id.content, fragment)
.commit() .commit()
} }
@ -69,7 +72,7 @@ class ComposeMessageActivity : AppCompatActivity() {
private fun getReplyIntent(ctx: Context, item: Plaintext): Intent { private fun getReplyIntent(ctx: Context, item: Plaintext): Intent {
val replyIntent = Intent(ctx, ComposeMessageActivity::class.java) val replyIntent = Intent(ctx, ComposeMessageActivity::class.java)
val receivingIdentity = item.to val receivingIdentity = item.to
if (receivingIdentity!!.isChan) { if (receivingIdentity?.isChan ?: false) {
// reply to chan, not to the sender of the message // reply to chan, not to the sender of the message
replyIntent.putExtra(EXTRA_RECIPIENT, receivingIdentity) replyIntent.putExtra(EXTRA_RECIPIENT, receivingIdentity)
// I hate when people send as chan, so it won't be the default behaviour. // I hate when people send as chan, so it won't be the default behaviour.
@ -84,14 +87,14 @@ class ComposeMessageActivity : AppCompatActivity() {
replyIntent.putExtra(EXTRA_ENCODING, EXTENDED) replyIntent.putExtra(EXTRA_ENCODING, EXTENDED)
} }
replyIntent.putExtra(EXTRA_PARENT, item) replyIntent.putExtra(EXTRA_PARENT, item)
val prefix: String item.subject?.let { subject ->
if (item.subject!!.length >= 3 && item.subject!!.substring(0, 3) val prefix: String = if (subject.length >= 3 && subject.substring(0, 3).equals("RE:", ignoreCase = true)) {
.equals("RE:", ignoreCase = true)) { ""
prefix = ""
} else { } else {
prefix = "RE: " "RE: "
}
replyIntent.putExtra(EXTRA_SUBJECT, prefix + subject)
} }
replyIntent.putExtra(EXTRA_SUBJECT, prefix + item.subject!!)
replyIntent.putExtra(EXTRA_CONTENT, replyIntent.putExtra(EXTRA_CONTENT,
"\n\n------------------------------------------------------\n" + item.text!!) "\n\n------------------------------------------------------\n" + item.text!!)
return replyIntent return replyIntent

View File

@ -19,7 +19,9 @@ abstract class DetailActivity : AppCompatActivity() {
setSupportActionBar(toolbar) setSupportActionBar(toolbar)
// Show the Up button in the action bar. // Show the Up button in the action bar.
supportActionBar!!.setDisplayHomeAsUpEnabled(true) supportActionBar?.apply {
setDisplayHomeAsUpEnabled(true)
}
MaterializeBuilder() MaterializeBuilder()
.withActivity(this) .withActivity(this)

View File

@ -145,8 +145,8 @@ class MessageDetailFragment : Fragment() {
recyclerView.layoutManager = LinearLayoutManager(activity) recyclerView.layoutManager = LinearLayoutManager(activity)
} }
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater?) { override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater!!.inflate(R.menu.message, menu) inflater.inflate(R.menu.message, menu)
Drawables.addIcon(activity, menu, R.id.reply, GoogleMaterial.Icon.gmd_reply) Drawables.addIcon(activity, menu, R.id.reply, GoogleMaterial.Icon.gmd_reply)
Drawables.addIcon(activity, menu, R.id.delete, GoogleMaterial.Icon.gmd_delete) Drawables.addIcon(activity, menu, R.id.delete, GoogleMaterial.Icon.gmd_delete)

View File

@ -90,7 +90,7 @@ class MessageListFragment : Fragment(), ListHolder<Label> {
} }
override fun updateList(label: Label) { override fun updateList(label: Label) {
if (currentLabel != null && currentLabel != label && currentLabel != backStack.peek()) { if (currentLabel != null && currentLabel != label && (backStack.isEmpty() || currentLabel != backStack.peek())) {
backStack.push(currentLabel) backStack.push(currentLabel)
} }
if (!isResumed) { if (!isResumed) {

View File

@ -30,8 +30,10 @@ class StatusActivity : AppCompatActivity() {
setContentView(R.layout.activity_status) setContentView(R.layout.activity_status)
setSupportActionBar(toolbar) setSupportActionBar(toolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled(true) supportActionBar?.apply {
supportActionBar!!.setHomeButtonEnabled(false) setDisplayHomeAsUpEnabled(true)
setHomeButtonEnabled(false)
}
MaterializeBuilder() MaterializeBuilder()
.withActivity(this) .withActivity(this)

View File

@ -83,12 +83,9 @@ class ContactAdapter(ctx: Context) : BaseAdapter(), Filterable {
val newValues = ArrayList<BitmessageAddress>() val newValues = ArrayList<BitmessageAddress>()
for (i in originalData.indices) { originalData
val value = originalData[i] .forEach { value ->
value.alias?.toLowerCase()?.let { alias ->
// First match against the whole, non-splitted value
if (value.alias != null) {
val alias = value.alias!!.toLowerCase()
if (alias.startsWith(prefixString)) { if (alias.startsWith(prefixString)) {
newValues.add(value) newValues.add(value)
} else { } else {
@ -101,12 +98,12 @@ class ContactAdapter(ctx: Context) : BaseAdapter(), Filterable {
} }
} }
} }
} else { } ?: {
val address = value.address.toLowerCase() val address = value.address.toLowerCase()
if (address.contains(prefixString)) { if (address.contains(prefixString)) {
newValues.add(value) newValues.add(value)
} }
} }.invoke()
} }
results.values = newValues results.values = newValues

View File

@ -32,7 +32,6 @@ import ch.dissem.bitmessage.entity.payload.Pubkey
import kotlinx.android.synthetic.main.dialog_add_deterministic_identity.* import kotlinx.android.synthetic.main.dialog_add_deterministic_identity.*
import org.jetbrains.anko.doAsync import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread import org.jetbrains.anko.uiThread
import kotlinx.android.synthetic.main.dialog_add_deterministic_identity.*
/** /**
* @author Christian Basler * @author Christian Basler
@ -50,19 +49,17 @@ class DeterministicIdentityDialogFragment : AppCompatDialogFragment() {
return inflater.inflate(R.layout.dialog_add_deterministic_identity, container, false) return inflater.inflate(R.layout.dialog_add_deterministic_identity, container, false)
} }
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { override fun onViewCreated(dialogView: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState) super.onViewCreated(dialogView, savedInstanceState)
ok.setOnClickListener { ok.setOnClickListener {
dismiss() dismiss()
val context = activity.baseContext val context = activity.baseContext
val dialogView = getView()!! val passphraseText = passphrase.text.toString()
val passphrase = dialogView.findViewById(R.id.passphrase) as TextView
Toast.makeText(context, R.string.toast_long_running_operation, Toast.makeText(context, R.string.toast_long_running_operation, Toast.LENGTH_SHORT).show()
Toast.LENGTH_SHORT).show()
doAsync { doAsync {
val identities = bmc.createDeterministicAddresses( val identities = bmc.createDeterministicAddresses(
passphrase.text.toString(), passphraseText,
number_of_identities.text.toString().toInt(), number_of_identities.text.toString().toInt(),
Pubkey.LATEST_VERSION, Pubkey.LATEST_VERSION,
1L, 1L,

View File

@ -55,7 +55,7 @@ class NetworkNotification(ctx: Context) : AbstractNotification(ctx) {
val connections = BitmessageService.status.getProperty("network", "connections") val connections = BitmessageService.status.getProperty("network", "connections")
if (!running) { if (!running) {
builder.setContentText(ctx.getString(R.string.connection_info_disconnected)) builder.setContentText(ctx.getString(R.string.connection_info_disconnected))
} else if (connections!!.properties.isEmpty()) { } else if (connections == null || connections.properties.isEmpty()) {
builder.setContentText(ctx.getString(R.string.connection_info_pending)) builder.setContentText(ctx.getString(R.string.connection_info_pending))
} else { } else {
val info = StringBuilder() val info = StringBuilder()

View File

@ -45,8 +45,9 @@ class NewMessageNotification(ctx: Context) : AbstractNotification(ctx) {
fun singleNotification(plaintext: Plaintext): NewMessageNotification { fun singleNotification(plaintext: Plaintext): NewMessageNotification {
val builder = NotificationCompat.Builder(ctx) val builder = NotificationCompat.Builder(ctx)
val bigText = SpannableString(plaintext.subject + "\n" + plaintext.text) val bigText = SpannableString(plaintext.subject + "\n" + plaintext.text)
bigText.setSpan(SPAN_EMPHASIS, 0, plaintext.subject!!.length, Spanned plaintext.subject?.let { subject ->
.SPAN_INCLUSIVE_EXCLUSIVE) bigText.setSpan(SPAN_EMPHASIS, 0, subject.length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
}
builder.setSmallIcon(R.drawable.ic_notification_new_message) builder.setSmallIcon(R.drawable.ic_notification_new_message)
.setLargeIcon(toBitmap(Identicon(plaintext.from), 192)) .setLargeIcon(toBitmap(Identicon(plaintext.from), 192))
.setContentTitle(plaintext.from.toString()) .setContentTitle(plaintext.from.toString())

View File

@ -161,11 +161,12 @@ class AndroidMessageRepository(private val sql: SqlHelper, private val context:
private fun updateParents(db: SQLiteDatabase, message: Plaintext) { private fun updateParents(db: SQLiteDatabase, message: Plaintext) {
if (message.inventoryVector == null || message.parents.isEmpty()) { val inventoryVector = message.inventoryVector
if (inventoryVector == null || message.parents.isEmpty()) {
// There are no parents to save yet (they are saved in the extended data, that's enough for now) // There are no parents to save yet (they are saved in the extended data, that's enough for now)
return return
} }
val childIV = message.inventoryVector!!.hash val childIV = inventoryVector.hash
db.delete(PARENTS_TABLE_NAME, "child=?", arrayOf(hex(childIV))) db.delete(PARENTS_TABLE_NAME, "child=?", arrayOf(hex(childIV)))
// save new parents // save new parents
@ -347,7 +348,7 @@ class AndroidMessageRepository(private val sql: SqlHelper, private val context:
override fun remove(message: Plaintext) { override fun remove(message: Plaintext) {
val db = sql.writableDatabase val db = sql.writableDatabase
db.delete(TABLE_NAME, "id = " + message.id!!, null) db.delete(TABLE_NAME, "id = ?", arrayOf(message.id.toString()))
} }
companion object { companion object {

View File

@ -97,7 +97,7 @@ class SqlHelper(private val ctx: Context) : SQLiteOpenHelper(ctx, DATABASE_NAME,
companion object { companion object {
// If you change the database schema, you must increment the database version. // If you change the database schema, you must increment the database version.
private val DATABASE_VERSION = 7 private val DATABASE_VERSION = 7
private val DATABASE_NAME = "jabit.db" val DATABASE_NAME = "jabit.db"
internal fun join(vararg types: Enum<*>): String = types.joinToString(separator = "', '", prefix = "'", postfix = "'", transform = {it.name}) internal fun join(vararg types: Enum<*>): String = types.joinToString(separator = "', '", prefix = "'", postfix = "'", transform = {it.name})
} }

View File

@ -36,19 +36,21 @@ class BitmessageIntentService : IntentService("BitmessageIntentService") {
} }
override fun onHandleIntent(intent: Intent?) { override fun onHandleIntent(intent: Intent?) {
if (intent!!.hasExtra(EXTRA_DELETE_MESSAGE)) { intent?.let {
val item = intent.getSerializableExtra(EXTRA_DELETE_MESSAGE) as Plaintext if (it.hasExtra(EXTRA_DELETE_MESSAGE)) {
val item = it.getSerializableExtra(EXTRA_DELETE_MESSAGE) as Plaintext
bmc.labeler.delete(item) bmc.labeler.delete(item)
bmc.messages.save(item) bmc.messages.save(item)
Singleton.getMessageListener(this).resetNotification() Singleton.getMessageListener(this).resetNotification()
} }
if (intent.hasExtra(EXTRA_STARTUP_NODE)) { if (it.hasExtra(EXTRA_STARTUP_NODE)) {
NetworkUtils.enableNode(this) NetworkUtils.enableNode(this)
} }
if (intent.hasExtra(EXTRA_SHUTDOWN_NODE)) { if (it.hasExtra(EXTRA_SHUTDOWN_NODE)) {
NetworkUtils.disableNode(this) NetworkUtils.disableNode(this)
} }
} }
}
companion object { companion object {
const val EXTRA_DELETE_MESSAGE = "ch.dissem.abit.DeleteMessage" const val EXTRA_DELETE_MESSAGE = "ch.dissem.abit.DeleteMessage"

View File

@ -42,7 +42,7 @@ class ServicePowEngine(private val ctx: Context) : ProofOfWorkEngine {
synchronized(lock) { synchronized(lock) {
this@ServicePowEngine.service = service as PowBinder this@ServicePowEngine.service = service as PowBinder
while (!queue.isEmpty()) { while (!queue.isEmpty()) {
this@ServicePowEngine.service!!.process(queue.poll()) service.process(queue.poll())
} }
} }
} }
@ -57,8 +57,7 @@ class ServicePowEngine(private val ctx: Context) : ProofOfWorkEngine {
synchronized(lock) { synchronized(lock) {
service?.process(item) ?: { service?.process(item) ?: {
queue.add(item) queue.add(item)
ctx.bindService(Intent(ctx, ProofOfWorkService::class.java), connection, ctx.bindService(Intent(ctx, ProofOfWorkService::class.java), connection, BIND_AUTO_CREATE)
BIND_AUTO_CREATE)
}.invoke() }.invoke()
} }
} }

View File

@ -30,7 +30,6 @@ import ch.dissem.bitmessage.BitmessageContext
import ch.dissem.bitmessage.entity.BitmessageAddress import ch.dissem.bitmessage.entity.BitmessageAddress
import ch.dissem.bitmessage.entity.payload.Pubkey import ch.dissem.bitmessage.entity.payload.Pubkey
import ch.dissem.bitmessage.networking.nio.NioNetworkHandler import ch.dissem.bitmessage.networking.nio.NioNetworkHandler
import ch.dissem.bitmessage.ports.ProofOfWorkRepository
import ch.dissem.bitmessage.utils.ConversationService import ch.dissem.bitmessage.utils.ConversationService
import ch.dissem.bitmessage.utils.TTL import ch.dissem.bitmessage.utils.TTL
import ch.dissem.bitmessage.utils.UnixTime.DAY import ch.dissem.bitmessage.utils.UnixTime.DAY
@ -53,7 +52,8 @@ object Singleton {
return init({ bitmessageContext }, { bitmessageContext = it }) { return init({ bitmessageContext }, { bitmessageContext = it }) {
val ctx = context.applicationContext val ctx = context.applicationContext
val sqlHelper = SqlHelper(ctx) val sqlHelper = SqlHelper(ctx)
powRepo = AndroidProofOfWorkRepository(sqlHelper) val powRepo = AndroidProofOfWorkRepository(sqlHelper)
this.powRepo = powRepo
TTL.pubkey = 2 * DAY TTL.pubkey = 2 * DAY
BitmessageContext.Builder() BitmessageContext.Builder()
.proofOfWorkEngine(SwitchingProofOfWorkEngine( .proofOfWorkEngine(SwitchingProofOfWorkEngine(
@ -66,7 +66,7 @@ object Singleton {
.inventory(AndroidInventory(sqlHelper)) .inventory(AndroidInventory(sqlHelper))
.addressRepo(AndroidAddressRepository(sqlHelper)) .addressRepo(AndroidAddressRepository(sqlHelper))
.messageRepo(AndroidMessageRepository(sqlHelper, ctx)) .messageRepo(AndroidMessageRepository(sqlHelper, ctx))
.powRepo(powRepo!!) .powRepo(powRepo)
.networkHandler(NioNetworkHandler()) .networkHandler(NioNetworkHandler())
.listener(getMessageListener(ctx)) .listener(getMessageListener(ctx))
.doNotSendPubkeyOnIdentityCreation() .doNotSendPubkeyOnIdentityCreation()
@ -80,10 +80,7 @@ object Singleton {
fun getAddressRepository(ctx: Context) = getBitmessageContext(ctx).addresses as AndroidAddressRepository fun getAddressRepository(ctx: Context) = getBitmessageContext(ctx).addresses as AndroidAddressRepository
fun getProofOfWorkRepository(ctx: Context): ProofOfWorkRepository { fun getProofOfWorkRepository(ctx: Context) = powRepo ?: getBitmessageContext(ctx).internals.proofOfWorkRepository
if (powRepo == null) getBitmessageContext(ctx)
return powRepo!!
}
fun getIdentity(ctx: Context): BitmessageAddress? { fun getIdentity(ctx: Context): BitmessageAddress? {
return init<BitmessageAddress?>(ctx, { identity }, { identity = it }) { bmc -> return init<BitmessageAddress?>(ctx, { identity }, { identity = it }) { bmc ->

View File

@ -104,7 +104,7 @@ class SyncAdapter(context: Context, autoInitialize: Boolean) : AbstractThreadedS
// If the Bitmessage context acts as a full node, synchronization isn't necessary // If the Bitmessage context acts as a full node, synchronization isn't necessary
LOG.info("Looking for completed POW") LOG.info("Looking for completed POW")
val privateKey = identity.privateKey!!.privateEncryptionKey val privateKey = identity.privateKey?.privateEncryptionKey ?: throw IllegalStateException("Identity without private key")
val signingKey = cryptography().createPublicKey(identity.publicDecryptionKey) val signingKey = cryptography().createPublicKey(identity.publicDecryptionKey)
val reader = ProofOfWorkRequest.Reader(identity) val reader = ProofOfWorkRequest.Reader(identity)
val powRepo = Singleton.getProofOfWorkRepository(context) val powRepo = Singleton.getProofOfWorkRepository(context)

View File

@ -70,11 +70,12 @@ object Drawables {
if (address.alias != null) { if (address.alias != null) {
link.append("?label=").append(address.alias) link.append("?label=").append(address.alias)
} }
if (address.pubkey != null) { address.pubkey?.apply {
link.append(if (address.alias == null) '?' else '&') link.append(if (address.alias == null) '?' else '&')
val pubkey = ByteArrayOutputStream() val pubkey = ByteArrayOutputStream()
address.pubkey!!.writeUnencrypted(pubkey) writeUnencrypted(pubkey)
link.append("pubkey=").append(Base64.encodeToString(pubkey.toByteArray(), URL_SAFE or NO_WRAP)) link.append("pubkey=").append(Base64.encodeToString(pubkey.toByteArray(), URL_SAFE or NO_WRAP))
} }
val result: BitMatrix val result: BitMatrix
try { try {

View File

@ -10,7 +10,7 @@ import java.math.BigInteger
* POW statistics that might help estimate the POW time, depending on * POW statistics that might help estimate the POW time, depending on
*/ */
object PowStats { object PowStats {
private val TWO_POW_64 = BigInteger.valueOf(2).pow(64)!! private val TWO_POW_64: BigInteger = BigInteger.valueOf(2).pow(64)
var averagePowUnitTime = 0L var averagePowUnitTime = 0L
var powCount = 0L var powCount = 0L