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?) {
super.onSaveInstanceState(outState)
if (activatedPosition != ListView.INVALID_POSITION) {
if (outState != null && activatedPosition != ListView.INVALID_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
result = convertView
}
val item = getItem(position)!!
v.avatar.setImageDrawable(Identicon(item))
v.name.text = item.toString()
v.streamNumber.text = v.ctx.getString(R.string.stream_number, item.stream)
v.subscribed.visibility = if (item.isSubscribed) View.VISIBLE else View.INVISIBLE
getItem(position)?.let { item ->
v.avatar.setImageDrawable(Identicon(item))
v.name.text = item.toString()
v.streamNumber.text = v.ctx.getString(R.string.stream_number, item.stream)
v.subscribed.visibility = if (item.isSubscribed) View.VISIBLE else View.INVISIBLE
}
return result
}
}

View File

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

View File

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

View File

@ -145,8 +145,8 @@ class MessageDetailFragment : Fragment() {
recyclerView.layoutManager = LinearLayoutManager(activity)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater?) {
inflater!!.inflate(R.menu.message, menu)
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.message, menu)
Drawables.addIcon(activity, menu, R.id.reply, GoogleMaterial.Icon.gmd_reply)
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) {
if (currentLabel != null && currentLabel != label && currentLabel != backStack.peek()) {
if (currentLabel != null && currentLabel != label && (backStack.isEmpty() || currentLabel != backStack.peek())) {
backStack.push(currentLabel)
}
if (!isResumed) {

View File

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

View File

@ -83,31 +83,28 @@ class ContactAdapter(ctx: Context) : BaseAdapter(), Filterable {
val newValues = ArrayList<BitmessageAddress>()
for (i in originalData.indices) {
val value = originalData[i]
// First match against the whole, non-splitted value
if (value.alias != null) {
val alias = value.alias!!.toLowerCase()
if (alias.startsWith(prefixString)) {
newValues.add(value)
} else {
val words = alias.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
for (word in words) {
if (word.startsWith(prefixString)) {
originalData
.forEach { value ->
value.alias?.toLowerCase()?.let { alias ->
if (alias.startsWith(prefixString)) {
newValues.add(value)
break
} else {
val words = alias.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
for (word in words) {
if (word.startsWith(prefixString)) {
newValues.add(value)
break
}
}
}
}
} ?: {
val address = value.address.toLowerCase()
if (address.contains(prefixString)) {
newValues.add(value)
}
}.invoke()
}
} else {
val address = value.address.toLowerCase()
if (address.contains(prefixString)) {
newValues.add(value)
}
}
}
results.values = newValues
results.count = newValues.size

View File

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

View File

@ -41,11 +41,11 @@ class NetworkNotification(ctx: Context) : AbstractNotification(ctx) {
val showAppIntent = Intent(ctx, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(ctx, 1, showAppIntent, 0)
builder
.setSmallIcon(R.drawable.ic_notification_full_node)
.setContentTitle(ctx.getString(R.string.bitmessage_full_node))
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setShowWhen(false)
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_notification_full_node)
.setContentTitle(ctx.getString(R.string.bitmessage_full_node))
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setShowWhen(false)
.setContentIntent(pendingIntent)
}
@SuppressLint("StringFormatMatches")
@ -55,7 +55,7 @@ class NetworkNotification(ctx: Context) : AbstractNotification(ctx) {
val connections = BitmessageService.status.getProperty("network", "connections")
if (!running) {
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))
} else {
val info = StringBuilder()
@ -64,10 +64,10 @@ class NetworkNotification(ctx: Context) : AbstractNotification(ctx) {
val nodeCount = stream.getProperty("nodes")!!.value as Int?
if (nodeCount == 1) {
info.append(ctx.getString(R.string.connection_info_1,
streamNumber))
streamNumber))
} else {
info.append(ctx.getString(R.string.connection_info_n,
streamNumber, nodeCount))
streamNumber, nodeCount))
}
info.append('\n')
}
@ -78,13 +78,13 @@ class NetworkNotification(ctx: Context) : AbstractNotification(ctx) {
if (running) {
intent.putExtra(BitmessageIntentService.EXTRA_SHUTDOWN_NODE, true)
builder.addAction(R.drawable.ic_notification_node_stop,
ctx.getString(R.string.full_node_stop),
PendingIntent.getService(ctx, 0, intent, FLAG_UPDATE_CURRENT))
ctx.getString(R.string.full_node_stop),
PendingIntent.getService(ctx, 0, intent, FLAG_UPDATE_CURRENT))
} else {
intent.putExtra(BitmessageIntentService.EXTRA_STARTUP_NODE, true)
builder.addAction(R.drawable.ic_notification_node_start,
ctx.getString(R.string.full_node_restart),
PendingIntent.getService(ctx, 1, intent, FLAG_UPDATE_CURRENT))
ctx.getString(R.string.full_node_restart),
PendingIntent.getService(ctx, 1, intent, FLAG_UPDATE_CURRENT))
}
notification = builder.build()
return running
@ -117,8 +117,8 @@ class NetworkNotification(ctx: Context) : AbstractNotification(ctx) {
intent.putExtra(BitmessageIntentService.EXTRA_SHUTDOWN_NODE, true)
builder.mActions.clear()
builder.addAction(R.drawable.ic_notification_node_stop,
ctx.getString(R.string.full_node_stop),
PendingIntent.getService(ctx, 0, intent, FLAG_UPDATE_CURRENT))
ctx.getString(R.string.full_node_stop),
PendingIntent.getService(ctx, 0, intent, FLAG_UPDATE_CURRENT))
notification = builder.build()
}

View File

@ -45,8 +45,9 @@ class NewMessageNotification(ctx: Context) : AbstractNotification(ctx) {
fun singleNotification(plaintext: Plaintext): NewMessageNotification {
val builder = NotificationCompat.Builder(ctx)
val bigText = SpannableString(plaintext.subject + "\n" + plaintext.text)
bigText.setSpan(SPAN_EMPHASIS, 0, plaintext.subject!!.length, Spanned
.SPAN_INCLUSIVE_EXCLUSIVE)
plaintext.subject?.let { subject ->
bigText.setSpan(SPAN_EMPHASIS, 0, subject.length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE)
}
builder.setSmallIcon(R.drawable.ic_notification_new_message)
.setLargeIcon(toBitmap(Identicon(plaintext.from), 192))
.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) {
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)
return
}
val childIV = message.inventoryVector!!.hash
val childIV = inventoryVector.hash
db.delete(PARENTS_TABLE_NAME, "child=?", arrayOf(hex(childIV)))
// save new parents
@ -347,7 +348,7 @@ class AndroidMessageRepository(private val sql: SqlHelper, private val context:
override fun remove(message: Plaintext) {
val db = sql.writableDatabase
db.delete(TABLE_NAME, "id = " + message.id!!, null)
db.delete(TABLE_NAME, "id = ?", arrayOf(message.id.toString()))
}
companion object {

View File

@ -97,7 +97,7 @@ class SqlHelper(private val ctx: Context) : SQLiteOpenHelper(ctx, DATABASE_NAME,
companion object {
// If you change the database schema, you must increment the database version.
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})
}

View File

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

View File

@ -42,7 +42,7 @@ class ServicePowEngine(private val ctx: Context) : ProofOfWorkEngine {
synchronized(lock) {
this@ServicePowEngine.service = service as PowBinder
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) {
service?.process(item) ?: {
queue.add(item)
ctx.bindService(Intent(ctx, ProofOfWorkService::class.java), connection,
BIND_AUTO_CREATE)
ctx.bindService(Intent(ctx, ProofOfWorkService::class.java), connection, BIND_AUTO_CREATE)
}.invoke()
}
}

View File

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

View File

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

View File

@ -10,7 +10,7 @@ import java.math.BigInteger
* POW statistics that might help estimate the POW time, depending on
*/
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 powCount = 0L