translators = new ArrayList<>();
-
- /**
- * Specify the translators to be used at creation time.
- *
- * @param translators CharSequenceTranslator array to aggregate
- */
- public AggregateTranslator(final CharSequenceTranslator... translators) {
- if (translators != null) {
- for (CharSequenceTranslator translator : translators) {
- if (translator != null) {
- this.translators.add(translator);
- }
- }
- }
- }
-
- /**
- * The first translator to consume codepoints from the input is the 'winner'.
- * Execution stops with the number of consumed codepoints being returned.
- * {@inheritDoc}
- */
- @Override
- public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
- for (final CharSequenceTranslator translator : translators) {
- final int consumed = translator.translate(input, index, out);
- if (consumed != 0) {
- return consumed;
- }
- }
- return 0;
- }
-
-}
diff --git a/twidere/src/main/java/org/apache/commons/text/translate/CharSequenceTranslator.java b/twidere/src/main/java/org/apache/commons/text/translate/CharSequenceTranslator.java
deleted file mode 100644
index de6fa2e65f..0000000000
--- a/twidere/src/main/java/org/apache/commons/text/translate/CharSequenceTranslator.java
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.text.translate;
-
-import java.io.IOException;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.util.Locale;
-
-/**
- * An API for translating text.
- * Its core use is to escape and unescape text. Because escaping and unescaping
- * is completely contextual, the API does not present two separate signatures.
- *
- * @since 1.0
- */
-public abstract class CharSequenceTranslator {
-
- /**
- * Array containing the hexadecimal alphabet.
- */
- static final char[] HEX_DIGITS = new char[]{'0', '1', '2', '3',
- '4', '5', '6', '7',
- '8', '9', 'A', 'B',
- 'C', 'D', 'E', 'F'};
-
- /**
- * Translate a set of codepoints, represented by an int index into a CharSequence,
- * into another set of codepoints. The number of codepoints consumed must be returned,
- * and the only IOExceptions thrown must be from interacting with the Writer so that
- * the top level API may reliably ignore StringWriter IOExceptions.
- *
- * @param input CharSequence that is being translated
- * @param index int representing the current point of translation
- * @param out Writer to translate the text to
- * @return int count of codepoints consumed
- * @throws IOException if and only if the Writer produces an IOException
- */
- public abstract int translate(CharSequence input, int index, Writer out) throws IOException;
-
- /**
- * Helper for non-Writer usage.
- *
- * @param input CharSequence to be translated
- * @return String output of translation
- */
- public final String translate(final CharSequence input) {
- if (input == null) {
- return null;
- }
- try {
- final StringWriter writer = new StringWriter(input.length() * 2);
- translate(input, writer);
- return writer.toString();
- } catch (final IOException ioe) {
- // this should never ever happen while writing to a StringWriter
- throw new RuntimeException(ioe);
- }
- }
-
- /**
- * Translate an input onto a Writer. This is intentionally final as its algorithm is
- * tightly coupled with the abstract method of this class.
- *
- * @param input CharSequence that is being translated
- * @param out Writer to translate the text to
- * @throws IOException if and only if the Writer produces an IOException
- */
- public final void translate(final CharSequence input, final Writer out) throws IOException {
- if (out == null) throw new IllegalArgumentException("The Writer must not be null");
- if (input == null) {
- return;
- }
- int pos = 0;
- final int len = input.length();
- while (pos < len) {
- final int consumed = translate(input, pos, out);
- if (consumed == 0) {
- // inlined implementation of Character.toChars(Character.codePointAt(input, pos))
- // avoids allocating temp char arrays and duplicate checks
- final char c1 = input.charAt(pos);
- out.write(c1);
- pos++;
- if (Character.isHighSurrogate(c1) && pos < len) {
- final char c2 = input.charAt(pos);
- if (Character.isLowSurrogate(c2)) {
- out.write(c2);
- pos++;
- }
- }
- continue;
- }
- // contract with translators is that they have to understand codepoints
- // and they just took care of a surrogate pair
- for (int pt = 0; pt < consumed; pt++) {
- pos += Character.charCount(Character.codePointAt(input, pos));
- }
- }
- }
-
- /**
- * Helper method to create a merger of this translator with another set of
- * translators. Useful in customizing the standard functionality.
- *
- * @param translators CharSequenceTranslator array of translators to merge with this one
- * @return CharSequenceTranslator merging this translator with the others
- */
- public final CharSequenceTranslator with(final CharSequenceTranslator... translators) {
- final CharSequenceTranslator[] newArray = new CharSequenceTranslator[translators.length + 1];
- newArray[0] = this;
- System.arraycopy(translators, 0, newArray, 1, translators.length);
- return new AggregateTranslator(newArray);
- }
-
- /**
- * Returns an upper case hexadecimal String
for the given
- * character.
- *
- * @param codepoint The codepoint to convert.
- * @return An upper case hexadecimal String
- */
- public static String hex(final int codepoint) {
- return Integer.toHexString(codepoint).toUpperCase(Locale.ENGLISH);
- }
-
-}
diff --git a/twidere/src/main/java/org/apache/commons/text/translate/CodePointTranslator.java b/twidere/src/main/java/org/apache/commons/text/translate/CodePointTranslator.java
deleted file mode 100644
index 71828be069..0000000000
--- a/twidere/src/main/java/org/apache/commons/text/translate/CodePointTranslator.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.text.translate;
-
-import java.io.IOException;
-import java.io.Writer;
-
-/**
- * Helper subclass to CharSequenceTranslator to allow for translations that
- * will replace up to one character at a time.
- *
- * @since 1.0
- */
-public abstract class CodePointTranslator extends CharSequenceTranslator {
-
- /**
- * Implementation of translate that maps onto the abstract translate(int, Writer) method.
- * {@inheritDoc}
- */
- @Override
- public final int translate(final CharSequence input, final int index, final Writer out) throws IOException {
- final int codepoint = Character.codePointAt(input, index);
- final boolean consumed = translate(codepoint, out);
- return consumed ? 1 : 0;
- }
-
- /**
- * Translate the specified codepoint into another.
- *
- * @param codepoint int character input to translate
- * @param out Writer to optionally push the translated output to
- * @return boolean as to whether translation occurred or not
- * @throws IOException if and only if the Writer produces an IOException
- */
- public abstract boolean translate(int codepoint, Writer out) throws IOException;
-
-}
diff --git a/twidere/src/main/java/org/apache/commons/text/translate/LookupTranslator.java b/twidere/src/main/java/org/apache/commons/text/translate/LookupTranslator.java
deleted file mode 100644
index c4d5e2ee66..0000000000
--- a/twidere/src/main/java/org/apache/commons/text/translate/LookupTranslator.java
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.text.translate;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.security.InvalidParameterException;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.Map;
-
-/**
- * Translates a value using a lookup table.
- *
- * @since 1.0
- */
-public class LookupTranslator extends CharSequenceTranslator {
-
- /** The mapping to be used in translation. */
- private final Map lookupMap;
- /** The first character of each key in the lookupMap. */
- private final HashSet prefixSet;
- /** The length of the shortest key in the lookupMap. */
- private final int shortest;
- /** The length of the longest key in the lookupMap. */
- private final int longest;
-
- /**
- * Define the lookup table to be used in translation
- *
- * Note that, as of Lang 3.1 (the orgin of this code), the key to the lookup
- * table is converted to a java.lang.String. This is because we need the key
- * to support hashCode and equals(Object), allowing it to be the key for a
- * HashMap. See LANG-882.
- *
- * @param lookupMap Map<CharSequence, CharSequence> table of translator
- * mappings
- */
- public LookupTranslator(final Map lookupMap) {
- if (lookupMap == null) {
- throw new InvalidParameterException("lookupMap cannot be null");
- }
- this.lookupMap = new HashMap<>();
- this.prefixSet = new HashSet<>();
- int currentShortest = Integer.MAX_VALUE;
- int currentLongest = 0;
- Iterator> it = lookupMap.entrySet().iterator();
-
- while (it.hasNext()) {
- Map.Entry pair = it.next();
- this.lookupMap.put(pair.getKey().toString(), pair.getValue().toString());
- this.prefixSet.add(pair.getKey().charAt(0));
- final int sz = pair.getKey().length();
- if (sz < currentShortest) {
- currentShortest = sz;
- }
- if (sz > currentLongest) {
- currentLongest = sz;
- }
- }
- this.shortest = currentShortest;
- this.longest = currentLongest;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
- // check if translation exists for the input at position index
- if (prefixSet.contains(input.charAt(index))) {
- int max = longest;
- if (index + longest > input.length()) {
- max = input.length() - index;
- }
- // implement greedy algorithm by trying maximum match first
- for (int i = max; i >= shortest; i--) {
- final CharSequence subSeq = input.subSequence(index, index + i);
- final String result = lookupMap.get(subSeq.toString());
-
- if (result != null) {
- out.write(result);
- return i;
- }
- }
- }
- return 0;
- }
-}
diff --git a/twidere/src/main/java/org/apache/commons/text/translate/NumericEntityUnescaper.java b/twidere/src/main/java/org/apache/commons/text/translate/NumericEntityUnescaper.java
deleted file mode 100644
index 66704dd1a5..0000000000
--- a/twidere/src/main/java/org/apache/commons/text/translate/NumericEntityUnescaper.java
+++ /dev/null
@@ -1,139 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.text.translate;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Arrays;
-import java.util.EnumSet;
-
-/**
- * Translate XML numeric entities of the form &#[xX]?\d+;? to
- * the specific codepoint.
- *
- * Note that the semi-colon is optional.
- *
- * @since 1.0
- */
-public class NumericEntityUnescaper extends CharSequenceTranslator {
-
- /** NumericEntityUnescaper option enum. */
- public enum OPTION { semiColonRequired, semiColonOptional, errorIfNoSemiColon }
-
- /** EnumSet of OPTIONS, given from the constructor. */
- private final EnumSet options;
-
- /**
- * Create a UnicodeUnescaper.
- *
- * The constructor takes a list of options, only one type of which is currently
- * available (whether to allow, error or ignore the semi-colon on the end of a
- * numeric entity to being missing).
- *
- * For example, to support numeric entities without a ';':
- * new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.semiColonOptional)
- * and to throw an IllegalArgumentException when they're missing:
- * new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.errorIfNoSemiColon)
- *
- * Note that the default behaviour is to ignore them.
- *
- * @param options to apply to this unescaper
- */
- public NumericEntityUnescaper(final OPTION... options) {
- if (options.length > 0) {
- this.options = EnumSet.copyOf(Arrays.asList(options));
- } else {
- this.options = EnumSet.of(OPTION.semiColonRequired);
- }
- }
-
- /**
- * Whether the passed in option is currently set.
- *
- * @param option to check state of
- * @return whether the option is set
- */
- public boolean isSet(final OPTION option) {
- return options != null && options.contains(option);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
- final int seqEnd = input.length();
- // Uses -2 to ensure there is something after the
- if (input.charAt(index) == '&' && index < seqEnd - 2 && input.charAt(index + 1) == '#') {
- int start = index + 2;
- boolean isHex = false;
-
- final char firstChar = input.charAt(start);
- if (firstChar == 'x' || firstChar == 'X') {
- start++;
- isHex = true;
-
- // Check there's more than just an x after the
- if (start == seqEnd) {
- return 0;
- }
- }
-
- int end = start;
- // Note that this supports character codes without a ; on the end
- while (end < seqEnd && (input.charAt(end) >= '0' && input.charAt(end) <= '9'
- || input.charAt(end) >= 'a' && input.charAt(end) <= 'f'
- || input.charAt(end) >= 'A' && input.charAt(end) <= 'F')) {
- end++;
- }
-
- final boolean semiNext = end != seqEnd && input.charAt(end) == ';';
-
- if (!semiNext) {
- if (isSet(OPTION.semiColonRequired)) {
- return 0;
- } else {
- if (isSet(OPTION.errorIfNoSemiColon)) {
- throw new IllegalArgumentException("Semi-colon required at end of numeric entity");
- }
- }
- }
-
- int entityValue;
- try {
- if (isHex) {
- entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16);
- } else {
- entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10);
- }
- } catch (final NumberFormatException nfe) {
- return 0;
- }
-
- if (entityValue > 0xFFFF) {
- final char[] chrs = Character.toChars(entityValue);
- out.write(chrs[0]);
- out.write(chrs[1]);
- } else {
- out.write(entityValue);
- }
-
- return 2 + end - start + (isHex ? 1 : 0) + (semiNext ? 1 : 0);
- }
- return 0;
- }
-}
diff --git a/twidere/src/main/java/org/mariotaku/twidere/Constants.java b/twidere/src/main/java/org/mariotaku/twidere/Constants.java
index 5a1fdf1c82..edb9331c8d 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/Constants.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/Constants.java
@@ -91,6 +91,7 @@ public interface Constants extends TwidereConstants {
String TWIDERE_PREVIEW_NAME = "Twidere Project";
String TWIDERE_PREVIEW_SCREEN_NAME = "TwidereProject";
String TWIDERE_PREVIEW_TEXT_HTML = "Twidere is an open source twitter client for Android, see github.com/mariotak… ";
+ String TWIDERE_PREVIEW_LINK_URI = "https://github.com/TwidereProject/Twidere-Android";
String TWIDERE_PREVIEW_TEXT_UNESCAPED = "Twidere is an open source twitter client for Android, see github.com/mariotak…";
String TWIDERE_PREVIEW_SOURCE = "Twidere for Android";
diff --git a/twidere/src/main/java/org/mariotaku/twidere/adapter/ArrayAdapter.java b/twidere/src/main/java/org/mariotaku/twidere/adapter/ArrayAdapter.java
index decef593e4..2cd96943ed 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/adapter/ArrayAdapter.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/adapter/ArrayAdapter.java
@@ -101,7 +101,7 @@ public class ArrayAdapter extends BaseAdapter implements Filterable {
* instantiating views.
*/
public ArrayAdapter(Context context, int resource) {
- init(context, resource, new ArrayList());
+ init(context, resource, new ArrayList<>());
}
/**
diff --git a/twidere/src/main/java/org/mariotaku/twidere/adapter/decorator/ExtendedDividerItemDecoration.java b/twidere/src/main/java/org/mariotaku/twidere/adapter/decorator/ExtendedDividerItemDecoration.java
index 595d869350..ddff1c4940 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/adapter/decorator/ExtendedDividerItemDecoration.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/adapter/decorator/ExtendedDividerItemDecoration.java
@@ -84,12 +84,9 @@ public void onDraw(Canvas c, RecyclerView parent, State state) {
}
public void setPadding(final int left, final int top, final int right, final int bottom) {
- mPadding = new Padding() {
- @Override
- public boolean get(int position, Rect rect) {
- rect.set(left, top, right, bottom);
- return true;
- }
+ mPadding = (position, rect) -> {
+ rect.set(left, top, right, bottom);
+ return true;
};
}
diff --git a/twidere/src/main/java/org/mariotaku/twidere/fragment/DataExportImportTypeSelectorDialogFragment.java b/twidere/src/main/java/org/mariotaku/twidere/fragment/DataExportImportTypeSelectorDialogFragment.java
index ab3f95d0af..1e6817c91f 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/fragment/DataExportImportTypeSelectorDialogFragment.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/fragment/DataExportImportTypeSelectorDialogFragment.java
@@ -66,12 +66,9 @@ public void onCancel(final DialogInterface dialog) {
@Override
public final void onClick(final DialogInterface dialog, final int which) {
- switch (which) {
- case DialogInterface.BUTTON_POSITIVE: {
- final int flags = getCheckedFlags();
- onPositiveButtonClicked(flags);
- break;
- }
+ if (which == DialogInterface.BUTTON_POSITIVE) {
+ final int flags = getCheckedFlags();
+ onPositiveButtonClicked(flags);
}
}
diff --git a/twidere/src/main/java/org/mariotaku/twidere/fragment/FileSelectorDialogFragment.java b/twidere/src/main/java/org/mariotaku/twidere/fragment/FileSelectorDialogFragment.java
index e6569702d8..b3848a953d 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/fragment/FileSelectorDialogFragment.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/fragment/FileSelectorDialogFragment.java
@@ -118,14 +118,11 @@ public Dialog onCreateDialog(final Bundle savedInstanceState) {
builder.setPositiveButton(android.R.string.ok, this);
}
final AlertDialog dialog = builder.create();
- dialog.setOnShowListener(new DialogInterface.OnShowListener() {
- @Override
- public void onShow(final DialogInterface dialog) {
- final AlertDialog alertDialog = (AlertDialog) dialog;
- DialogExtensionsKt.applyTheme(alertDialog);
- final ListView listView = alertDialog.getListView();
- listView.setOnItemClickListener(FileSelectorDialogFragment.this);
- }
+ dialog.setOnShowListener(dialog1 -> {
+ final AlertDialog alertDialog = (AlertDialog) dialog1;
+ DialogExtensionsKt.applyTheme(alertDialog);
+ final ListView listView = alertDialog.getListView();
+ listView.setOnItemClickListener(FileSelectorDialogFragment.this);
});
return dialog;
}
@@ -268,12 +265,9 @@ private static class FilesLoader extends FixedAsyncTaskLoader> {
private final String[] extensions;
private final Pattern extensions_regex;
- private static final Comparator NAME_COMPARATOR = new Comparator() {
- @Override
- public int compare(final File file1, final File file2) {
- final Locale loc = Locale.getDefault();
- return file1.getName().toLowerCase(loc).compareTo(file2.getName().toLowerCase(loc));
- }
+ private static final Comparator NAME_COMPARATOR = (file1, file2) -> {
+ final Locale loc = Locale.getDefault();
+ return file1.getName().toLowerCase(loc).compareTo(file2.getName().toLowerCase(loc));
};
public FilesLoader(final Context context, final File path, final String[] extensions) {
diff --git a/twidere/src/main/java/org/mariotaku/twidere/fragment/KeyboardShortcutsFragment.java b/twidere/src/main/java/org/mariotaku/twidere/fragment/KeyboardShortcutsFragment.java
index da22ce0321..866fc293ee 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/fragment/KeyboardShortcutsFragment.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/fragment/KeyboardShortcutsFragment.java
@@ -24,7 +24,6 @@
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
-import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import androidx.annotation.NonNull;
@@ -66,12 +65,10 @@ public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
@Override
public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case R.id.reset: {
- final DialogFragment f = new ResetKeyboardShortcutConfirmDialogFragment();
- f.show(getFragmentManager(), "reset_keyboard_shortcut_confirm");
- return true;
- }
+ if (item.getItemId() == R.id.reset) {
+ final DialogFragment f = new ResetKeyboardShortcutConfirmDialogFragment();
+ f.show(getFragmentManager(), "reset_keyboard_shortcut_confirm");
+ return true;
}
return super.onOptionsItemSelected(item);
}
@@ -90,12 +87,7 @@ public KeyboardShortcutPreferenceCompat(final Context context, final KeyboardSho
mAction = action;
setPersistent(false);
setTitle(KeyboardShortcutsHandler.getActionLabel(context, action));
- mPreferencesChangeListener = new OnSharedPreferenceChangeListener() {
- @Override
- public void onSharedPreferenceChanged(SharedPreferences preferences, String key) {
- updateSummary();
- }
- };
+ mPreferencesChangeListener = (preferences, key) -> updateSummary();
updateSummary();
}
@@ -103,8 +95,8 @@ public void onSharedPreferenceChanged(SharedPreferences preferences, String key)
protected void onClick() {
final Context context = getContext();
final Intent intent = new Intent(context, KeyboardShortcutPreferenceCompatActivity.class);
- intent.putExtra(KeyboardShortcutPreferenceCompatActivity.Companion.getEXTRA_CONTEXT_TAG(), mContextTag);
- intent.putExtra(KeyboardShortcutPreferenceCompatActivity.Companion.getEXTRA_KEY_ACTION(), mAction);
+ intent.putExtra(KeyboardShortcutPreferenceCompatActivity.EXTRA_CONTEXT_TAG, mContextTag);
+ intent.putExtra(KeyboardShortcutPreferenceCompatActivity.EXTRA_KEY_ACTION, mAction);
context.startActivity(intent);
}
@@ -132,11 +124,8 @@ public static class ResetKeyboardShortcutConfirmDialogFragment extends BaseDialo
implements OnClickListener {
@Override
public void onClick(DialogInterface dialog, int which) {
- switch (which) {
- case DialogInterface.BUTTON_POSITIVE: {
- keyboardShortcutsHandler.reset();
- break;
- }
+ if (which == DialogInterface.BUTTON_POSITIVE) {
+ keyboardShortcutsHandler.reset();
}
}
@@ -148,12 +137,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) {
builder.setPositiveButton(android.R.string.ok, this);
builder.setNegativeButton(android.R.string.cancel, this);
final AlertDialog dialog = builder.create();
- dialog.setOnShowListener(new DialogInterface.OnShowListener() {
- @Override
- public void onShow(final DialogInterface dialog) {
- DialogExtensionsKt.applyTheme((AlertDialog) dialog);
- }
- });
+ dialog.setOnShowListener(dialog1 -> DialogExtensionsKt.applyTheme((AlertDialog) dialog1));
return dialog;
}
}
diff --git a/twidere/src/main/java/org/mariotaku/twidere/fragment/ThemedListPreferenceDialogFragmentCompat.java b/twidere/src/main/java/org/mariotaku/twidere/fragment/ThemedListPreferenceDialogFragmentCompat.java
index 9cc1cb1067..4455099f83 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/fragment/ThemedListPreferenceDialogFragmentCompat.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/fragment/ThemedListPreferenceDialogFragmentCompat.java
@@ -47,24 +47,21 @@ protected void onPrepareDialogBuilder(AlertDialog.Builder builder) {
}
mClickedDialogEntryIndex = preference.findIndexOfValue(preference.getValue());
builder.setSingleChoiceItems(entries, mClickedDialogEntryIndex,
- new DialogInterface.OnClickListener() {
- public void onClick(DialogInterface dialog, int which) {
- mClickedDialogEntryIndex = which;
- /*
- * Clicking on an item simulates the positive button
- * click, and dismisses the dialog.
- */
- ThemedListPreferenceDialogFragmentCompat.this.onClick(dialog,
- DialogInterface.BUTTON_POSITIVE);
- dialog.dismiss();
- }
+ (dialog, which) -> {
+ mClickedDialogEntryIndex = which;
+ /*
+ * Clicking on an item simulates the positive button
+ * click, and dismisses the dialog.
+ */
+ ThemedListPreferenceDialogFragmentCompat.this.onClick(dialog,
+ DialogInterface.BUTTON_POSITIVE);
+ dialog.dismiss();
});
/*
* The typical interaction for list-based dialogs is to have
* click-on-an-item dismiss the dialog instead of the user having to
* press 'Ok'.
*/
- //noinspection ConstantConditions
builder.setPositiveButton(null, null);
}
diff --git a/twidere/src/main/java/org/mariotaku/twidere/loader/ObjectCursorLoader.java b/twidere/src/main/java/org/mariotaku/twidere/loader/ObjectCursorLoader.java
index 9abba3bd68..f8f87302ea 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/loader/ObjectCursorLoader.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/loader/ObjectCursorLoader.java
@@ -68,7 +68,6 @@ protected ObjectCursor createObjectCursor(Cursor cursor, ObjectCursor.CursorI
return new ObjectCursor<>(cursor, indices, mUseCache);
}
- @SuppressWarnings("TryWithIdenticalCatches")
@NonNull
private ObjectCursor.CursorIndices createIndices(final Cursor cursor) {
return ObjectCursor.indicesFrom(cursor, mObjectClass);
diff --git a/twidere/src/main/java/org/mariotaku/twidere/model/CronExpression.java b/twidere/src/main/java/org/mariotaku/twidere/model/CronExpression.java
index f6321ccbc1..8cabe426b6 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/model/CronExpression.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/model/CronExpression.java
@@ -447,7 +447,7 @@ private static String[] split(@NonNull final String str, final char separatorCha
if (match) {
list.add(str.substring(start, i));
}
- return list.toArray(new String[list.size()]);
+ return list.toArray(new String[0]);
}
}
diff --git a/twidere/src/main/java/org/mariotaku/twidere/model/tab/DrawableHolder.java b/twidere/src/main/java/org/mariotaku/twidere/model/tab/DrawableHolder.java
index 6249d6b75c..7b5a61a041 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/model/tab/DrawableHolder.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/model/tab/DrawableHolder.java
@@ -92,11 +92,7 @@ public void setName(String name) {
}
public static DrawableHolder parse(String str) {
- DrawableHolder icon = builtin(str);
- if (icon != null) {
- return icon;
- }
- return null;
+ return builtin(str);
}
public static List builtins() {
diff --git a/twidere/src/main/java/org/mariotaku/twidere/preference/MultiSelectListPreference.java b/twidere/src/main/java/org/mariotaku/twidere/preference/MultiSelectListPreference.java
index 40f003f7a1..b4e77996b1 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/preference/MultiSelectListPreference.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/preference/MultiSelectListPreference.java
@@ -100,12 +100,7 @@ public Dialog onCreateDialog(Bundle savedInstanceState) {
builder.setNegativeButton(android.R.string.cancel, null);
builder.setMultiChoiceItems(mNames, mValues, this);
final AlertDialog dialog = builder.create();
- dialog.setOnShowListener(new DialogInterface.OnShowListener() {
- @Override
- public void onShow(final DialogInterface dialog) {
- DialogExtensionsKt.applyTheme((AlertDialog) dialog);
- }
- });
+ dialog.setOnShowListener(dialog1 -> DialogExtensionsKt.applyTheme((AlertDialog) dialog1));
return dialog;
}
diff --git a/twidere/src/main/java/org/mariotaku/twidere/preference/SettingsImportExportPreference.java b/twidere/src/main/java/org/mariotaku/twidere/preference/SettingsImportExportPreference.java
index 7c9bbdb740..7d520e36ca 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/preference/SettingsImportExportPreference.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/preference/SettingsImportExportPreference.java
@@ -21,7 +21,6 @@
import android.app.Dialog;
import android.content.Context;
-import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
@@ -78,19 +77,9 @@ public Dialog onCreateDialog(Bundle savedInstanceState) {
entries[1] = context.getString(R.string.export_settings);
values[0] = new Intent(context, DataImportActivity.class);
values[1] = new Intent(context, DataExportActivity.class);
- builder.setItems(entries, new DialogInterface.OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- startActivity(values[which]);
- }
- });
+ builder.setItems(entries, (dialog, which) -> startActivity(values[which]));
final AlertDialog dialog = builder.create();
- dialog.setOnShowListener(new DialogInterface.OnShowListener() {
- @Override
- public void onShow(final DialogInterface dialog) {
- DialogExtensionsKt.applyTheme((AlertDialog) dialog);
- }
- });
+ dialog.setOnShowListener(dialog1 -> DialogExtensionsKt.applyTheme((AlertDialog) dialog1));
return dialog;
}
diff --git a/twidere/src/main/java/org/mariotaku/twidere/preference/ThemeBackgroundPreference.java b/twidere/src/main/java/org/mariotaku/twidere/preference/ThemeBackgroundPreference.java
index bc73466493..ad66c6aefa 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/preference/ThemeBackgroundPreference.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/preference/ThemeBackgroundPreference.java
@@ -2,8 +2,6 @@
import android.app.Dialog;
import android.content.Context;
-import android.content.DialogInterface;
-import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Bundle;
@@ -17,7 +15,6 @@
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
-import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SeekBar;
@@ -160,42 +157,33 @@ public Dialog onCreateDialog(Bundle savedInstanceState) {
final SharedPreferences preferences = preference.getSharedPreferences();
preference.setValue(preference.getPersistedString(null));
builder.setTitle(preference.getDialogTitle());
- builder.setSingleChoiceItems(preference.mBackgroundEntries, preference.getValueIndex(), new OnClickListener() {
- @Override
- public void onClick(DialogInterface dialog, int which) {
- preference.setSelectedOption(which);
- updateAlphaVisibility();
- }
+ builder.setSingleChoiceItems(preference.mBackgroundEntries, preference.getValueIndex(), (dialog, which) -> {
+ preference.setSelectedOption(which);
+ updateAlphaVisibility();
});
builder.setPositiveButton(android.R.string.ok, this);
builder.setNegativeButton(android.R.string.cancel, this);
final Dialog dialog = builder.create();
- dialog.setOnShowListener(new DialogInterface.OnShowListener() {
- @Override
- public void onShow(DialogInterface dialog) {
- final AlertDialog alertDialog = (AlertDialog) dialog;
- DialogExtensionsKt.applyTheme(alertDialog);
- if (preferences != null) {
- final LayoutInflater inflater = alertDialog.getLayoutInflater();
- final ListView listView = alertDialog.getListView();
- assert listView != null;
- final ViewGroup listViewParent = (ViewGroup) listView.getParent();
- listViewParent.removeView(listView);
- final View view = inflater.inflate(R.layout.dialog_theme_background_preference, listViewParent);
- ((ViewGroup) view.findViewById(R.id.list_container)).addView(listView);
- mAlphaContainer = view.findViewById(R.id.alpha_container);
- mAlphaSlider = view.findViewById(R.id.alpha_slider);
- mAlphaSlider.setMax(MAX_ALPHA - MIN_ALPHA);
- mAlphaSlider.setProgress(preferences.getInt(KEY_THEME_BACKGROUND_ALPHA, DEFAULT_THEME_BACKGROUND_ALPHA) - MIN_ALPHA);
- listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView> parent, View view, int position, long id) {
- preference.setSelectedOption(position);
- updateAlphaVisibility();
- }
- });
+ dialog.setOnShowListener(dialog1 -> {
+ final AlertDialog alertDialog = (AlertDialog) dialog1;
+ DialogExtensionsKt.applyTheme(alertDialog);
+ if (preferences != null) {
+ final LayoutInflater inflater = alertDialog.getLayoutInflater();
+ final ListView listView = alertDialog.getListView();
+ assert listView != null;
+ final ViewGroup listViewParent = (ViewGroup) listView.getParent();
+ listViewParent.removeView(listView);
+ final View view = inflater.inflate(R.layout.dialog_theme_background_preference, listViewParent);
+ ((ViewGroup) view.findViewById(R.id.list_container)).addView(listView);
+ mAlphaContainer = view.findViewById(R.id.alpha_container);
+ mAlphaSlider = view.findViewById(R.id.alpha_slider);
+ mAlphaSlider.setMax(MAX_ALPHA - MIN_ALPHA);
+ mAlphaSlider.setProgress(preferences.getInt(KEY_THEME_BACKGROUND_ALPHA, DEFAULT_THEME_BACKGROUND_ALPHA) - MIN_ALPHA);
+ listView.setOnItemClickListener((parent, view1, position, id) -> {
+ preference.setSelectedOption(position);
updateAlphaVisibility();
- }
+ });
+ updateAlphaVisibility();
}
});
return dialog;
diff --git a/twidere/src/main/java/org/mariotaku/twidere/util/AbsServiceInterface.java b/twidere/src/main/java/org/mariotaku/twidere/util/AbsServiceInterface.java
index 254a2a4128..f678104a97 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/util/AbsServiceInterface.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/util/AbsServiceInterface.java
@@ -31,7 +31,6 @@
import org.mariotaku.twidere.constant.IntentConstants;
import org.mariotaku.twidere.util.ServiceUtils.ServiceToken;
-import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
@@ -73,12 +72,7 @@ public final boolean waitForService() {
final Intent intent = new Intent(IntentConstants.INTENT_ACTION_EXTENSION_SHORTEN_STATUS);
final ComponentName component = ComponentName.unflattenFromString(mShortenerName);
intent.setComponent(component);
- final FutureTask futureTask = new FutureTask<>(new Callable() {
- @Override
- public Boolean call() throws Exception {
- return mIInterface != null;
- }
- });
+ final FutureTask futureTask = new FutureTask<>(() -> mIInterface != null);
mToken = ServiceUtils.bindToService(mContext, intent, new ServiceConnection() {
@Override
public void onServiceConnected(final ComponentName name, final IBinder obj) {
@@ -112,7 +106,6 @@ public final void checkService(CheckServiceAction action) throws CheckServiceExc
}
public interface CheckServiceAction {
- @SuppressWarnings("RedundantThrows")
void check(@Nullable Bundle metaData) throws CheckServiceException;
}
diff --git a/twidere/src/main/java/org/mariotaku/twidere/util/DataImportExportUtils.java b/twidere/src/main/java/org/mariotaku/twidere/util/DataImportExportUtils.java
index 65d4dbe699..dc1966a104 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/util/DataImportExportUtils.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/util/DataImportExportUtils.java
@@ -26,6 +26,7 @@
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
+import android.os.Build;
import androidx.annotation.NonNull;
import androidx.annotation.WorkerThread;
@@ -169,7 +170,7 @@ public static int getImportedSettingsFlags(@NonNull final Context context, @NonN
ZipInputStream zipInputStream = new ZipInputStream(inputStream)) {
int flags = 0;
List entryNames = new ArrayList<>();
- ZipEntry entry = null;
+ ZipEntry entry;
while ((entry = zipInputStream.getNextEntry()) != null) {
entryNames.add(entry.getName());
}
@@ -203,11 +204,11 @@ public static void importData(final Context context, final DocumentFile src, fin
try (InputStream inputStream = context.getContentResolver().openInputStream(src.getUri());
ZipInputStream zipInputStream = new ZipInputStream(inputStream)
) {
- ZipEntry entry = null;
+ ZipEntry entry;
while ((entry = zipInputStream.getNextEntry()) != null) {
StringBuilder stringBuilder = new StringBuilder();
byte[] buffer = new byte[1024];
- int read = 0;
+ int read;
while ((read = zipInputStream.read(buffer, 0, 1024)) >= 0) {
stringBuilder.append(new String(buffer, 0, read));
}
@@ -292,7 +293,15 @@ private static void importSharedPreferencesData(@NonNull final ZipEntry entry, @
@NonNull final String preferencesName, @NonNull final String entryName,
@NonNull final SharedPreferencesProcessStrategy strategy,
@NonNull final String data) throws IOException {
- if (!Objects.equals(entry.getName(), entryName)) return;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
+ if (!Objects.equals(entry.getName(), entryName)) {
+ return;
+ }
+ } else {
+ if (entry.getName().equals(entryName)) {
+ return;
+ }
+ }
final JsonParser jsonParser = LoganSquare.JSON_FACTORY.createParser(data);
if (jsonParser.getCurrentToken() == null) {
jsonParser.nextToken();
@@ -327,7 +336,15 @@ private static void importItemsList(@NonNull final Context context,
@NonNull final String data,
@NonNull final ContentResolverProcessStrategy> strategy)
throws IOException {
- if (!Objects.equals(entry.getName(), entryName)) return;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
+ if (!Objects.equals(entry.getName(), entryName)) {
+ return;
+ }
+ } else {
+ if (entry.getName().equals(entryName)) {
+ return;
+ }
+ }
List itemsList = JsonSerializer.parseList(data, itemCls);
strategy.importItem(context.getContentResolver(), itemsList);
}
@@ -352,7 +369,15 @@ private static void importItem(@NonNull final Context context,
@NonNull final String data,
@NonNull final ContentResolverProcessStrategy strategy)
throws IOException {
- if (!Objects.equals(entry.getName(), entryName)) return;
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
+ if (!Objects.equals(entry.getName(), entryName)) {
+ return;
+ }
+ } else {
+ if (entry.getName().equals(entryName)) {
+ return;
+ }
+ }
T item = JsonSerializer.parse(data, itemCls);
strategy.importItem(context.getContentResolver(), item);
}
diff --git a/twidere/src/main/java/org/mariotaku/twidere/util/MouseScrollDirectionDecider.java b/twidere/src/main/java/org/mariotaku/twidere/util/MouseScrollDirectionDecider.java
index 071cc8103e..b5b1bf7fdc 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/util/MouseScrollDirectionDecider.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/util/MouseScrollDirectionDecider.java
@@ -132,7 +132,7 @@ public void setOverScrollMode(int mode) {
}
@SuppressLint("ViewConstructor")
- private class InternalHorizontalScrollView extends HorizontalScrollView {
+ private static class InternalHorizontalScrollView extends HorizontalScrollView {
private final int factor;
private final MouseScrollDirectionDecider decider;
diff --git a/twidere/src/main/java/org/mariotaku/twidere/util/MultiSelectManager.java b/twidere/src/main/java/org/mariotaku/twidere/util/MultiSelectManager.java
index 0be0adc23c..d9e9a28ab6 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/util/MultiSelectManager.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/util/MultiSelectManager.java
@@ -133,7 +133,7 @@ public static UserKey[] getSelectedUserKeys(final List selectedItems) {
userKeys.add(((ParcelableStatus) item).user_key);
}
}
- return userKeys.toArray(new UserKey[userKeys.size()]);
+ return userKeys.toArray(new UserKey[0]);
}
public interface Callback {
diff --git a/twidere/src/main/java/org/mariotaku/twidere/util/NotificationManagerWrapper.java b/twidere/src/main/java/org/mariotaku/twidere/util/NotificationManagerWrapper.java
index f0895ebb00..6f1e4e9b07 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/util/NotificationManagerWrapper.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/util/NotificationManagerWrapper.java
@@ -113,7 +113,7 @@ public void cancelByTag() {
}
- private class PostedNotification {
+ private static class PostedNotification {
private final String tag;
private final int id;
diff --git a/twidere/src/main/java/org/mariotaku/twidere/util/RecyclerViewNavigationHelper.java b/twidere/src/main/java/org/mariotaku/twidere/util/RecyclerViewNavigationHelper.java
index 0d9fe69fb9..3c1b0ff82d 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/util/RecyclerViewNavigationHelper.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/util/RecyclerViewNavigationHelper.java
@@ -112,13 +112,11 @@ public boolean handleKeyboardShortcutRepeat(@NonNull final KeyboardShortcutsHand
public boolean handleKeyboardShortcutSingle(@NonNull KeyboardShortcutsHandler handler, int keyCode, @NonNull KeyEvent event, int metaState) {
final String action = handler.getKeyAction(CONTEXT_TAG_NAVIGATION, keyCode, event, metaState);
if (action == null) return false;
- switch (action) {
- case ACTION_NAVIGATION_TOP: {
- if (iface != null) {
- iface.scrollToStart();
- }
- return true;
+ if (ACTION_NAVIGATION_TOP.equals(action)) {
+ if (iface != null) {
+ iface.scrollToStart();
}
+ return true;
}
return false;
}
diff --git a/twidere/src/main/java/org/mariotaku/twidere/util/SwipeDismissListViewTouchListener.java b/twidere/src/main/java/org/mariotaku/twidere/util/SwipeDismissListViewTouchListener.java
index 1e1d57991c..77636e8daa 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/util/SwipeDismissListViewTouchListener.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/util/SwipeDismissListViewTouchListener.java
@@ -325,7 +325,7 @@ public void onAnimationEnd(Animator animation) {
return false;
}
- class PendingDismissData implements Comparable {
+ static class PendingDismissData implements Comparable {
public int position;
public View view;
@@ -391,12 +391,9 @@ public void onAnimationEnd(Animator animation) {
}
});
- animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
- @Override
- public void onAnimationUpdate(ValueAnimator valueAnimator) {
- lp.height = (Integer) valueAnimator.getAnimatedValue();
- dismissView.setLayoutParams(lp);
- }
+ animator.addUpdateListener(valueAnimator -> {
+ lp.height = (Integer) valueAnimator.getAnimatedValue();
+ dismissView.setLayoutParams(lp);
});
mPendingDismisses.add(new PendingDismissData(dismissPosition, dismissView));
diff --git a/twidere/src/main/java/org/mariotaku/twidere/util/collection/CompactHashSet.java b/twidere/src/main/java/org/mariotaku/twidere/util/collection/CompactHashSet.java
index c1d378e7e9..88b32aebe5 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/util/collection/CompactHashSet.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/util/collection/CompactHashSet.java
@@ -25,6 +25,7 @@
import androidx.annotation.NonNull;
+import java.util.Arrays;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
@@ -253,8 +254,7 @@ public boolean remove(Object o) {
@Override
public void clear() {
elements = 0;
- for (int ix = 0; ix < objects.length; ix++)
- objects[ix] = null;
+ Arrays.fill(objects, null);
freecells = objects.length;
modCount++;
}
diff --git a/twidere/src/main/java/org/mariotaku/twidere/util/content/ContentResolverUtils.java b/twidere/src/main/java/org/mariotaku/twidere/util/content/ContentResolverUtils.java
index 371fcdce71..ed060e533c 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/util/content/ContentResolverUtils.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/util/content/ContentResolverUtils.java
@@ -81,7 +81,7 @@ public static int bulkDelete(@NonNull final ContentResolver resolver, @NonNull f
public static int bulkInsert(@NonNull final ContentResolver resolver, @NonNull final Uri uri,
@NonNull final Collection values) {
- return bulkInsert(resolver, uri, values.toArray(new ContentValues[values.size()]));
+ return bulkInsert(resolver, uri, values.toArray(new ContentValues[0]));
}
public static int bulkInsert(@NonNull final ContentResolver resolver, @NonNull final Uri uri,
diff --git a/twidere/src/main/java/org/mariotaku/twidere/util/content/DatabaseUpgradeHelper.java b/twidere/src/main/java/org/mariotaku/twidere/util/content/DatabaseUpgradeHelper.java
index 0a7d13c269..ce5d4619b7 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/util/content/DatabaseUpgradeHelper.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/util/content/DatabaseUpgradeHelper.java
@@ -107,7 +107,7 @@ private static String createInsertDataQuery(final String table, final String tem
newInsertColsList.add(newCol);
}
}
- final String[] newInsertCols = newInsertColsList.toArray(new String[newInsertColsList.size()]);
+ final String[] newInsertCols = newInsertColsList.toArray(new String[0]);
if (!TwidereArrayUtils.contains(newInsertCols, notNullCols)) return null;
qb.columns(newInsertCols);
final Columns.Column[] oldDataCols = new Columns.Column[newInsertCols.length];
diff --git a/twidere/src/main/java/org/mariotaku/twidere/util/media/preview/provider/ImgurProvider.java b/twidere/src/main/java/org/mariotaku/twidere/util/media/preview/provider/ImgurProvider.java
index 59ab2d90ad..6c2a77f117 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/util/media/preview/provider/ImgurProvider.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/util/media/preview/provider/ImgurProvider.java
@@ -15,12 +15,7 @@ public class ImgurProvider implements Provider {
public boolean supports(@NonNull String link) {
final String authority = UriUtils.getAuthority(link);
if (authority == null) return false;
- switch (authority) {
- case "i.imgur.com":
- return true;
- default:
- return false;
- }
+ return "i.imgur.com".equals(authority);
}
@Nullable
@@ -28,13 +23,11 @@ public boolean supports(@NonNull String link) {
public ParcelableMedia from(@NonNull String url) {
final String authority = UriUtils.getAuthority(url);
if (authority == null) return null;
- switch (authority) {
- case "i.imgur.com": {
- final String path = UriUtils.getPath(url);
- if (path == null) return null;
- ParcelableMedia media = new ParcelableMedia();
- media.url = url;
- }
+ if ("i.imgur.com".equals(authority)) {
+ final String path = UriUtils.getPath(url);
+ if (path == null) return null;
+ ParcelableMedia media = new ParcelableMedia();
+ media.url = url;
}
return null;
}
diff --git a/twidere/src/main/java/org/mariotaku/twidere/util/support/ViewSupport.java b/twidere/src/main/java/org/mariotaku/twidere/util/support/ViewSupport.java
index 03d5920e15..7fd1bb7bc6 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/util/support/ViewSupport.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/util/support/ViewSupport.java
@@ -47,13 +47,8 @@ public static boolean isInLayout(View view) {
}
}
- @SuppressWarnings("deprecation")
public static void setBackground(final View view, final Drawable background) {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
- view.setBackgroundDrawable(background);
- } else {
- ViewAccessorJB.setBackground(view, background);
- }
+ ViewAccessorJB.setBackground(view, background);
}
public static void setButtonTintList(CompoundButton view, ColorStateList list) {
@@ -97,8 +92,8 @@ public static T findViewByType(View view, Class cls) {
if (cls.isAssignableFrom(view.getClass())) return (T) view;
if (view instanceof ViewGroup) {
for (int i = 0, j = ((ViewGroup) view).getChildCount(); i < j; i++) {
- final View found = findViewByType(((ViewGroup) view).getChildAt(i), cls);
- if (found != null) return (T) found;
+ final T found = findViewByType(((ViewGroup) view).getChildAt(i), cls);
+ if (found != null) return found;
}
}
return null;
@@ -130,7 +125,6 @@ private ViewAccessorJB() {
}
static void setBackground(final View view, final Drawable background) {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) return;
view.setBackground(background);
}
}
@@ -142,10 +136,8 @@ private ViewAccessorICS() {
static void setForeground(final View view, final Drawable foreground) {
if (view instanceof FrameLayout) {
- //noinspection RedundantCast
((FrameLayout) view).setForeground(foreground);
} else if (view instanceof IForegroundView) {
- //noinspection RedundantCast
((IForegroundView) view).setForeground(foreground);
}
}
diff --git a/twidere/src/main/java/org/mariotaku/twidere/util/support/WebSettingsSupport.java b/twidere/src/main/java/org/mariotaku/twidere/util/support/WebSettingsSupport.java
index ef601353fc..90553f8109 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/util/support/WebSettingsSupport.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/util/support/WebSettingsSupport.java
@@ -29,14 +29,12 @@ private WebSettingsSupport() {
}
public static void setAllowUniversalAccessFromFileURLs(final WebSettings settings, final boolean flag) {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) return;
WebSettingsAccessorSDK16.setAllowUniversalAccessFromFileURLs(settings, flag);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private static class WebSettingsAccessorSDK16 {
private static void setAllowUniversalAccessFromFileURLs(final WebSettings settings, final boolean flag) {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) return;
settings.setAllowUniversalAccessFromFileURLs(flag);
}
}
diff --git a/twidere/src/main/java/org/mariotaku/twidere/view/BirthdayView.java b/twidere/src/main/java/org/mariotaku/twidere/view/BirthdayView.java
index eaee407742..2ca8e382dd 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/view/BirthdayView.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/view/BirthdayView.java
@@ -83,7 +83,6 @@ protected void onSizeChanged(final int w, final int h, final int oldw, final int
((AnimatedBitmapLayer) layers[2]).setScale(Math.max(1, w / 160));
}
- @SuppressWarnings("deprecation")
@Override
protected boolean fitSystemWindows(@NonNull Rect insets) {
final int stripTop = Utils.INSTANCE.getInsetsTopWithoutActionBarHeight(getContext(), insets.top);
diff --git a/twidere/src/main/java/org/mariotaku/twidere/view/HeaderDrawerLayout.java b/twidere/src/main/java/org/mariotaku/twidere/view/HeaderDrawerLayout.java
index f565663ac4..97cf52fc37 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/view/HeaderDrawerLayout.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/view/HeaderDrawerLayout.java
@@ -409,13 +409,11 @@ public int clampViewPositionVertical(final View child, final int top, final int
if (dy > 0 && mDrawer.canScrollCallback(-dy) && mDrawer.isTouchingScrollableContent()) {
if (!mDrawer.isUsingDragHelper()) {
// Scrolling up while list still has space to scroll, so make header still
- mScrollingHeaderByHelper = false;
- return current;
} else {
mDrawer.scrollByCallback(-dy);
- mScrollingHeaderByHelper = false;
- return current;
}
+ mScrollingHeaderByHelper = false;
+ return current;
}
final int min = mDrawer.getHeaderTopMinimum(), max = mDrawer.getHeaderTopMaximum();
if (top < min && mDrawer.isTouchingScrollableContent() && mDrawer.isUsingDragHelper()) {
diff --git a/twidere/src/main/java/org/mariotaku/twidere/view/ShapedImageView.java b/twidere/src/main/java/org/mariotaku/twidere/view/ShapedImageView.java
index 36870e2531..82b92bfc03 100644
--- a/twidere/src/main/java/org/mariotaku/twidere/view/ShapedImageView.java
+++ b/twidere/src/main/java/org/mariotaku/twidere/view/ShapedImageView.java
@@ -196,17 +196,14 @@ protected void onDraw(@NonNull Canvas canvas) {
contentHeight = contentBottom - contentTop;
final int size = Math.min(contentWidth, contentHeight);
- if (OUTLINE_DRAW) {
- drawShape(canvas, mDestination, 0, mBackgroundPaint);
- super.onDraw(canvas);
- } else {
+ if (!OUTLINE_DRAW) {
if (mShadowBitmap != null && mDrawShadow) {
canvas.drawBitmap(mShadowBitmap, contentLeft + (contentWidth - size) / 2 - mShadowRadius,
contentTop + (contentHeight - size) / 2 - mShadowRadius, null);
}
- drawShape(canvas, mDestination, 0, mBackgroundPaint);
- super.onDraw(canvas);
}
+ drawShape(canvas, mDestination, 0, mBackgroundPaint);
+ super.onDraw(canvas);
// Then draw the border.
if (mBorderEnabled) {
drawBorder(canvas, mDestination);
diff --git a/twidere/src/main/java/org/oshkimaadziig/george/androidutils/SpanFormatter.java b/twidere/src/main/java/org/oshkimaadziig/george/androidutils/SpanFormatter.java
index 07318b49c3..97465e6e07 100644
--- a/twidere/src/main/java/org/oshkimaadziig/george/androidutils/SpanFormatter.java
+++ b/twidere/src/main/java/org/oshkimaadziig/george/androidutils/SpanFormatter.java
@@ -17,6 +17,8 @@
* along with this program. If not, see .
*/
+// Uses https://github.com/george-steel/android-utils/commit/289aff11e53593a55d780f9f5986e49343a79e55
+
package org.oshkimaadziig.george.androidutils;
import android.text.Spannable;
@@ -33,7 +35,6 @@
*
* @author George T. Steel
*/
-@SuppressWarnings("IfCanBeSwitch")
public class SpanFormatter {
public static final Pattern FORMAT_SEQUENCE = Pattern.compile("%([0-9]+\\$|)([^a-zA-z%]*)([[a-zA-Z%]&&[^tT]]|[tT][a-zA-Z])");
@@ -88,10 +89,10 @@ public static SpannedString format(Locale locale, CharSequence format, Object...
if (typeTerm.equals("%")) {
cookedArg = "%";
- } else if (typeTerm.equals("%")) {
+ } else if (typeTerm.equals("n")) {
cookedArg = "\n";
} else {
- int argIdx = 0;
+ int argIdx;
if (argTerm.equals("")) argIdx = ++argAt;
else if (argTerm.equals("<")) argIdx = argAt;
else argIdx = Integer.parseInt(argTerm.substring(0, argTerm.length() - 1)) - 1;
diff --git a/twidere/src/main/kotlin/androidx/core/os/LocaleHelperAccessor.kt b/twidere/src/main/kotlin/androidx/core/os/LocaleHelperAccessor.kt
index 5a1e268c91..7735fa2b37 100644
--- a/twidere/src/main/kotlin/androidx/core/os/LocaleHelperAccessor.kt
+++ b/twidere/src/main/kotlin/androidx/core/os/LocaleHelperAccessor.kt
@@ -25,26 +25,38 @@ import java.util.*
@SuppressLint("RestrictedApi")
object LocaleHelperAccessor {
fun forLanguageTag(str: String): Locale {
- if (str.contains("-")) {
- val args = str.split("-").dropLastWhile { it.isEmpty() }.toTypedArray()
- if (args.size > 2) {
- return Locale(args[0], args[1], args[2])
- } else if (args.size > 1) {
- return Locale(args[0], args[1])
- } else if (args.size == 1) {
- return Locale(args[0])
+ when {
+ str.contains("-") -> {
+ val args = str.split("-").dropLastWhile { it.isEmpty() }.toTypedArray()
+ when {
+ args.size > 2 -> {
+ return Locale(args[0], args[1], args[2])
+ }
+ args.size > 1 -> {
+ return Locale(args[0], args[1])
+ }
+ args.size == 1 -> {
+ return Locale(args[0])
+ }
+ }
}
- } else if (str.contains("_")) {
- val args = str.split("_").dropLastWhile { it.isEmpty() }.toTypedArray()
- if (args.size > 2) {
- return Locale(args[0], args[1], args[2])
- } else if (args.size > 1) {
- return Locale(args[0], args[1])
- } else if (args.size == 1) {
- return Locale(args[0])
+ str.contains("_") -> {
+ val args = str.split("_").dropLastWhile { it.isEmpty() }.toTypedArray()
+ when {
+ args.size > 2 -> {
+ return Locale(args[0], args[1], args[2])
+ }
+ args.size > 1 -> {
+ return Locale(args[0], args[1])
+ }
+ args.size == 1 -> {
+ return Locale(args[0])
+ }
+ }
+ }
+ else -> {
+ return Locale(str)
}
- } else {
- return Locale(str)
}
throw IllegalArgumentException("Can not parse language tag: [$str]")
diff --git a/twidere/src/main/kotlin/androidx/core/view/WindowInsetsCompatAccessor.kt b/twidere/src/main/kotlin/androidx/core/view/WindowInsetsCompatAccessor.kt
index b085d3b2ee..843e423d31 100644
--- a/twidere/src/main/kotlin/androidx/core/view/WindowInsetsCompatAccessor.kt
+++ b/twidere/src/main/kotlin/androidx/core/view/WindowInsetsCompatAccessor.kt
@@ -19,8 +19,12 @@
package androidx.core.view
-fun createWindowInsetsCompat(obj: Any) = WindowInsetsCompat(obj)
+import android.annotation.TargetApi
+import android.os.Build
+import android.view.WindowInsets
+
+@TargetApi(Build.VERSION_CODES.KITKAT_WATCH)
+fun createWindowInsetsCompat(obj: Any) = WindowInsetsCompat.toWindowInsetsCompat(obj as WindowInsets)
val WindowInsetsCompat.unwrapped: Any?
- @Suppress("RestrictedApi")
get() = this.toWindowInsets()
\ No newline at end of file
diff --git a/twidere/src/main/kotlin/androidx/loader/app/LoaderManagerExtensions.kt b/twidere/src/main/kotlin/androidx/loader/app/LoaderManagerExtensions.kt
index 3920617b14..172cba0da4 100644
--- a/twidere/src/main/kotlin/androidx/loader/app/LoaderManagerExtensions.kt
+++ b/twidere/src/main/kotlin/androidx/loader/app/LoaderManagerExtensions.kt
@@ -1,8 +1,5 @@
package androidx.loader.app
-import androidx.loader.app.LoaderManager
-import androidx.loader.app.LoaderManagerImpl
-
/**
* Created by mariotaku on 2016/11/26.
*/
diff --git a/twidere/src/main/kotlin/androidx/loader/content/FixedAsyncTaskLoader.kt b/twidere/src/main/kotlin/androidx/loader/content/FixedAsyncTaskLoader.kt
index fab5db6b59..6dde68c1a8 100644
--- a/twidere/src/main/kotlin/androidx/loader/content/FixedAsyncTaskLoader.kt
+++ b/twidere/src/main/kotlin/androidx/loader/content/FixedAsyncTaskLoader.kt
@@ -2,7 +2,6 @@ package androidx.loader.content
import android.content.Context
import android.os.AsyncTask
-import androidx.loader.content.AsyncTaskLoader
import org.mariotaku.twidere.extension.set
import org.mariotaku.twidere.util.Analyzer
diff --git a/twidere/src/main/kotlin/androidx/recyclerview/widget/RecyclerViewAccessor.kt b/twidere/src/main/kotlin/androidx/recyclerview/widget/RecyclerViewAccessor.kt
index c0fe226db4..bdff2b83ca 100644
--- a/twidere/src/main/kotlin/androidx/recyclerview/widget/RecyclerViewAccessor.kt
+++ b/twidere/src/main/kotlin/androidx/recyclerview/widget/RecyclerViewAccessor.kt
@@ -19,6 +19,4 @@
package androidx.recyclerview.widget
-import androidx.recyclerview.widget.RecyclerView
-
val RecyclerView.LayoutManager.recyclerView: RecyclerView? get() = mRecyclerView
diff --git a/twidere/src/main/kotlin/org/mariotaku/ktextension/AccountManagerExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/ktextension/AccountManagerExtensions.kt
index f3cede5294..563dd16178 100644
--- a/twidere/src/main/kotlin/org/mariotaku/ktextension/AccountManagerExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/ktextension/AccountManagerExtensions.kt
@@ -10,23 +10,23 @@ import android.os.Handler
fun AccountManager.addOnAccountsUpdatedListenerSafe(listener: OnAccountsUpdateListener,
handler: Handler? = null, updateImmediately: Boolean = false): Boolean {
- try {
+ return try {
this.addOnAccountsUpdatedListener(listener, handler, updateImmediately)
- return true
+ true
} catch (e: IllegalStateException) {
- return false
+ false
} catch (e: IllegalArgumentException) {
- return false
+ false
}
}
fun AccountManager.removeOnAccountsUpdatedListenerSafe(listener: OnAccountsUpdateListener): Boolean {
- try {
+ return try {
this.removeOnAccountsUpdatedListener(listener)
- return true
+ true
} catch (e: IllegalStateException) {
- return false
+ false
} catch (e: IllegalArgumentException) {
- return false
+ false
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/ktextension/CollectionExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/ktextension/CollectionExtensions.kt
index 880ec6289c..4f2e6dcb74 100644
--- a/twidere/src/main/kotlin/org/mariotaku/ktextension/CollectionExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/ktextension/CollectionExtensions.kt
@@ -13,10 +13,10 @@ fun Collection<*>?.isNullOrEmpty(): Boolean {
}
fun MutableCollection.addAllEnhanced(collection: Collection, ignoreDuplicates: Boolean): Boolean {
- if (ignoreDuplicates) {
- return addAll(collection.filter { it !in this })
+ return if (ignoreDuplicates) {
+ addAll(collection.filter { it !in this })
} else {
- return addAll(collection)
+ addAll(collection)
}
}
@@ -41,7 +41,7 @@ fun Collection.contentEquals(other: Collection): Boolean {
inline fun List.subArray(range: IntRange): Array {
return Array(range.count()) {
- this[range.start + it]
+ this[range.first + it]
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/ktextension/ContextExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/ktextension/ContextExtensions.kt
index 43bab2a445..e8401e1b25 100644
--- a/twidere/src/main/kotlin/org/mariotaku/ktextension/ContextExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/ktextension/ContextExtensions.kt
@@ -20,11 +20,11 @@ fun Context.checkAnySelfPermissionsGranted(vararg permissions: String): Boolean
fun Context.unregisterReceiverSafe(receiver: BroadcastReceiver?): Boolean {
if (receiver == null) return false
- try {
+ return try {
unregisterReceiver(receiver)
- return true
+ true
} catch (e: IllegalArgumentException) {
- return false
+ false
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/ktextension/CursorExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/ktextension/CursorExtensions.kt
index ac6952906b..34c70b59b4 100644
--- a/twidere/src/main/kotlin/org/mariotaku/ktextension/CursorExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/ktextension/CursorExtensions.kt
@@ -26,7 +26,7 @@ fun Cursor.safeGetInt(columnIndex: Int, def: Int = -1) = try {
def
}
-fun Cursor.safeGetString(columnIndex: Int, def: String = "") = try {
+fun Cursor.safeGetString(columnIndex: Int, def: String = ""): String = try {
getString(columnIndex)
} catch (e: IllegalStateException) {
def
diff --git a/twidere/src/main/kotlin/org/mariotaku/ktextension/LocaleExtension.kt b/twidere/src/main/kotlin/org/mariotaku/ktextension/LocaleExtension.kt
index e8fbe0d38f..99d0fef92c 100644
--- a/twidere/src/main/kotlin/org/mariotaku/ktextension/LocaleExtension.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/ktextension/LocaleExtension.kt
@@ -58,10 +58,10 @@ val Locale.bcp47Tag: String
}
val bcp47Tag = StringBuilder(language)
- if (!country.isEmpty()) {
+ if (country.isNotEmpty()) {
bcp47Tag.append(SEP).append(country)
}
- if (!variant.isEmpty()) {
+ if (variant.isNotEmpty()) {
bcp47Tag.append(SEP).append(variant)
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/ktextension/NumberExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/ktextension/NumberExtensions.kt
index 63c0a6e209..e8c69bb221 100644
--- a/twidere/src/main/kotlin/org/mariotaku/ktextension/NumberExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/ktextension/NumberExtensions.kt
@@ -48,7 +48,7 @@ fun Number.toLocalizedString(locale: Locale = Locale.getDefault()): String {
val Int.nextPowerOf2: Int
get() {
var n = this
- if (n <= 0 || n > 1 shl 30) throw IllegalArgumentException("n is invalid: " + n)
+ if (n <= 0 || n > 1 shl 30) throw IllegalArgumentException("n is invalid: $n")
n -= 1
n = n or (n shr 16)
n = n or (n shr 8)
diff --git a/twidere/src/main/kotlin/org/mariotaku/ktextension/RecyclerViewExtension.kt b/twidere/src/main/kotlin/org/mariotaku/ktextension/RecyclerViewExtension.kt
index e86e71910a..6b9784e334 100644
--- a/twidere/src/main/kotlin/org/mariotaku/ktextension/RecyclerViewExtension.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/ktextension/RecyclerViewExtension.kt
@@ -6,5 +6,5 @@ import androidx.recyclerview.widget.RecyclerView
* Created by mariotaku on 16/8/21.
*/
fun RecyclerView.Adapter<*>.findPositionByItemId(itemId: Long): Int {
- return (0 until itemCount).firstOrNull { getItemId(it) == itemId } ?: androidx.recyclerview.widget.RecyclerView.NO_POSITION
+ return (0 until itemCount).firstOrNull { getItemId(it) == itemId } ?: RecyclerView.NO_POSITION
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/ktextension/StreamExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/ktextension/StreamExtensions.kt
index 56f14ffa6c..c9a2b03dae 100644
--- a/twidere/src/main/kotlin/org/mariotaku/ktextension/StreamExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/ktextension/StreamExtensions.kt
@@ -40,5 +40,5 @@ fun InputStream.expectLine(string: String = "", charset: Charset = Charset.defau
fun InputStream.expectBytes(bytes: ByteArray): Boolean {
val readBytes = ByteArray(bytes.size)
read(readBytes)
- return Arrays.equals(readBytes, bytes)
+ return readBytes.contentEquals(bytes)
}
\ No newline at end of file
diff --git a/twidere/src/main/kotlin/org/mariotaku/microblog/library/twitter/model/InternalActivityCreator.kt b/twidere/src/main/kotlin/org/mariotaku/microblog/library/twitter/model/InternalActivityCreator.kt
index 306aca20c7..6f153d2546 100644
--- a/twidere/src/main/kotlin/org/mariotaku/microblog/library/twitter/model/InternalActivityCreator.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/microblog/library/twitter/model/InternalActivityCreator.kt
@@ -35,20 +35,24 @@ object InternalActivityCreator {
activity.maxSortPosition = activity.minSortPosition
activity.createdAt = status.getCreatedAt()
- if (status.getInReplyToUserId() == accountId) {
- activity.action = Activity.Action.REPLY
- activity.targetStatuses = arrayOf(status)
-
- //TODO set target statuses (in reply to status)
- activity.targetObjectStatuses = arrayOfNulls(0)
- } else if (status.quotedStatus?.user?.id == accountId) {
- activity.action = Activity.Action.QUOTE
- activity.targetStatuses = arrayOf(status)
- activity.targetObjectStatuses = arrayOfNulls(0)
- } else {
- activity.action = Activity.Action.MENTION
- activity.targetUsers = arrayOfNulls(0)
- activity.targetObjectStatuses = arrayOf(status)
+ when {
+ status.getInReplyToUserId() == accountId -> {
+ activity.action = Activity.Action.REPLY
+ activity.targetStatuses = arrayOf(status)
+
+ //TODO set target statuses (in reply to status)
+ activity.targetObjectStatuses = arrayOfNulls(0)
+ }
+ status.quotedStatus?.user?.id == accountId -> {
+ activity.action = Activity.Action.QUOTE
+ activity.targetStatuses = arrayOf(status)
+ activity.targetObjectStatuses = arrayOfNulls(0)
+ }
+ else -> {
+ activity.action = Activity.Action.MENTION
+ activity.targetUsers = arrayOfNulls(0)
+ activity.targetObjectStatuses = arrayOf(status)
+ }
}
activity.sourcesSize = 1
activity.sources = arrayOf(status.getUser())
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/AccountSelectorActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/AccountSelectorActivity.kt
index 0376f95acb..c386c9f0dc 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/AccountSelectorActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/AccountSelectorActivity.kt
@@ -34,7 +34,6 @@ import org.mariotaku.twidere.R
import org.mariotaku.twidere.TwidereConstants.*
import org.mariotaku.twidere.adapter.AccountDetailsAdapter
import org.mariotaku.twidere.annotation.AccountType
-import org.mariotaku.twidere.app.TwidereApplication
import org.mariotaku.twidere.extension.model.isOAuth
import org.mariotaku.twidere.model.UserKey
import org.mariotaku.twidere.model.util.AccountUtils
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/AssistLauncherActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/AssistLauncherActivity.kt
index 903284f50b..5064e88ce5 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/AssistLauncherActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/AssistLauncherActivity.kt
@@ -13,8 +13,7 @@ class AssistLauncherActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val prefs = getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
- val composeNowAction = prefs.getString(KEY_COMPOSE_NOW_ACTION, VALUE_COMPOSE_NOW_ACTION_COMPOSE)
- val action = when (composeNowAction) {
+ val action = when (prefs.getString(KEY_COMPOSE_NOW_ACTION, VALUE_COMPOSE_NOW_ACTION_COMPOSE)) {
VALUE_COMPOSE_NOW_ACTION_TAKE_PHOTO -> INTENT_ACTION_COMPOSE_TAKE_PHOTO
VALUE_COMPOSE_NOW_ACTION_PICK_IMAGE -> INTENT_ACTION_COMPOSE_PICK_IMAGE
else -> INTENT_ACTION_COMPOSE
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/BaseActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/BaseActivity.kt
index bb82941518..bf7e022470 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/BaseActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/BaseActivity.kt
@@ -27,22 +27,22 @@ import android.graphics.Rect
import android.nfc.NfcAdapter
import android.os.Build
import android.os.Bundle
+import android.util.AttributeSet
+import android.view.KeyEvent
+import android.view.MotionEvent
+import android.view.View
+import android.view.WindowManager
import androidx.annotation.StyleRes
-import androidx.fragment.app.Fragment
+import androidx.appcompat.app.TwilightManagerAccessor
+import androidx.appcompat.view.menu.ActionMenuItemView
+import androidx.appcompat.widget.TwidereActionMenuView
import androidx.core.graphics.ColorUtils
import androidx.core.view.OnApplyWindowInsetsListener
import androidx.core.view.WindowInsetsCompat
-import androidx.appcompat.app.TwilightManagerAccessor
+import androidx.fragment.app.Fragment
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.PreferenceFragmentCompat.OnPreferenceDisplayDialogCallback
-import androidx.appcompat.view.menu.ActionMenuItemView
-import androidx.appcompat.widget.TwidereActionMenuView
-import android.util.AttributeSet
-import android.view.KeyEvent
-import android.view.MotionEvent
-import android.view.View
-import android.view.WindowManager
import com.bumptech.glide.Glide
import com.bumptech.glide.RequestManager
import com.squareup.otto.Bus
@@ -300,7 +300,7 @@ open class BaseActivity : ChameleonActivity(), IBaseActivity, IThe
for (i in 0 until handlerFilter.countDataAuthorities()) {
val authorityEntry = handlerFilter.getDataAuthority(i)
val port = authorityEntry.port
- intentFilter.addDataAuthority(authorityEntry.host, if (port < 0) null else Integer.toString(port))
+ intentFilter.addDataAuthority(authorityEntry.host, if (port < 0) null else port.toString())
}
try {
adapter.enableForegroundDispatch(this, intent, arrayOf(intentFilter), null)
@@ -363,7 +363,11 @@ open class BaseActivity : ChameleonActivity(), IBaseActivity, IThe
super.attachBaseContext(newBase)
return
}
- super.attachBaseContext(newBase.overriding(locale))
+ val newContext = newBase.overriding(locale)
+ super.attachBaseContext(newContext)
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
+ applyOverrideConfiguration(newContext.resources.configuration)
+ }
}
override fun executeAfterFragmentResumed(useHandler: Boolean, action: (BaseActivity) -> Unit): Promise {
@@ -465,20 +469,20 @@ open class BaseActivity : ChameleonActivity(), IBaseActivity, IThe
}
private fun newInstance(name: String, context: Context, attrs: AttributeSet): View? {
- try {
+ return try {
val cls = findClass(name) ?: throw ClassNotFoundException(name)
val constructor = cls.getConstructor(Context::class.java, AttributeSet::class.java)
- return constructor.newInstance(context, attrs) as View
+ constructor.newInstance(context, attrs) as View
} catch (e: InstantiationException) {
- return null
+ null
} catch (e: IllegalAccessException) {
- return null
+ null
} catch (e: InvocationTargetException) {
- return null
+ null
} catch (e: NoSuchMethodException) {
- return null
+ null
} catch (e: ClassNotFoundException) {
- return null
+ null
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/ColorPickerDialogActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/ColorPickerDialogActivity.kt
index 2b249da205..ef81b00f49 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/ColorPickerDialogActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/ColorPickerDialogActivity.kt
@@ -69,7 +69,7 @@ class ColorPickerDialogActivity : BaseActivity(), Callback {
companion object {
- val RESULT_CLEARED = -2
+ const val RESULT_CLEARED = -2
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/ComposeActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/ComposeActivity.kt
index 258354b193..2ab75e095d 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/ComposeActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/ComposeActivity.kt
@@ -113,6 +113,7 @@ import java.text.Normalizer
import java.util.*
import javax.inject.Inject
import kotlin.collections.ArrayList
+import kotlin.math.abs
import android.Manifest.permission as AndroidPermission
@SuppressLint("RestrictedApi")
@@ -389,11 +390,15 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_TAKE_PHOTO, REQUEST_PICK_MEDIA -> {
if (resultCode == Activity.RESULT_OK && data != null) {
val src = MediaPickerActivity.getMediaUris(data)
- TaskStarter.execute(AddMediaTask(this, src, null, false, false))
+ TaskStarter.execute(AddMediaTask(this, src, null,
+ copySrc = false,
+ deleteSrc = false
+ ))
val extras = data.getBundleExtra(MediaPickerActivity.EXTRA_EXTRAS)
if (extras?.getBoolean(EXTRA_IS_POSSIBLY_SENSITIVE) == true) {
possiblySensitive = true
@@ -430,7 +435,10 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
val src = MediaPickerActivity.getMediaUris(data)?.takeIf(Array::isNotEmpty) ?:
data.getParcelableExtra(EXTRA_IMAGE_URI)?.let { arrayOf(it) }
if (src != null) {
- TaskStarter.execute(AddMediaTask(this, src, null, false, false))
+ TaskStarter.execute(AddMediaTask(this, src, null,
+ copySrc = false,
+ deleteSrc = false
+ ))
}
}
}
@@ -508,7 +516,7 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
}
replyLabel -> {
if (replyLabel.visibility != View.VISIBLE) return
- replyLabel.setSingleLine(replyLabel.lineCount > 1)
+ replyLabel.isSingleLine = replyLabel.lineCount > 1
}
}
}
@@ -806,8 +814,7 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
private fun extensionIntentItemSelected(item: MenuItem) {
val intent = item.intent ?: return
try {
- val action = intent.action
- when (action) {
+ when (intent.action) {
INTENT_ACTION_EXTENSION_COMPOSE -> {
val accountKeys = accountsAdapter.selectedAccountKeys
intent.putExtra(EXTRA_TEXT, ParseUtils.parseString(editText.text))
@@ -1083,16 +1090,20 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
val action = intent.action
val hasVisibility = intent.hasExtra(EXTRA_VISIBILITY)
val hasAccountKeys: Boolean
- if (intent.hasExtra(EXTRA_ACCOUNT_KEYS)) {
- val accountKeys = intent.getTypedArrayExtra(EXTRA_ACCOUNT_KEYS)
- accountsAdapter.selectedAccountKeys = accountKeys
- hasAccountKeys = true
- } else if (intent.hasExtra(EXTRA_ACCOUNT_KEY)) {
- val accountKey = intent.getParcelableExtra(EXTRA_ACCOUNT_KEY)
- accountsAdapter.selectedAccountKeys = arrayOf(accountKey)
- hasAccountKeys = true
- } else {
- hasAccountKeys = false
+ when {
+ intent.hasExtra(EXTRA_ACCOUNT_KEYS) -> {
+ val accountKeys = intent.getTypedArrayExtra(EXTRA_ACCOUNT_KEYS)
+ accountsAdapter.selectedAccountKeys = accountKeys
+ hasAccountKeys = true
+ }
+ intent.hasExtra(EXTRA_ACCOUNT_KEY) -> {
+ val accountKey = intent.getParcelableExtra(EXTRA_ACCOUNT_KEY)
+ accountsAdapter.selectedAccountKeys = arrayOf(accountKey)
+ hasAccountKeys = true
+ }
+ else -> {
+ hasAccountKeys = false
+ }
}
when (action) {
Intent.ACTION_SEND, Intent.ACTION_SEND_MULTIPLE -> {
@@ -1101,7 +1112,10 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
val stream = intent.getStreamExtra()
if (stream != null) {
val src = stream.toTypedArray()
- TaskStarter.execute(AddMediaTask(this, src, null, true, false))
+ TaskStarter.execute(AddMediaTask(this, src, null,
+ copySrc = true,
+ deleteSrc = false
+ ))
}
}
else -> {
@@ -1110,7 +1124,10 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
val data = intent.data
if (data != null) {
val src = arrayOf(data)
- TaskStarter.execute(AddMediaTask(this, src, null, true, false))
+ TaskStarter.execute(AddMediaTask(this, src, null,
+ copySrc = true,
+ deleteSrc = false
+ ))
}
}
}
@@ -1146,16 +1163,16 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
}
INTENT_ACTION_EDIT_DRAFT -> {
val draft: Draft? = intent.getParcelableExtra(EXTRA_DRAFT)
- when (draft?.action_type) {
+ return when (draft?.action_type) {
Draft.Action.REPLY -> {
- return showReplyLabelAndHint((draft.action_extras as? UpdateStatusActionExtras)?.inReplyToStatus)
+ showReplyLabelAndHint((draft.action_extras as? UpdateStatusActionExtras)?.inReplyToStatus)
}
Draft.Action.QUOTE -> {
- return showQuoteLabelAndHint((draft.action_extras as? UpdateStatusActionExtras)?.inReplyToStatus)
+ showQuoteLabelAndHint((draft.action_extras as? UpdateStatusActionExtras)?.inReplyToStatus)
}
else -> {
showDefaultLabelAndHint()
- return false
+ false
}
}
}
@@ -1785,7 +1802,7 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
s.setSpan(MarkForDeleteSpan(), start, start + count,
Spanned.SPAN_INCLUSIVE_INCLUSIVE)
}
- if (!imageSources.isEmpty()) {
+ if (imageSources.isNotEmpty()) {
val intent = ThemedMediaPickerActivity.withThemed(this@ComposeActivity)
.getMedia(Uri.parse(imageSources[0]))
.build()
@@ -1816,7 +1833,10 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
})
editText.customSelectionActionModeCallback = this
editText.imageInputListener = { contentInfo ->
- val task = AddMediaTask(this, arrayOf(contentInfo.contentUri), null, true, false)
+ val task = AddMediaTask(this, arrayOf(contentInfo.contentUri), null,
+ copySrc = true,
+ deleteSrc = false
+ )
task.callback = {
contentInfo.releasePermission()
}
@@ -1839,8 +1859,8 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val context = activity!!
- val builder = AlertDialog.Builder(context!!)
+ val context = requireActivity()
+ val builder = AlertDialog.Builder(requireContext())
builder.setMessage(R.string.quote_protected_status_warning_message)
builder.setPositiveButton(R.string.send_anyway, this)
builder.setNegativeButton(android.R.string.cancel, null)
@@ -1873,8 +1893,8 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val context = activity!!
- val builder = AlertDialog.Builder(context!!)
+ val context = requireActivity()
+ val builder = AlertDialog.Builder(requireContext())
builder.setMessage(getString(R.string.message_format_compose_message_convert_to_status,
"@$screenName"))
builder.setPositiveButton(R.string.action_send, this)
@@ -1886,7 +1906,7 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
}
}
- class AttachedMediaItemTouchHelperCallback(adapter: SimpleItemTouchHelperCallback.ItemTouchHelperAdapter) : SimpleItemTouchHelperCallback(adapter) {
+ class AttachedMediaItemTouchHelperCallback(adapter: ItemTouchHelperAdapter) : SimpleItemTouchHelperCallback(adapter) {
override fun isLongPressDragEnabled(): Boolean {
return true
@@ -1906,7 +1926,7 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
override fun onChildDraw(c: Canvas, recyclerView: RecyclerView, viewHolder: ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
// Fade out the view as it is swiped out of the parent's bounds
- val alpha = ALPHA_FULL - Math.abs(dY) / viewHolder.itemView.height.toFloat()
+ val alpha = ALPHA_FULL - abs(dY) / viewHolder.itemView.height.toFloat()
viewHolder.itemView.alpha = alpha
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
} else {
@@ -1924,7 +1944,7 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
}
companion object {
- val ALPHA_FULL = 1.0f
+ const val ALPHA_FULL = 1.0f
}
}
@@ -1996,7 +2016,7 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
set(value) {
selection.clear()
for (accountKey in value) {
- selection.put(accountKey, true)
+ selection[accountKey] = true
}
notifyDataSetChanged()
}
@@ -2034,7 +2054,7 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
fun toggleSelection(position: Int) {
if (accounts == null || position < 0) return
val account = accounts!![position]
- selection.put(account.key, true != selection[account.key])
+ selection[account.key] = true != selection[account.key]
activity.updateAccountSelectionState()
activity.updateVisibilityState()
activity.updateSummaryTextState()
@@ -2046,7 +2066,7 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
if (accounts == null || position < 0) return
val account = accounts!![position]
selection.clear()
- selection.put(account.key, true != selection[account.key])
+ selection[account.key] = true != selection[account.key]
activity.updateAccountSelectionState()
activity.updateVisibilityState()
activity.updateSummaryTextState()
@@ -2096,12 +2116,12 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
private class DisplayPlaceNameTask : AbstractTask, ComposeActivity>() {
override fun doLongOperation(location: ParcelableLocation): List? {
- try {
+ return try {
val activity = callback ?: throw IOException("Interrupted")
val gcd = Geocoder(activity, Locale.getDefault())
- return gcd.getFromLocation(location.latitude, location.longitude, 1)
+ gcd.getFromLocation(location.latitude, location.longitude, 1)
} catch (e: IOException) {
- return null
+ null
}
}
@@ -2119,13 +2139,16 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
textView.spannable = ParcelableLocationUtils.getHumanReadableString(location, 3)
textView.tag = location
} else {
- val tag = textView.tag
- if (tag is Address) {
- textView.spannable = tag.locality
- } else if (tag is NoAddress) {
- textView.setText(R.string.label_location_your_coarse_location)
- } else {
- textView.setText(R.string.getting_location)
+ when (val tag = textView.tag) {
+ is Address -> {
+ textView.spannable = tag.locality
+ }
+ is NoAddress -> {
+ textView.setText(R.string.label_location_your_coarse_location)
+ }
+ else -> {
+ textView.setText(R.string.getting_location)
+ }
}
}
} else {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/DataExportActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/DataExportActivity.kt
index 3af8d91651..e5d25081cf 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/DataExportActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/DataExportActivity.kt
@@ -105,12 +105,12 @@ class DataExportActivity : BaseActivity(), DataExportImportTypeSelectorDialogFra
?: return false
// val file = File(folder, fileName)
// file.delete()
- try {
+ return try {
DataImportExportUtils.exportData(activity, file, flags)
- return true
+ true
} catch (e: IOException) {
Log.w(LOGTAG, e)
- return false
+ false
}
}
@@ -134,7 +134,7 @@ class DataExportActivity : BaseActivity(), DataExportImportTypeSelectorDialogFra
}
companion object {
- private val FRAGMENT_TAG = "import_settings_dialog"
+ private const val FRAGMENT_TAG = "import_settings_dialog"
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/DataImportActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/DataImportActivity.kt
index 7d2826064c..af32b31fa1 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/DataImportActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/DataImportActivity.kt
@@ -111,12 +111,12 @@ class DataImportActivity : BaseActivity(), DataExportImportTypeSelectorDialogFra
return false
}
if (!file.isFile) return false
- try {
+ return try {
DataImportExportUtils.importData(activity, file, flags)
- return true
+ true
} catch (e: IOException) {
Log.w(LOGTAG, e)
- return false
+ false
}
}
@@ -140,7 +140,7 @@ class DataImportActivity : BaseActivity(), DataExportImportTypeSelectorDialogFra
}
companion object {
- private val FRAGMENT_TAG = "import_settings_dialog"
+ private const val FRAGMENT_TAG = "import_settings_dialog"
}
}
@@ -152,10 +152,10 @@ class DataImportActivity : BaseActivity(), DataExportImportTypeSelectorDialogFra
return 0
}
if (!file.isFile) return 0
- try {
- return DataImportExportUtils.getImportedSettingsFlags(activity, file)
+ return try {
+ DataImportExportUtils.getImportedSettingsFlags(activity, file)
} catch (e: IOException) {
- return 0
+ 0
}
}
@@ -185,7 +185,7 @@ class DataImportActivity : BaseActivity(), DataExportImportTypeSelectorDialogFra
companion object {
- private val FRAGMENT_TAG = "read_settings_data_dialog"
+ private const val FRAGMENT_TAG = "read_settings_data_dialog"
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/FileSelectorActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/FileSelectorActivity.kt
index b808436fde..bf71b508c1 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/FileSelectorActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/FileSelectorActivity.kt
@@ -87,13 +87,17 @@ class FileSelectorActivity : BaseActivity(), FileSelectorDialogFragment.Callback
finish()
return
}
- if (checkAllSelfPermissionsGranted(AndroidPermissions.READ_EXTERNAL_STORAGE, AndroidPermissions.WRITE_EXTERNAL_STORAGE)) {
- showPickFileDialog()
- } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
- val permissions = arrayOf(AndroidPermissions.READ_EXTERNAL_STORAGE, AndroidPermissions.WRITE_EXTERNAL_STORAGE)
- ActivityCompat.requestPermissions(this, permissions, REQUEST_REQUEST_PERMISSIONS)
- } else {
- finishWithDeniedMessage()
+ when {
+ checkAllSelfPermissionsGranted(AndroidPermissions.READ_EXTERNAL_STORAGE, AndroidPermissions.WRITE_EXTERNAL_STORAGE) -> {
+ showPickFileDialog()
+ }
+ Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN -> {
+ val permissions = arrayOf(AndroidPermissions.READ_EXTERNAL_STORAGE, AndroidPermissions.WRITE_EXTERNAL_STORAGE)
+ ActivityCompat.requestPermissions(this, permissions, REQUEST_REQUEST_PERMISSIONS)
+ }
+ else -> {
+ finishWithDeniedMessage()
+ }
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/HomeActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/HomeActivity.kt
index 1feb6a6c24..9211b48de9 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/HomeActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/HomeActivity.kt
@@ -107,6 +107,7 @@ import org.mariotaku.twidere.util.premium.ExtraFeaturesService
import org.mariotaku.twidere.view.HomeDrawerLayout
import org.mariotaku.twidere.view.TabPagerIndicator
import java.lang.ref.WeakReference
+import kotlin.math.floor
class HomeActivity : BaseActivity(), OnClickListener, OnPageChangeListener, SupportFragmentCallback,
OnLongClickListener, DrawerLayout.DrawerListener {
@@ -422,12 +423,18 @@ class HomeActivity : BaseActivity(), OnClickListener, OnPageChangeListener, Supp
if (!ViewCompat.getFitsSystemWindows(homeMenu)) {
homeContent.setPadding(0, insets.systemWindowInsetTop, 0, 0)
}
+ (toolbar.layoutParams as? MarginLayoutParams)?.bottomMargin = insets.systemWindowInsetBottom
(actionsButton.layoutParams as? MarginLayoutParams)?.bottomMargin =
- actionsButtonBottomMargin + insets.systemWindowInsetBottom
+ actionsButtonBottomMargin + if (preferences[tabPositionKey] == SharedPreferenceConstants.VALUE_TAB_POSITION_TOP) {
+ insets.systemWindowInsetBottom
+ } else {
+ 0
+ }
return insets
}
override fun onNewIntent(intent: Intent) {
+ super.onNewIntent(intent)
val tabPosition = handleIntent(intent, false)
if (tabPosition >= 0) {
mainPager.currentItem = tabPosition.coerceInOr(0 until pagerAdapter.count, 0)
@@ -623,16 +630,22 @@ class HomeActivity : BaseActivity(), OnClickListener, OnPageChangeListener, Supp
}
notifyControlBarOffsetChanged()
} else {
+ val layoutparams = toolbar.layoutParams
+ val toolbarMarginBottom = if (layoutparams is MarginLayoutParams) {
+ layoutparams.bottomMargin
+ } else {
+ 0
+ }
val translationY = if (mainTabs.columns > 1 || !toolbar.isVisible) {
0
} else {
- (toolbar.height * (offset - 1)).toInt()
+ ((toolbar.height + toolbarMarginBottom) * (offset - 1)).toInt()
}
toolbar.translationY = -translationY.toFloat()
windowOverlay.translationY = -translationY.toFloat()
val lp = actionsButton.layoutParams
if (lp is MarginLayoutParams) {
- actionsButton.translationY = (lp.bottomMargin + toolbar.height + actionsButton.height) * (1 - offset)
+ actionsButton.translationY = (lp.bottomMargin + toolbar.height + actionsButton.height + toolbarMarginBottom) * (1 - offset)
} else {
actionsButton.translationY = actionsButton.height * (1 - offset)
}
@@ -848,7 +861,7 @@ class HomeActivity : BaseActivity(), OnClickListener, OnPageChangeListener, Supp
"wide" -> resources.getDimension(R.dimen.preferred_tab_column_width_wide)
else -> resources.getDimension(R.dimen.preferred_tab_column_width_normal)
}
- mainTabs.columns = Math.floor(1.0 / pagerAdapter.getPageWidth(0)).toInt()
+ mainTabs.columns = floor(1.0 / pagerAdapter.getPageWidth(0)).toInt()
} else {
mainPager.pageMargin = 0
mainPager.setPageMarginDrawable(null)
@@ -1059,7 +1072,7 @@ class HomeActivity : BaseActivity(), OnClickListener, OnPageChangeListener, Supp
class AutoRefreshConfirmDialogFragment : BaseDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setTitle(R.string.auto_refresh)
builder.setMessage(R.string.message_auto_refresh_confirm)
builder.setPositiveButton(android.R.string.ok) { _, _ ->
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/ImageCropperActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/ImageCropperActivity.kt
index 914b8cb6cc..c092e3d623 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/ImageCropperActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/ImageCropperActivity.kt
@@ -171,7 +171,7 @@ class ImageCropperActivity : BaseActivity(), CropImageView.OnSetImageUriComplete
private fun getResultIntent(uri: Uri?, error: Exception?, sampleSize: Int): Intent {
val result = CropImage.ActivityResult(cropImageView.imageUri, uri, error,
cropImageView.cropPoints, cropImageView.cropRect, cropImageView.rotatedDegrees,
- sampleSize)
+ cropImageView.wholeImageRect, sampleSize)
val intent = Intent()
intent.putExtra(CropImage.CROP_IMAGE_EXTRA_RESULT, result)
return intent
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/InvalidAccountAlertActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/InvalidAccountAlertActivity.kt
index 51d90f0b3e..b3c48ee0d8 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/InvalidAccountAlertActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/InvalidAccountAlertActivity.kt
@@ -30,7 +30,7 @@ class InvalidAccountAlertActivity : FragmentActivity() {
class InvalidAccountAlertDialogFragment : BaseDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setTitle(R.string.title_error_invalid_account)
builder.setMessage(R.string.message_error_invalid_account)
builder.setPositiveButton(android.R.string.ok) { _, _ ->
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/KeyboardShortcutPreferenceCompatActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/KeyboardShortcutPreferenceCompatActivity.kt
index 786cbeac46..40c2d645ee 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/KeyboardShortcutPreferenceCompatActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/KeyboardShortcutPreferenceCompatActivity.kt
@@ -119,7 +119,7 @@ class KeyboardShortcutPreferenceCompatActivity : BaseActivity(), OnClickListener
companion object {
- val EXTRA_CONTEXT_TAG = "context_tag"
- val EXTRA_KEY_ACTION = "key_action"
+ const val EXTRA_CONTEXT_TAG = "context_tag"
+ const val EXTRA_KEY_ACTION = "key_action"
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/MediaViewerActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/MediaViewerActivity.kt
index df5f88f827..78a12544db 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/MediaViewerActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/MediaViewerActivity.kt
@@ -26,7 +26,6 @@ import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.Parcelable
-import android.provider.MediaStore
import androidx.annotation.RequiresApi
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.Fragment
@@ -75,6 +74,8 @@ import org.mariotaku.twidere.view.viewer.MediaSwipeCloseContainer
import java.io.File
import javax.inject.Inject
import kotlin.concurrent.thread
+import kotlin.math.abs
+import kotlin.math.roundToInt
import android.Manifest.permission as AndroidPermissions
class MediaViewerActivity : BaseActivity(), IMediaViewerActivity, MediaSwipeCloseContainer.Listener,
@@ -146,7 +147,7 @@ class MediaViewerActivity : BaseActivity(), IMediaViewerActivity, MediaSwipeClos
activityLayout.statusBarAlpha = offset
}
try {
- actionBar.hideOffset = Math.round(controlBarHeight * (1f - offset))
+ actionBar.hideOffset = (controlBarHeight * (1f - offset)).roundToInt()
} catch (e: UnsupportedOperationException) {
// Some device will throw this exception
hideOffsetNotSupported = true
@@ -181,6 +182,7 @@ class MediaViewerActivity : BaseActivity(), IMediaViewerActivity, MediaSwipeClos
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_SHARE_MEDIA -> {
ShareProvider.clearTempFiles(this)
@@ -367,10 +369,10 @@ class MediaViewerActivity : BaseActivity(), IMediaViewerActivity, MediaSwipeClos
ParcelableMedia.Type.IMAGE -> {
val mediaUrl = media.media_url ?: return Fragment.instantiate(this, ExternalBrowserPageFragment::class.java.name, args) as MediaViewerFragment
args.putParcelable(EXTRA_MEDIA_URI, Uri.parse(mediaUrl))
- if (mediaUrl.endsWith(".gif")) {
- return Fragment.instantiate(this, GifPageFragment::class.java.name, args) as MediaViewerFragment
+ return if (mediaUrl.endsWith(".gif")) {
+ Fragment.instantiate(this, GifPageFragment::class.java.name, args) as MediaViewerFragment
} else {
- return Fragment.instantiate(this, ImagePageFragment::class.java.name, args) as MediaViewerFragment
+ Fragment.instantiate(this, ImagePageFragment::class.java.name, args) as MediaViewerFragment
}
}
ParcelableMedia.Type.ANIMATED_GIF, ParcelableMedia.Type.CARD_ANIMATED_GIF -> {
@@ -408,10 +410,10 @@ class MediaViewerActivity : BaseActivity(), IMediaViewerActivity, MediaSwipeClos
}
override fun onSwipeOffsetChanged(offset: Int) {
- val offsetFactor = 1 - (Math.abs(offset).toFloat() / swipeContainer.height)
+ val offsetFactor = 1 - (abs(offset).toFloat() / swipeContainer.height)
swipeContainer.backgroundAlpha = offsetFactor
val colorToolbar = overrideTheme.colorToolbar
- val alpha = Math.round(Color.alpha(colorToolbar) * offsetFactor).coerceIn(0..255)
+ val alpha = (Color.alpha(colorToolbar) * offsetFactor).roundToInt().coerceIn(0..255)
activityLayout.statusBarAlpha = alpha / 255f
}
@@ -450,11 +452,7 @@ class MediaViewerActivity : BaseActivity(), IMediaViewerActivity, MediaSwipeClos
}
private fun instantiateMediaViewerFragment(args: Bundle): MediaViewerFragment {
- return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
- Fragment.instantiate(this, VideoPageFragment::class.java.name, args) as MediaViewerFragment
- } else {
- Fragment.instantiate(this, ExoPlayerPageFragment::class.java.name, args) as MediaViewerFragment
- }
+ return Fragment.instantiate(this, ExoPlayerPageFragment::class.java.name, args) as MediaViewerFragment
}
private fun processShareIntent(intent: Intent) {
@@ -468,11 +466,10 @@ class MediaViewerActivity : BaseActivity(), IMediaViewerActivity, MediaSwipeClos
if (checkAllSelfPermissionsGranted(AndroidPermissions.WRITE_EXTERNAL_STORAGE)) {
saveToStorage()
} else {
- val permissions: Array
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
- permissions = arrayOf(AndroidPermissions.WRITE_EXTERNAL_STORAGE, AndroidPermissions.READ_EXTERNAL_STORAGE)
+ val permissions: Array = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
+ arrayOf(AndroidPermissions.WRITE_EXTERNAL_STORAGE, AndroidPermissions.READ_EXTERNAL_STORAGE)
} else {
- permissions = arrayOf(AndroidPermissions.WRITE_EXTERNAL_STORAGE)
+ arrayOf(AndroidPermissions.WRITE_EXTERNAL_STORAGE)
}
PermissionRequestDialog.show(supportFragmentManager, getString(R.string.message_permission_request_save_media),
permissions, REQUEST_PERMISSION_SAVE_MEDIA)
@@ -503,8 +500,7 @@ class MediaViewerActivity : BaseActivity(), IMediaViewerActivity, MediaSwipeClos
private fun saveToStorage() {
val fileInfo = getCurrentCacheFileInfo(saveToStoragePosition) ?: return
- val type = (fileInfo as? CacheProvider.CacheFileTypeSupport)?.cacheFileType
- val pubDir = when (type) {
+ val pubDir = when ((fileInfo as? CacheProvider.CacheFileTypeSupport)?.cacheFileType) {
CacheFileType.VIDEO -> {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES)
@@ -640,10 +636,10 @@ class MediaViewerActivity : BaseActivity(), IMediaViewerActivity, MediaSwipeClos
companion object {
- private val REQUEST_SHARE_MEDIA = 201
- private val REQUEST_PERMISSION_SAVE_MEDIA = 202
- private val REQUEST_PERMISSION_SHARE_MEDIA = 203
- private val REQUEST_SELECT_SAVE_MEDIA = 204
+ private const val REQUEST_SHARE_MEDIA = 201
+ private const val REQUEST_PERMISSION_SAVE_MEDIA = 202
+ private const val REQUEST_PERMISSION_SHARE_MEDIA = 203
+ private const val REQUEST_SELECT_SAVE_MEDIA = 204
@RequiresApi(Build.VERSION_CODES.JELLY_BEAN)
const val FLAG_SYSTEM_UI_HIDE_BARS = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/PremiumDashboardActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/PremiumDashboardActivity.kt
index 3214036d3e..59d6547510 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/PremiumDashboardActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/PremiumDashboardActivity.kt
@@ -89,6 +89,7 @@ class PremiumDashboardActivity : BaseActivity() {
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ super.onActivityResult(requestCode, resultCode, data)
when (resultCode) {
REQUEST_PURCHASE_EXTRA_FEATURES -> {
if (resultCode == Activity.RESULT_OK) {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/QuickSearchBarActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/QuickSearchBarActivity.kt
index c52d5203fb..91551eb84b 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/QuickSearchBarActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/QuickSearchBarActivity.kt
@@ -171,7 +171,7 @@ class QuickSearchBarActivity : BaseActivity(), OnClickListener, LoaderCallbacks<
override fun onDismiss(listView: ListView, reverseSortedPositions: IntArray) {
val adapter = suggestionsList.adapter as SuggestionsAdapter
val ids = LongArray(reverseSortedPositions.size)
- for (i in 0 until reverseSortedPositions.size) {
+ for (i in reverseSortedPositions.indices) {
val position = reverseSortedPositions[i]
val item = adapter.getSuggestionItem(position) ?: return
ids[i] = item._id
@@ -215,6 +215,7 @@ class QuickSearchBarActivity : BaseActivity(), OnClickListener, LoaderCallbacks<
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_SCAN_QR -> {
if (resultCode == Activity.RESULT_OK && data != null) {
@@ -504,7 +505,7 @@ class QuickSearchBarActivity : BaseActivity(), OnClickListener, LoaderCallbacks<
private fun getActualPosition(position: Int): Int {
var skipped = 0
for (i in 0 until removedPositions.size) {
- if (position + skipped >= removedPositions.get(i)) {
+ if (position + skipped >= removedPositions[i]) {
skipped++
}
}
@@ -537,10 +538,10 @@ class QuickSearchBarActivity : BaseActivity(), OnClickListener, LoaderCallbacks<
companion object {
- internal val VIEW_TYPE_SEARCH_HISTORY = 0
- internal val VIEW_TYPE_SAVED_SEARCH = 1
- internal val VIEW_TYPE_USER_SUGGESTION_ITEM = 2
- internal val VIEW_TYPE_USER_SCREEN_NAME = 3
+ internal const val VIEW_TYPE_SEARCH_HISTORY = 0
+ internal const val VIEW_TYPE_SAVED_SEARCH = 1
+ internal const val VIEW_TYPE_USER_SUGGESTION_ITEM = 2
+ internal const val VIEW_TYPE_USER_SCREEN_NAME = 3
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/SettingsActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/SettingsActivity.kt
index 7216b56a16..f42837efb1 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/SettingsActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/SettingsActivity.kt
@@ -54,6 +54,7 @@ import org.mariotaku.twidere.util.DeviceUtils
import org.mariotaku.twidere.util.KeyboardShortcutsHandler
import org.mariotaku.twidere.util.ThemeUtils
import java.util.*
+import kotlin.system.exitProcess
class SettingsActivity : BaseActivity(), OnItemClickListener, OnPreferenceStartFragmentCallback {
@@ -74,8 +75,7 @@ class SettingsActivity : BaseActivity(), OnItemClickListener, OnPreferenceStartF
shouldTerminate = savedInstanceState.getBoolean(EXTRA_SHOULD_TERMINATE, shouldTerminate)
} else if (intent.getBooleanExtra(EXTRA_SHOULD_TERMINATE, false)) {
finishNoRestart()
- System.exit(0)
- return
+ exitProcess(0)
}
val backgroundOption = currentThemeBackgroundOption
@@ -349,8 +349,8 @@ class SettingsActivity : BaseActivity(), OnItemClickListener, OnPreferenceStartF
companion object {
- val VIEW_TYPE_PREFERENCE_ENTRY = 0
- val VIEW_TYPE_HEADER_ENTRY = 1
+ const val VIEW_TYPE_PREFERENCE_ENTRY = 0
+ const val VIEW_TYPE_HEADER_ENTRY = 1
}
}
@@ -388,7 +388,7 @@ class SettingsActivity : BaseActivity(), OnItemClickListener, OnPreferenceStartF
class RestartConfirmDialogFragment : BaseDialogFragment(), DialogInterface.OnClickListener {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(activity!!)
+ val builder = AlertDialog.Builder(requireActivity())
if (arguments?.getBoolean(EXTRA_SHOULD_TERMINATE) == true) {
builder.setMessage(R.string.app_terminate_confirm)
builder.setNegativeButton(R.string.action_dont_terminate, this)
@@ -424,7 +424,7 @@ class SettingsActivity : BaseActivity(), OnItemClickListener, OnPreferenceStartF
companion object {
- private val RESULT_SETTINGS_CHANGED = 10
+ private const val RESULT_SETTINGS_CHANGED = 10
fun setShouldRecreate(activity: Activity) {
if (activity !is SettingsActivity) return
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/SignInActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/SignInActivity.kt
index 09f6c1e54c..3889005f8a 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/SignInActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/SignInActivity.kt
@@ -428,23 +428,30 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher,
internal fun onSignInError(exception: Exception) {
DebugLog.w(LOGTAG, "Sign in error", exception)
var errorReason: String? = null
- if (exception is AuthenticityTokenException) {
- Toast.makeText(this, R.string.message_toast_wrong_api_key, Toast.LENGTH_SHORT).show()
- errorReason = "wrong_api_key"
- } else if (exception is WrongUserPassException) {
- Toast.makeText(this, R.string.message_toast_wrong_username_password, Toast.LENGTH_SHORT).show()
- errorReason = "wrong_username_password"
- } else if (exception is SignInTask.WrongBasicCredentialException) {
- Toast.makeText(this, R.string.message_toast_wrong_username_password, Toast.LENGTH_SHORT).show()
- errorReason = "wrong_username_password"
- } else if (exception is SignInTask.WrongAPIURLFormatException) {
- Toast.makeText(this, R.string.message_toast_wrong_api_key, Toast.LENGTH_SHORT).show()
- errorReason = "wrong_api_key"
- } else if (exception is LoginVerificationException) {
- Toast.makeText(this, R.string.message_toast_login_verification_failed, Toast.LENGTH_SHORT).show()
- errorReason = "login_verification_failed"
- } else {
- Toast.makeText(this, exception.getErrorMessage(this), Toast.LENGTH_SHORT).show()
+ when (exception) {
+ is AuthenticityTokenException -> {
+ Toast.makeText(this, R.string.message_toast_wrong_api_key, Toast.LENGTH_SHORT).show()
+ errorReason = "wrong_api_key"
+ }
+ is WrongUserPassException -> {
+ Toast.makeText(this, R.string.message_toast_wrong_username_password, Toast.LENGTH_SHORT).show()
+ errorReason = "wrong_username_password"
+ }
+ is SignInTask.WrongBasicCredentialException -> {
+ Toast.makeText(this, R.string.message_toast_wrong_username_password, Toast.LENGTH_SHORT).show()
+ errorReason = "wrong_username_password"
+ }
+ is SignInTask.WrongAPIURLFormatException -> {
+ Toast.makeText(this, R.string.message_toast_wrong_api_key, Toast.LENGTH_SHORT).show()
+ errorReason = "wrong_api_key"
+ }
+ is LoginVerificationException -> {
+ Toast.makeText(this, R.string.message_toast_login_verification_failed, Toast.LENGTH_SHORT).show()
+ errorReason = "login_verification_failed"
+ }
+ else -> {
+ Toast.makeText(this, exception.getErrorMessage(this), Toast.LENGTH_SHORT).show()
+ }
}
Analyzer.log(SignIn(false, credentialsType = apiConfig.credentialsType,
errorReason = errorReason, accountType = apiConfig.type))
@@ -573,13 +580,13 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher,
class SignInTypeChooserDialogFragment : BaseDialogFragment(),
LoaderManager.LoaderCallbacks> {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setView(R.layout.dialog_expandable_list)
val dialog = builder.create()
dialog.onShow {
it.applyTheme()
val listView = it.expandableList
- val adapter = LoginTypeAdapter(context!!)
+ val adapter = LoginTypeAdapter(requireContext())
listView.setAdapter(adapter)
listView.setOnGroupClickListener { _, _, groupPosition, _ ->
val type = adapter.getGroup(groupPosition)
@@ -623,7 +630,7 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher,
AccountType.MASTODON, AccountType.STATUSNET)
val result = supportedAccountTypes.mapNotNullTo(ArrayList()) { type ->
if (type == AccountType.MASTODON) return@mapNotNullTo LoginType(type,
- listOf(CustomAPIConfig.mastodon(context!!)))
+ listOf(CustomAPIConfig.mastodon(requireContext())))
return@mapNotNullTo configGroup[type]?.let { list ->
LoginType(type, list.sortedBy { !it.isDefault })
}
@@ -632,7 +639,7 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher,
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader> {
- return DefaultAPIConfigLoader(context!!)
+ return DefaultAPIConfigLoader(requireContext())
}
override fun onLoaderReset(loader: Loader>) {
@@ -694,7 +701,7 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher,
var challengeType: String? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setTitle(R.string.login_verification)
builder.setView(R.layout.dialog_login_verification_code)
builder.positive(android.R.string.ok, this::performVerification)
@@ -753,7 +760,7 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher,
class PasswordSignInDialogFragment : BaseDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setView(R.layout.dialog_password_sign_in)
builder.positive(R.string.action_sign_in, this::onPositiveButton)
builder.setNegativeButton(android.R.string.cancel, null)
@@ -809,10 +816,10 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher,
val oauth = newMicroBlogInstance(context, endpoint = endpoint, auth = auth,
accountType = apiConfig.type, cls = TwitterOAuth::class.java)
val accessToken: OAuthToken
- if (oauthVerifier != null) {
- accessToken = oauth.getAccessToken(requestToken, oauthVerifier)
+ accessToken = if (oauthVerifier != null) {
+ oauth.getAccessToken(requestToken, oauthVerifier)
} else {
- accessToken = oauth.getAccessToken(requestToken)
+ oauth.getAccessToken(requestToken)
}
auth = apiConfig.getOAuthAuthorization(accessToken) ?:
throw MicroBlogException("Invalid OAuth credential")
@@ -823,7 +830,7 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher,
accountType = apiConfig.type, cls = MicroBlog::class.java)
val apiUser = twitter.verifyCredentials()
var color = analyseUserProfileColor(apiUser)
- val (type, extras) = SignInActivity.detectAccountType(twitter, apiUser, apiConfig.type)
+ val (type, extras) = detectAccountType(twitter, apiUser, apiConfig.type)
val accountKey = apiUser.key
val user = apiUser.toParcelable(accountKey, type, profileImageSize = profileImageSize)
val am = AccountManager.get(context)
@@ -901,7 +908,7 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher,
return authOAuth()
}
- @Throws(OAuthPasswordAuthenticator.AuthenticationException::class, MicroBlogException::class)
+ @Throws(AuthenticationException::class, MicroBlogException::class)
private fun authOAuth(): SignInResponse {
val activity = activityRef.get() ?: throw InterruptedException()
val endpoint = MicroBlogAPIFactory.getOAuthSignInEndpoint(apiUrlFormat,
@@ -940,7 +947,7 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher,
return getOAuthSignInResponse(activity, accessToken, Credentials.Type.XAUTH)
}
- @Throws(MicroBlogException::class, OAuthPasswordAuthenticator.AuthenticationException::class)
+ @Throws(MicroBlogException::class, AuthenticationException::class)
private fun authBasic(): SignInResponse {
val activity = activityRef.get() ?: throw InterruptedException()
val versionSuffix = if (apiConfig.isNoVersionSuffix) null else "1.1"
@@ -962,7 +969,7 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher,
}
var color = analyseUserProfileColor(apiUser)
- val (type, extras) = SignInActivity.detectAccountType(twitter, apiUser, apiConfig.type)
+ val (type, extras) = detectAccountType(twitter, apiUser, apiConfig.type)
val accountKey = apiUser.key
val user = apiUser.toParcelable(accountKey, type, profileImageSize = profileImageSize)
val am = AccountManager.get(activity)
@@ -991,7 +998,7 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher,
accountType = apiConfig.type, cls = MicroBlog::class.java)
val apiUser = twitter.verifyCredentials()
var color = analyseUserProfileColor(apiUser)
- val (type, extras) = SignInActivity.detectAccountType(twitter, apiUser, apiConfig.type)
+ val (type, extras) = detectAccountType(twitter, apiUser, apiConfig.type)
val accountKey = apiUser.key
val user = apiUser.toParcelable(accountKey, type, profileImageSize = profileImageSize)
val am = AccountManager.get(activity)
@@ -1018,7 +1025,7 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher,
accountType = apiConfig.type, cls = MicroBlog::class.java)
val apiUser = twitter.verifyCredentials()
var color = analyseUserProfileColor(apiUser)
- val (type, extras) = SignInActivity.detectAccountType(twitter, apiUser, apiConfig.type)
+ val (type, extras) = detectAccountType(twitter, apiUser, apiConfig.type)
val accountKey = apiUser.key
val user = apiUser.toParcelable(accountKey, type, profileImageSize = profileImageSize)
val am = AccountManager.get(activity)
@@ -1040,11 +1047,11 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher,
return SignInResponse(account != null, authType, credentials, user, color, type, extras)
}
- internal class WrongBasicCredentialException : OAuthPasswordAuthenticator.AuthenticationException()
+ internal class WrongBasicCredentialException : AuthenticationException()
- internal class WrongAPIURLFormatException : OAuthPasswordAuthenticator.AuthenticationException()
+ internal class WrongAPIURLFormatException : AuthenticationException()
- internal inner class InputLoginVerificationCallback : OAuthPasswordAuthenticator.LoginVerificationCallback {
+ internal inner class InputLoginVerificationCallback : LoginVerificationCallback {
override fun getLoginVerification(challengeType: String): String? {
// Dismiss current progress dialog
@@ -1087,10 +1094,10 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher,
protected val profileImageSize: String = activity.getString(R.string.profile_image_size)
final override fun doInBackground(vararg args: Any?): SingleResponse {
- try {
- return SingleResponse.getInstance(performLogin())
+ return try {
+ SingleResponse.getInstance(performLogin())
} catch (e: Exception) {
- return SingleResponse.getInstance(e)
+ SingleResponse.getInstance(e)
}
}
@@ -1189,8 +1196,8 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher,
const val REQUEST_BROWSER_TWITTER_SIGN_IN = 101
const val REQUEST_BROWSER_MASTODON_SIGN_IN = 102
- private val FRAGMENT_TAG_SIGN_IN_PROGRESS = "sign_in_progress"
- private val EXTRA_API_LAST_CHANGE = "api_last_change"
+ private const val FRAGMENT_TAG_SIGN_IN_PROGRESS = "sign_in_progress"
+ private const val EXTRA_API_LAST_CHANGE = "api_last_change"
@Throws(IOException::class)
internal fun detectAccountType(twitter: MicroBlog, user: User, type: String?): Pair {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/ThemedMediaPickerActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/ThemedMediaPickerActivity.kt
index a4334235c9..173d443d71 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/ThemedMediaPickerActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/ThemedMediaPickerActivity.kt
@@ -41,8 +41,8 @@ class ThemedMediaPickerActivity : MediaPickerActivity() {
companion object {
- fun withThemed(context: Context): MediaPickerActivity.IntentBuilder {
- val builder = MediaPickerActivity.IntentBuilder(context, ThemedMediaPickerActivity::class.java)
+ fun withThemed(context: Context): IntentBuilder {
+ val builder = IntentBuilder(context, ThemedMediaPickerActivity::class.java)
builder.cropImageActivityClass(ImageCropperActivity::class.java)
builder.streamDownloaderClass(RestFuNetworkStreamDownloader::class.java)
return builder
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/TrendsLocationSelectorActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/TrendsLocationSelectorActivity.kt
index 976364e322..9ab2c7d631 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/TrendsLocationSelectorActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/TrendsLocationSelectorActivity.kt
@@ -93,7 +93,7 @@ class TrendsLocationSelectorActivity : BaseActivity() {
private val list: Array get() = arguments?.getTypedArray(EXTRA_DATA) ?: emptyArray()
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val selectorBuilder = AlertDialog.Builder(context!!)
+ val selectorBuilder = AlertDialog.Builder(requireContext())
selectorBuilder.setTitle(R.string.trends_location)
selectorBuilder.setView(R.layout.dialog_expandable_list)
selectorBuilder.setNegativeButton(android.R.string.cancel, null)
@@ -101,7 +101,7 @@ class TrendsLocationSelectorActivity : BaseActivity() {
dialog.onShow {
it.applyTheme()
val listView = it.expandableList
- val adapter = ExpandableTrendLocationsListAdapter(context!!)
+ val adapter = ExpandableTrendLocationsListAdapter(requireContext())
adapter.data = list
listView.setAdapter(adapter)
listView.setOnGroupClickListener(ExpandableListView.OnGroupClickListener { _, _, groupPosition, _ ->
@@ -177,23 +177,14 @@ class TrendsLocationSelectorActivity : BaseActivity() {
}
override fun getGroupView(groupPosition: Int, isExpanded: Boolean, convertView: View?, parent: ViewGroup): View {
- val view: View
- if (convertView != null) {
- view = convertView
- } else {
- view = inflater.inflate(android.R.layout.simple_expandable_list_item_1, parent, false)
- }
+ val view: View = convertView ?: inflater.inflate(android.R.layout.simple_expandable_list_item_1, parent, false)
view.findViewById(android.R.id.text1).text = getGroup(groupPosition).name
return view
}
override fun getChildView(groupPosition: Int, childPosition: Int, isLastChild: Boolean, convertView: View?, parent: ViewGroup): View {
- val view: View
- if (convertView != null) {
- view = convertView
- } else {
- view = inflater.inflate(android.R.layout.simple_list_item_1, parent, false)
- }
+ val view: View =
+ convertView ?: inflater.inflate(android.R.layout.simple_list_item_1, parent, false)
val location = getChild(groupPosition, childPosition)
val text1 = view.findViewById(android.R.id.text1)
if (location.parentId == WORLDWIDE) {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/UserListSelectorActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/UserListSelectorActivity.kt
index 370f9a5626..9187f4b216 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/UserListSelectorActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/UserListSelectorActivity.kt
@@ -28,7 +28,6 @@ import android.view.View
import android.widget.AdapterView.OnItemClickListener
import android.widget.TextView
import androidx.loader.app.hasRunningLoadersSafe
-import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.layout_list_with_empty_view.*
import org.mariotaku.ktextension.Bundle
import org.mariotaku.ktextension.contains
@@ -96,8 +95,7 @@ class UserListSelectorActivity : BaseActivity(),
listView.setOnScrollListener(handler)
listView.setOnTouchListener(handler.touchListener)
listView.onItemClickListener = OnItemClickListener { view, _, position, _ ->
- val item = view.getItemAtPosition(position)
- when (item) {
+ when (val item = view.getItemAtPosition(position)) {
is ParcelableUserList -> {
val data = Intent()
data.putExtra(EXTRA_USER_LIST, item)
@@ -135,6 +133,7 @@ class UserListSelectorActivity : BaseActivity(),
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_SELECT_USER -> {
if (resultCode == Activity.RESULT_OK && data != null) {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/UserSelectorActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/UserSelectorActivity.kt
index d048cb6abd..de3a94f7dd 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/UserSelectorActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/UserSelectorActivity.kt
@@ -109,12 +109,15 @@ class UserSelectorActivity : BaseActivity(), OnItemClickListener, LoaderManager.
override fun onCreateLoader(id: Int, args: Bundle?): Loader> {
val accountKey = args?.getParcelable(EXTRA_ACCOUNT_KEY)!!
- val query = args?.getString(EXTRA_QUERY).orEmpty()
- val fromCache = args?.getBoolean(EXTRA_FROM_CACHE)
+ val query = args.getString(EXTRA_QUERY).orEmpty()
+ val fromCache = args.getBoolean(EXTRA_FROM_CACHE)
if (!fromCache) {
showProgress()
}
- return CacheUserSearchLoader(this, accountKey, query, !fromCache, true, true)
+ return CacheUserSearchLoader(this, accountKey, query, !fromCache,
+ fromCache = true,
+ fromUser = true
+ )
}
override fun onLoaderReset(loader: Loader>) {
@@ -126,12 +129,16 @@ class UserSelectorActivity : BaseActivity(), OnItemClickListener, LoaderManager.
listContainer.visibility = View.VISIBLE
adapter.setData(data, true)
loader as CacheUserSearchLoader
- if (data.isNotNullOrEmpty()) {
- showList()
- } else if (loader.query.isEmpty()) {
- showSearchHint()
- } else {
- showNotFound()
+ when {
+ data.isNotNullOrEmpty() -> {
+ showList()
+ }
+ loader.query.isEmpty() -> {
+ showSearchHint()
+ }
+ else -> {
+ showNotFound()
+ }
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/WebLinkHandlerActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/WebLinkHandlerActivity.kt
index 98f7d73008..c409f3911d 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/WebLinkHandlerActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/WebLinkHandlerActivity.kt
@@ -47,7 +47,7 @@ class WebLinkHandlerActivity : Activity() {
startActivity(handledIntent)
} else {
if (!handledSuccessfully) {
- Analyzer.logException(TwitterLinkException("Unable to handle twitter uri " + uri))
+ Analyzer.logException(TwitterLinkException("Unable to handle twitter uri $uri"))
}
val fallbackIntent = Intent(Intent.ACTION_VIEW, uri)
fallbackIntent.addCategory(Intent.CATEGORY_BROWSABLE)
@@ -277,7 +277,7 @@ class WebLinkHandlerActivity : Activity() {
sb.append(text)
}
if (!url.isNullOrEmpty()) {
- if (!sb.isEmpty()) {
+ if (sb.isNotEmpty()) {
sb.append(" ")
}
sb.append(url)
@@ -366,7 +366,7 @@ class WebLinkHandlerActivity : Activity() {
"photo", "album", "paipai", "q", "userview", "dialogue")
- private val AUTHORITY_TWITTER_COM = "twitter.com"
+ private const val AUTHORITY_TWITTER_COM = "twitter.com"
private fun regulateTwitterUri(data: Uri): Uri {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/content/AbsStatusDialogActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/content/AbsStatusDialogActivity.kt
index 519fe368f0..1353c4a9a4 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/content/AbsStatusDialogActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/content/AbsStatusDialogActivity.kt
@@ -64,6 +64,7 @@ abstract class AbsStatusDialogActivity : BaseActivity() {
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_SELECT_ACCOUNT -> {
if (resultCode == RESULT_OK && data != null) {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/iface/IControlBarActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/iface/IControlBarActivity.kt
index 0baafbb6ce..478830bdd6 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/iface/IControlBarActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/iface/IControlBarActivity.kt
@@ -63,12 +63,12 @@ interface IControlBarActivity {
}
val animator: ObjectAnimator
val offset = activity.controlBarOffset
- if (visible) {
+ animator = if (visible) {
if (offset >= 1) return
- animator = ObjectAnimator.ofFloat(activity, ControlBarOffsetProperty, offset, 1f)
+ ObjectAnimator.ofFloat(activity, ControlBarOffsetProperty, offset, 1f)
} else {
if (offset <= 0) return
- animator = ObjectAnimator.ofFloat(activity, ControlBarOffsetProperty, offset, 0f)
+ ObjectAnimator.ofFloat(activity, ControlBarOffsetProperty, offset, 0f)
}
animator.interpolator = DecelerateInterpolator()
animator.addListener(object : AnimatorListener {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/shortcut/AbsShortcutCreatorActivity.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/shortcut/AbsShortcutCreatorActivity.kt
index 2c9cfeb176..7d206325ae 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/activity/shortcut/AbsShortcutCreatorActivity.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/activity/shortcut/AbsShortcutCreatorActivity.kt
@@ -46,6 +46,7 @@ abstract class AbsShortcutCreatorActivity : BaseActivity() {
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
REQUEST_SELECT_ACCOUNT -> {
if (resultCode != Activity.RESULT_OK || data == null) {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/AccountSelectorAdapter.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/AccountSelectorAdapter.kt
index 3bc8e8ea96..093e29adc5 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/AccountSelectorAdapter.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/AccountSelectorAdapter.kt
@@ -31,6 +31,7 @@ import org.mariotaku.twidere.model.AccountDetails
import org.mariotaku.twidere.view.holder.AccountProfileImageViewHolder
import org.mariotaku.twidere.view.transformer.AccountsSelectorTransformer
import java.util.*
+import kotlin.math.max
class AccountSelectorAdapter(
private val inflater: LayoutInflater,
@@ -46,7 +47,7 @@ class AccountSelectorAdapter(
set(value) {
if (value != null) {
val previousAccounts = accounts
- if (previousAccounts != null) {
+ field = if (previousAccounts != null) {
val tmpList = arrayListOf(*value)
val tmpResult = ArrayList()
previousAccounts.forEach { previousAccount ->
@@ -56,9 +57,9 @@ class AccountSelectorAdapter(
}
}
tmpResult.addAll(tmpList)
- field = tmpResult.toTypedArray()
+ tmpResult.toTypedArray()
} else {
- field = value
+ value
}
} else {
field = null
@@ -115,16 +116,16 @@ class AccountSelectorAdapter(
}
override fun getCount(): Int {
- return Math.max(3, accountsCount)
+ return max(3, accountsCount)
}
val accountStart: Int
- get() = Math.max(0, 3 - accountsCount)
+ get() = max(0, 3 - accountsCount)
val accountsCount: Int
get() {
val accounts = this.accounts ?: return 0
- return Math.max(0, accounts.size - 1)
+ return max(0, accounts.size - 1)
}
override fun getPageWidth(position: Int): Float {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/AccountsSpinnerAdapter.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/AccountsSpinnerAdapter.kt
index 1124dff7cf..64dbadde1b 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/AccountsSpinnerAdapter.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/AccountsSpinnerAdapter.kt
@@ -65,7 +65,7 @@ class AccountsSpinnerAdapter(
text1?.spannable = item.user.name
text2?.visibility = View.VISIBLE
val showType = objects.filter { it.type != null }.groupBy { it.type }.count().let { it > 1 }
- text2?.spannable = if (item.type == AccountType.MASTODON) {
+ text2?.spannable = if (item.type == AccountType.MASTODON || item.type == AccountType.STATUSNET) {
item.account.name
} else {
"${if (showType) item.type else ""}@${item.user.screen_name}"
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/DummyItemAdapter.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/DummyItemAdapter.kt
index 06e193bd56..57ac870c82 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/DummyItemAdapter.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/DummyItemAdapter.kt
@@ -65,6 +65,8 @@ class DummyItemAdapter(
var showCardNumbers: Boolean = false
+ var showLinkPreview: Boolean = false
+
private var showingActionCardPosition = RecyclerView.NO_POSITION
private val showingFullTextStates = SparseBooleanArray()
@@ -78,14 +80,18 @@ class DummyItemAdapter(
}
override fun getStatus(position: Int, raw: Boolean): ParcelableStatus {
- if (adapter is ParcelableStatusesAdapter) {
- return adapter.getStatus(position, raw)
- } else if (adapter is VariousItemsAdapter) {
- return adapter.getItem(position) as ParcelableStatus
- } else if (adapter is ParcelableActivitiesAdapter) {
- return adapter.getActivity(position).activityStatus!!
+ return when (adapter) {
+ is ParcelableStatusesAdapter -> {
+ adapter.getStatus(position, raw)
+ }
+ is VariousItemsAdapter -> {
+ adapter.getItem(position) as ParcelableStatus
+ }
+ is ParcelableActivitiesAdapter -> {
+ adapter.getActivity(position).activityStatus!!
+ }
+ else -> throw IndexOutOfBoundsException()
}
- throw IndexOutOfBoundsException()
}
override fun getStatusCount(raw: Boolean) = 0
@@ -110,6 +116,10 @@ class DummyItemAdapter(
return showCardActions || showingActionCardPosition == position
}
+ override fun isLinkPreviewShown(position: Int): Boolean {
+ return showLinkPreview
+ }
+
override fun showCardActions(position: Int) {
if (showingActionCardPosition != RecyclerView.NO_POSITION && adapter != null) {
adapter.notifyItemChanged(showingActionCardPosition)
@@ -189,6 +199,7 @@ class DummyItemAdapter(
sensitiveContentEnabled = preferences[displaySensitiveContentsKey]
showCardActions = !preferences[hideCardActionsKey]
showCardNumbers = !preferences[hideCardNumbersKey]
+ showLinkPreview = preferences[showLinkPreviewKey]
linkHighlightingStyle = preferences[linkHighlightOptionKey]
lightFont = preferences[lightFontKey]
useStarsForLikes = preferences[iWantMyStarsBackKey]
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/MessagesConversationAdapter.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/MessagesConversationAdapter.kt
index c3f4f1abbb..3f7792b871 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/MessagesConversationAdapter.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/MessagesConversationAdapter.kt
@@ -120,8 +120,7 @@ class MessagesConversationAdapter(
}
ITEM_LOAD_OLDER_INDICATOR -> {
val view = inflater.inflate(LoadIndicatorViewHolder.layoutResource, parent, false)
- val holder = LoadIndicatorViewHolder(view)
- return holder
+ return LoadIndicatorViewHolder(view)
}
}
throw UnsupportedOperationException()
@@ -151,20 +150,19 @@ class MessagesConversationAdapter(
}
override fun getItemViewType(position: Int): Int {
- val countIndex = itemCounts.getItemCountIndex(position)
- when (countIndex) {
+ return when (val countIndex = itemCounts.getItemCountIndex(position)) {
ITEM_START_MESSAGE -> when (getMessage(position, reuse = true).message_type) {
MessageType.STICKER -> {
- return ITEM_TYPE_STICKER_MESSAGE
+ ITEM_TYPE_STICKER_MESSAGE
}
MessageType.CONVERSATION_CREATE, MessageType.JOIN_CONVERSATION,
MessageType.PARTICIPANTS_LEAVE, MessageType.PARTICIPANTS_JOIN,
MessageType.CONVERSATION_NAME_UPDATE, MessageType.CONVERSATION_AVATAR_UPDATE -> {
- return ITEM_TYPE_NOTICE_MESSAGE
+ ITEM_TYPE_NOTICE_MESSAGE
}
- else -> return ITEM_TYPE_TEXT_MESSAGE
+ else -> ITEM_TYPE_TEXT_MESSAGE
}
- ITEM_START_LOAD_OLDER -> return ITEM_LOAD_OLDER_INDICATOR
+ ITEM_START_LOAD_OLDER -> ITEM_LOAD_OLDER_INDICATOR
else -> throw UnsupportedCountIndexException(countIndex, position)
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/MessagesEntriesAdapter.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/MessagesEntriesAdapter.kt
index ac65894c15..9f3ea8cf7a 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/MessagesEntriesAdapter.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/MessagesEntriesAdapter.kt
@@ -77,10 +77,9 @@ class MessagesEntriesAdapter(
}
override fun getItemViewType(position: Int): Int {
- val countIndex = itemCounts.getItemCountIndex(position)
- when (countIndex) {
- 0 -> return ITEM_TYPE_MESSAGE_ENTRY
- 1 -> return ITEM_VIEW_TYPE_LOAD_INDICATOR
+ return when (val countIndex = itemCounts.getItemCountIndex(position)) {
+ 0 -> ITEM_TYPE_MESSAGE_ENTRY
+ 1 -> ITEM_VIEW_TYPE_LOAD_INDICATOR
else -> throw UnsupportedCountIndexException(countIndex, position)
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/ParcelableActivitiesAdapter.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/ParcelableActivitiesAdapter.kt
index 89d7c8c2b1..f2e55fc4bd 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/ParcelableActivitiesAdapter.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/ParcelableActivitiesAdapter.kt
@@ -152,13 +152,12 @@ class ParcelableActivitiesAdapter(
}
override fun getItemId(position: Int): Long {
- val countIndex = itemCounts.getItemCountIndex(position)
- when (countIndex) {
+ return when (val countIndex = itemCounts.getItemCountIndex(position)) {
ITEM_INDEX_ACTIVITY -> {
- return getRowId(position, false)
+ getRowId(position, false)
}
else -> {
- return (countIndex.toLong() shl 32) or getItemViewType(position).toLong()
+ (countIndex.toLong() shl 32) or getItemViewType(position).toLong()
}
}
}
@@ -216,7 +215,7 @@ class ParcelableActivitiesAdapter(
return EmptyViewHolder(Space(context))
}
}
- throw UnsupportedOperationException("Unsupported viewType " + viewType)
+ throw UnsupportedOperationException("Unsupported viewType $viewType")
}
@@ -245,14 +244,12 @@ class ParcelableActivitiesAdapter(
}
override fun getItemViewType(position: Int): Int {
- val countIndex = getItemCountIndex(position)
- when (countIndex) {
+ when (val countIndex = getItemCountIndex(position)) {
ITEM_INDEX_ACTIVITY -> {
if (isGapItem(position)) {
return ITEM_VIEW_TYPE_GAP
}
- val action = getAction(position)
- when (action) {
+ when (getAction(position)) {
Activity.Action.MENTION, Activity.Action.QUOTE, Activity.Action.REPLY -> {
return ITEM_VIEW_TYPE_STATUS
}
@@ -350,12 +347,12 @@ class ParcelableActivitiesAdapter(
throw IndexOutOfBoundsException("index: $position, valid range is $validRange")
}
val data = this.data!!
- if (reuse && data is ObjectCursor) {
+ return if (reuse && data is ObjectCursor) {
val activity = data.setInto(dataPosition, reuseActivity)
activity.after_filtered_sources = null
- return activity
+ activity
} else {
- return data[dataPosition]
+ data[dataPosition]
}
}
@@ -428,7 +425,7 @@ class ParcelableActivitiesAdapter(
internal val text2 = itemView.findViewById(android.R.id.text2)
init {
- text2.setSingleLine(false)
+ text2.isSingleLine = false
}
@SuppressLint("SetTextI18n")
@@ -529,7 +526,7 @@ class ParcelableActivitiesAdapter(
result = 31 * result + timestamp.hashCode()
result = 31 * result + gap.hashCode()
result = 31 * result + action.hashCode()
- result = 31 * result + (filteredSources?.let { Arrays.hashCode(it) } ?: 0)
+ result = 31 * result + (filteredSources?.contentHashCode() ?: 0)
return result
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/ParcelableGroupsAdapter.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/ParcelableGroupsAdapter.kt
index da08946dc3..5075f74cf3 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/ParcelableGroupsAdapter.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/ParcelableGroupsAdapter.kt
@@ -108,7 +108,7 @@ class ParcelableGroupsAdapter(
return LoadIndicatorViewHolder(view)
}
}
- throw IllegalStateException("Unknown view type " + viewType)
+ throw IllegalStateException("Unknown view type $viewType")
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
@@ -142,6 +142,6 @@ class ParcelableGroupsAdapter(
companion object {
- val ITEM_VIEW_TYPE_USER_LIST = 2
+ const val ITEM_VIEW_TYPE_USER_LIST = 2
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/ParcelableStatusesAdapter.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/ParcelableStatusesAdapter.kt
index 96bc0ae8c1..54bcbc9806 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/ParcelableStatusesAdapter.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/ParcelableStatusesAdapter.kt
@@ -21,11 +21,11 @@ package org.mariotaku.twidere.adapter
import android.content.Context
import android.database.CursorIndexOutOfBoundsException
-import androidx.legacy.widget.Space
-import androidx.recyclerview.widget.RecyclerView
import android.util.SparseBooleanArray
import android.view.LayoutInflater
import android.view.ViewGroup
+import androidx.legacy.widget.Space
+import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.RequestManager
import org.mariotaku.kpreferences.get
import org.mariotaku.ktextension.*
@@ -80,6 +80,7 @@ abstract class ParcelableStatusesAdapter(
final override val sensitiveContentEnabled: Boolean = preferences.getBoolean(KEY_DISPLAY_SENSITIVE_CONTENTS, false)
private val showCardActions: Boolean = !preferences[hideCardActionsKey]
private val showCardNumbers: Boolean = !preferences[hideCardNumbersKey]
+ private val showLinkPreview: Boolean = preferences[showLinkPreviewKey]
private val gapLoadingIds: MutableSet = HashSet()
@@ -170,25 +171,29 @@ abstract class ParcelableStatusesAdapter(
override fun setData(data: List?): Boolean {
var changed = true
- if (data == null) {
- displayPositions = null
- displayDataCount = 0
- } else if (data is ObjectCursor) {
- displayPositions = null
- displayDataCount = data.size
- } else {
- var filteredCount = 0
- displayPositions = IntArray(data.size).apply {
- data.forEachIndexed { i, item ->
- if (!item.is_gap && item.is_filtered) {
- filteredCount++
- } else {
- this[i - filteredCount] = i
+ when (data) {
+ null -> {
+ displayPositions = null
+ displayDataCount = 0
+ }
+ is ObjectCursor -> {
+ displayPositions = null
+ displayDataCount = data.size
+ }
+ else -> {
+ var filteredCount = 0
+ displayPositions = IntArray(data.size).apply {
+ data.forEachIndexed { i, item ->
+ if (!item.is_gap && item.is_filtered) {
+ filteredCount++
+ } else {
+ this[i - filteredCount] = i
+ }
}
}
+ displayDataCount = data.size - filteredCount
+ changed = this.data != data
}
- displayDataCount = data.size - filteredCount
- changed = this.data != data
}
this.data = data
this.infoCache = if (data != null) arrayOfNulls(data.size) else null
@@ -267,6 +272,10 @@ abstract class ParcelableStatusesAdapter(
return showCardNumbers || showingActionCardId == getItemId(position)
}
+ override fun isLinkPreviewShown(position: Int): Boolean {
+ return showLinkPreview
+ }
+
override fun isCardActionsShown(position: Int): Boolean {
if (position == RecyclerView.NO_POSITION) return showCardActions
return showCardActions || showingActionCardId == getItemId(position)
@@ -319,7 +328,7 @@ abstract class ParcelableStatusesAdapter(
return TimelineFilterHeaderViewHolder(this, view)
}
}
- throw IllegalStateException("Unknown view type " + viewType)
+ throw IllegalStateException("Unknown view type $viewType")
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
@@ -345,8 +354,7 @@ abstract class ParcelableStatusesAdapter(
if (position == 0 && ILoadMoreSupportAdapter.START in loadMoreIndicatorPosition) {
return ITEM_VIEW_TYPE_LOAD_INDICATOR
}
- val countIndex = getItemCountIndex(position)
- when (countIndex) {
+ when (val countIndex = getItemCountIndex(position)) {
ITEM_INDEX_LOAD_START_INDICATOR, ITEM_INDEX_LOAD_END_INDICATOR -> {
return ITEM_VIEW_TYPE_LOAD_INDICATOR
}
@@ -405,7 +413,7 @@ abstract class ParcelableStatusesAdapter(
// lesser equals than read position
if (positionKey <= 0) return RecyclerView.NO_POSITION
val range = rangeOfSize(statusStartIndex, getStatusCount(raw))
- if (range.isEmpty() || range.start < 0) return RecyclerView.NO_POSITION
+ if (range.isEmpty() || range.first < 0) return RecyclerView.NO_POSITION
if (positionKey < getStatusPositionKey(range.last, raw)) {
return range.last
}
@@ -417,7 +425,7 @@ abstract class ParcelableStatusesAdapter(
// lesser equals than read position
if (sortId <= 0) return RecyclerView.NO_POSITION
val range = rangeOfSize(statusStartIndex, getStatusCount(raw))
- if (range.isEmpty() || range.start < 0) return RecyclerView.NO_POSITION
+ if (range.isEmpty() || range.first < 0) return RecyclerView.NO_POSITION
if (sortId < getStatusSortId(range.last, raw)) {
return range.last
}
@@ -484,11 +492,11 @@ abstract class ParcelableStatusesAdapter(
} else {
dataPosition
}
- if (reuse && data is ObjectCursor) {
+ return if (reuse && data is ObjectCursor) {
reuseStatus.is_filtered = false
- return data.setInto(listPosition, reuseStatus)
+ data.setInto(listPosition, reuseStatus)
} else {
- return data[listPosition]
+ data[listPosition]
}
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/ParcelableUserListsAdapter.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/ParcelableUserListsAdapter.kt
index 4bb0efd7f7..b52022311a 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/ParcelableUserListsAdapter.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/ParcelableUserListsAdapter.kt
@@ -99,7 +99,7 @@ class ParcelableUserListsAdapter(
return LoadIndicatorViewHolder(view)
}
}
- throw IllegalStateException("Unknown view type " + viewType)
+ throw IllegalStateException("Unknown view type $viewType")
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
@@ -122,7 +122,7 @@ class ParcelableUserListsAdapter(
companion object {
- val ITEM_VIEW_TYPE_USER_LIST = 2
+ const val ITEM_VIEW_TYPE_USER_LIST = 2
fun createUserListViewHolder(adapter: IUserListsAdapter<*>,
inflater: LayoutInflater,
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/ParcelableUsersAdapter.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/ParcelableUsersAdapter.kt
index 9d4b4389a4..0e14625739 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/ParcelableUsersAdapter.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/ParcelableUsersAdapter.kt
@@ -140,7 +140,7 @@ class ParcelableUsersAdapter(
return LoadIndicatorViewHolder(view)
}
}
- throw IllegalStateException("Unknown view type " + viewType)
+ throw IllegalStateException("Unknown view type $viewType")
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/SelectableUsersAdapter.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/SelectableUsersAdapter.kt
index 6dbaa6d549..09c6540aaf 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/SelectableUsersAdapter.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/SelectableUsersAdapter.kt
@@ -70,15 +70,14 @@ class SelectableUsersAdapter(
when (viewType) {
ITEM_VIEW_TYPE_USER -> {
val view = inflater.inflate(R.layout.list_item_simple_user, parent, false)
- val holder = SelectableUserViewHolder(view, this)
- return holder
+ return SelectableUserViewHolder(view, this)
}
ITEM_VIEW_TYPE_LOAD_INDICATOR -> {
val view = inflater.inflate(R.layout.list_item_load_indicator, parent, false)
return LoadIndicatorViewHolder(view)
}
}
- throw IllegalStateException("Unknown view type " + viewType)
+ throw IllegalStateException("Unknown view type $viewType")
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
@@ -90,18 +89,16 @@ class SelectableUsersAdapter(
}
override fun getItemViewType(position: Int): Int {
- val countIndex = itemCounts.getItemCountIndex(position)
- when (countIndex) {
- ITEM_TYPE_START_INDICATOR, ITEM_TYPE_END_INDICATOR -> return ITEM_VIEW_TYPE_LOAD_INDICATOR
- ITEM_TYPE_USER -> return ITEM_VIEW_TYPE_USER
+ return when (val countIndex = itemCounts.getItemCountIndex(position)) {
+ ITEM_TYPE_START_INDICATOR, ITEM_TYPE_END_INDICATOR -> ITEM_VIEW_TYPE_LOAD_INDICATOR
+ ITEM_TYPE_USER -> ITEM_VIEW_TYPE_USER
else -> throw UnsupportedCountIndexException(countIndex, position)
}
}
override fun getItemId(position: Int): Long {
- val countIndex = itemCounts.getItemCountIndex(position)
- return when (countIndex) {
+ return when (val countIndex = itemCounts.getItemCountIndex(position)) {
ITEM_TYPE_START_INDICATOR, ITEM_TYPE_END_INDICATOR -> (countIndex.toLong() shl 32)
ITEM_TYPE_USER -> (countIndex.toLong() shl 32) or getUser(position).hashCode().toLong()
else -> throw UnsupportedCountIndexException(countIndex, position)
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/SimpleParcelableUserListsAdapter.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/SimpleParcelableUserListsAdapter.kt
index 8e74fcc735..9522c938a7 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/SimpleParcelableUserListsAdapter.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/SimpleParcelableUserListsAdapter.kt
@@ -67,8 +67,7 @@ class SimpleParcelableUserListsAdapter(
return view
}
1 -> {
- val view = createViewFromResource(position, convertView, parent, R.layout.list_item_load_indicator)
- return view
+ return createViewFromResource(position, convertView, parent, R.layout.list_item_load_indicator)
}
}
throw UnsupportedOperationException()
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/SimpleParcelableUsersAdapter.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/SimpleParcelableUsersAdapter.kt
index 6bdf9c0c33..5a9f32b82d 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/SimpleParcelableUsersAdapter.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/SimpleParcelableUsersAdapter.kt
@@ -36,11 +36,7 @@ class SimpleParcelableUsersAdapter(
override fun getItemId(position: Int): Long {
val item = getItem(position)
- if (item != null) {
- return item.hashCode().toLong()
- } else {
- return -1
- }
+ return item?.hashCode()?.toLong() ?: -1
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/StatusDetailsAdapter.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/StatusDetailsAdapter.kt
index 693423eac6..9973b4fd56 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/StatusDetailsAdapter.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/StatusDetailsAdapter.kt
@@ -19,7 +19,6 @@
package org.mariotaku.twidere.adapter
-import androidx.recyclerview.widget.RecyclerView
import android.text.TextUtils
import android.text.method.LinkMovementMethod
import android.util.SparseBooleanArray
@@ -28,6 +27,7 @@ import android.view.View
import android.view.ViewGroup
import android.widget.Space
import android.widget.TextView
+import androidx.recyclerview.widget.RecyclerView
import org.mariotaku.kpreferences.get
import org.mariotaku.ktextension.contains
import org.mariotaku.microblog.library.twitter.model.TranslationResult
@@ -51,7 +51,7 @@ import org.mariotaku.twidere.view.holder.status.DetailStatusViewHolder
class StatusDetailsAdapter(
val fragment: StatusFragment
-) : LoadMoreSupportAdapter(fragment.context!!, fragment.requestManager),
+) : LoadMoreSupportAdapter(fragment.requireContext(), fragment.requestManager),
IStatusesAdapter>, IItemCountsAdapter {
override val twidereLinkify: TwidereLinkify
@@ -72,6 +72,7 @@ class StatusDetailsAdapter(
private val cardBackgroundColor: Int
private val showCardActions = !preferences[hideCardActionsKey]
private val showCardNumbers = !preferences[hideCardNumbersKey]
+ private val showLinkPreview = preferences[showLinkPreviewKey]
private var recyclerView: RecyclerView? = null
private var detailMediaExpanded: Boolean = false
@@ -79,10 +80,10 @@ class StatusDetailsAdapter(
internal set
var translationResult: TranslationResult? = null
internal set(translation) {
- if (translation == null || status?.originalId != translation.id) {
- field = null
+ field = if (translation == null || status?.originalId != translation.id) {
+ null
} else {
- field = translation
+ translation
}
notifyDataSetChanged()
}
@@ -117,7 +118,7 @@ class StatusDetailsAdapter(
inflater = LayoutInflater.from(context)
cardBackgroundColor = ThemeUtils.getCardBackgroundColor(context!!,
preferences[themeBackgroundOptionKey], preferences[themeBackgroundAlphaKey])
- val listener = StatusAdapterLinkClickHandler>(context!!, preferences)
+ val listener = StatusAdapterLinkClickHandler>(context, preferences)
listener.setAdapter(this)
twidereLinkify = TwidereLinkify(listener)
}
@@ -179,6 +180,10 @@ class StatusDetailsAdapter(
return showCardNumbers || showingActionCardPosition == position
}
+ override fun isLinkPreviewShown(position: Int): Boolean {
+ return showLinkPreview
+ }
+
override fun isCardActionsShown(position: Int): Boolean {
if (position == RecyclerView.NO_POSITION) return showCardActions
return showCardActions || showingActionCardPosition == position
@@ -306,7 +311,7 @@ class StatusDetailsAdapter(
when (holder.itemViewType) {
VIEW_TYPE_DETAIL_STATUS -> {
holder as DetailStatusViewHolder
- payloads.forEach { it ->
+ payloads.forEach {
when (it) {
is StatusFragment.StatusActivity -> {
holder.updateStatusActivity(it)
@@ -397,7 +402,7 @@ class StatusDetailsAdapter(
if (position in typeStart until typeEnd) return type
typeStart = typeEnd
}
- throw IllegalStateException("Unknown position " + position)
+ throw IllegalStateException("Unknown position $position")
}
fun getItemTypeStart(position: Int): Int {
@@ -497,10 +502,10 @@ class StatusDetailsAdapter(
var isConversationsLoading: Boolean
get() = ILoadMoreSupportAdapter.START in loadMoreIndicatorPosition
set(loading) {
- if (loading) {
- loadMoreIndicatorPosition = loadMoreIndicatorPosition or ILoadMoreSupportAdapter.START
+ loadMoreIndicatorPosition = if (loading) {
+ loadMoreIndicatorPosition or ILoadMoreSupportAdapter.START
} else {
- loadMoreIndicatorPosition = loadMoreIndicatorPosition and ILoadMoreSupportAdapter.START.inv()
+ loadMoreIndicatorPosition and ILoadMoreSupportAdapter.START.inv()
}
updateItemDecoration()
}
@@ -508,10 +513,10 @@ class StatusDetailsAdapter(
var isRepliesLoading: Boolean
get() = ILoadMoreSupportAdapter.END in loadMoreIndicatorPosition
set(loading) {
- if (loading) {
- loadMoreIndicatorPosition = loadMoreIndicatorPosition or ILoadMoreSupportAdapter.END
+ loadMoreIndicatorPosition = if (loading) {
+ loadMoreIndicatorPosition or ILoadMoreSupportAdapter.END
} else {
- loadMoreIndicatorPosition = loadMoreIndicatorPosition and ILoadMoreSupportAdapter.END.inv()
+ loadMoreIndicatorPosition and ILoadMoreSupportAdapter.END.inv()
}
updateItemDecoration()
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/SupportTabsAdapter.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/SupportTabsAdapter.kt
index 5f18ceacca..0c31c4f9c1 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/SupportTabsAdapter.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/SupportTabsAdapter.kt
@@ -26,7 +26,6 @@ import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.viewpager.widget.PagerAdapter
import android.view.View
-import android.view.ViewGroup
import org.mariotaku.twidere.fragment.iface.RefreshScrollTopInterface
import org.mariotaku.twidere.fragment.iface.SupportFragmentCallback
import org.mariotaku.twidere.model.SupportTabSpec
@@ -163,6 +162,6 @@ class SupportTabsAdapter(
companion object {
- private val EXTRA_ADAPTER_POSITION = "adapter_position"
+ private const val EXTRA_ADAPTER_POSITION = "adapter_position"
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/VariousItemsAdapter.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/VariousItemsAdapter.kt
index d2bd29e6ae..6f652a85ca 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/VariousItemsAdapter.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/VariousItemsAdapter.kt
@@ -57,8 +57,7 @@ class VariousItemsAdapter(
}
VIEW_TYPE_HASHTAG -> {
val view = inflater.inflate(R.layout.list_item_two_line_small, parent, false)
- val holder = HashtagViewHolder(view, hashtagClickListener)
- return holder
+ return HashtagViewHolder(view, hashtagClickListener)
}
}
throw UnsupportedOperationException()
@@ -88,12 +87,12 @@ class VariousItemsAdapter(
}
private fun getItemViewType(obj: Any): Int {
- when (obj) {
- is ParcelableStatus -> return VIEW_TYPE_STATUS
- is ParcelableUser -> return VIEW_TYPE_USER
- is ParcelableUserList -> return VIEW_TYPE_USER_LIST
- is ParcelableHashtag -> return VIEW_TYPE_HASHTAG
- else -> throw UnsupportedOperationException("Unsupported object " + obj)
+ return when (obj) {
+ is ParcelableStatus -> VIEW_TYPE_STATUS
+ is ParcelableUser -> VIEW_TYPE_USER
+ is ParcelableUserList -> VIEW_TYPE_USER_LIST
+ is ParcelableHashtag -> VIEW_TYPE_HASHTAG
+ else -> throw UnsupportedOperationException("Unsupported object $obj")
}
}
@@ -113,9 +112,9 @@ class VariousItemsAdapter(
companion object {
- val VIEW_TYPE_STATUS = 1
- val VIEW_TYPE_USER = 2
- val VIEW_TYPE_USER_LIST = 3
- val VIEW_TYPE_HASHTAG = 4
+ const val VIEW_TYPE_STATUS = 1
+ const val VIEW_TYPE_USER = 2
+ const val VIEW_TYPE_USER_LIST = 3
+ const val VIEW_TYPE_HASHTAG = 4
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/iface/ILoadMoreSupportAdapter.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/iface/ILoadMoreSupportAdapter.kt
index af1fce26bc..3f9877dcd1 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/iface/ILoadMoreSupportAdapter.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/iface/ILoadMoreSupportAdapter.kt
@@ -36,7 +36,7 @@ interface ILoadMoreSupportAdapter {
annotation class IndicatorPosition
companion object {
- val ITEM_VIEW_TYPE_LOAD_INDICATOR = 0
+ const val ITEM_VIEW_TYPE_LOAD_INDICATOR = 0
const val NONE: Long = 0
const val START: Long = 1
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/iface/IStatusesAdapter.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/iface/IStatusesAdapter.kt
index e3c6925560..053e622c27 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/iface/IStatusesAdapter.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/adapter/iface/IStatusesAdapter.kt
@@ -34,6 +34,8 @@ interface IStatusesAdapter : IContentAdapter, IGapSupportedAdapter {
val statusClickListener: IStatusViewHolder.StatusClickListener?
fun isCardNumbersShown(position: Int): Boolean
+
+ fun isLinkPreviewShown(position: Int): Boolean
fun isCardActionsShown(position: Int): Boolean
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/app/TwidereApplication.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/app/TwidereApplication.kt
index 490ccd1c95..142cd73071 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/app/TwidereApplication.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/app/TwidereApplication.kt
@@ -329,7 +329,7 @@ class TwidereApplication : Application(), OnSharedPreferenceChangeListener {
companion object {
- private val KEY_KEYBOARD_SHORTCUT_INITIALIZED = "keyboard_shortcut_initialized"
+ private const val KEY_KEYBOARD_SHORTCUT_INITIALIZED = "keyboard_shortcut_initialized"
var instance: TwidereApplication? = null
private set
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/constant/PreferenceKeys.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/constant/PreferenceKeys.kt
index 0432b03a25..92a4803369 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/constant/PreferenceKeys.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/constant/PreferenceKeys.kt
@@ -90,6 +90,7 @@ val tabPositionKey = KStringKey(KEY_TAB_POSITION, SharedPreferenceConstants.DEFA
val yandexKeyKey = KStringKey(SharedPreferenceConstants.KEY_YANDEX_KEY, TwidereConstants.YANDEX_KEY)
val autoHideTabs = KBooleanKey(SharedPreferenceConstants.KEY_AUTO_HIDE_TABS, true)
val hideCardNumbersKey = KBooleanKey(KEY_HIDE_CARD_NUMBERS, false)
+val showLinkPreviewKey = KBooleanKey(KEY_SHOW_LINK_PREVIEW, false)
object cacheSizeLimitKey : KSimpleKey(KEY_CACHE_SIZE_LIMIT, 300) {
@@ -146,10 +147,10 @@ object profileImageStyleKey : KSimpleKey(KEY_PROFILE_IMAGE_STYLE, ImageShap
object mediaPreviewStyleKey : KSimpleKey(KEY_MEDIA_PREVIEW_STYLE, PreviewStyle.CROP) {
override fun read(preferences: SharedPreferences): Int {
- when (preferences.getString(key, null)) {
- VALUE_MEDIA_PREVIEW_STYLE_SCALE -> return PreviewStyle.SCALE
- VALUE_MEDIA_PREVIEW_STYLE_REAL_SIZE -> return PreviewStyle.ACTUAL_SIZE
- else -> return PreviewStyle.CROP
+ return when (preferences.getString(key, null)) {
+ VALUE_MEDIA_PREVIEW_STYLE_SCALE -> PreviewStyle.SCALE
+ VALUE_MEDIA_PREVIEW_STYLE_REAL_SIZE -> PreviewStyle.ACTUAL_SIZE
+ else -> PreviewStyle.CROP
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/BitmapFactoryExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/BitmapFactoryExtensions.kt
index 6ce1bda866..a098c32306 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/BitmapFactoryExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/BitmapFactoryExtensions.kt
@@ -1,6 +1,8 @@
package org.mariotaku.twidere.extension
import android.graphics.BitmapFactory
+import kotlin.math.max
+import kotlin.math.roundToInt
fun BitmapFactory.Options.calculateInSampleSize(preferredWidth: Int, preferredHeight: Int): Int {
if (preferredHeight > outHeight && preferredWidth > outWidth) {
@@ -9,6 +11,7 @@ fun BitmapFactory.Options.calculateInSampleSize(preferredWidth: Int, preferredHe
if (preferredHeight <= 0 && preferredWidth <= 0) {
return 1
}
- val result = Math.round(Math.max(outWidth, outHeight) / Math.max(preferredWidth, preferredHeight).toFloat())
- return Math.max(1, result)
+ val result = (max(outWidth, outHeight) / max(preferredWidth, preferredHeight)
+ .toFloat()).roundToInt()
+ return max(1, result)
}
\ No newline at end of file
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/GlideExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/GlideExtensions.kt
index 7bff836d4e..5b196dc7b1 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/GlideExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/GlideExtensions.kt
@@ -114,20 +114,20 @@ fun RequestManager.loadProfileImage(context: Context, conversation: ParcelableMe
size: String? = null): RequestBuilder<*> {
if (conversation.conversation_type == ParcelableMessageConversation.ConversationType.ONE_TO_ONE) {
val user = conversation.user
- if (user != null) {
- return loadProfileImage(context, user, shapeStyle, cornerRadius, cornerRadiusRatio, size)
+ return if (user != null) {
+ loadProfileImage(context, user, shapeStyle, cornerRadius, cornerRadiusRatio, size)
} else {
// TODO: show default conversation icon
- return loadProfileImage(context, R.drawable.ic_profile_image_default_group, shapeStyle,
- cornerRadius, cornerRadiusRatio)
+ loadProfileImage(context, R.drawable.ic_profile_image_default_group, shapeStyle,
+ cornerRadius, cornerRadiusRatio)
}
} else {
- if (conversation.conversation_avatar != null) {
- return loadProfileImage(context, conversation.conversation_avatar, shapeStyle, cornerRadius,
- cornerRadiusRatio, size)
+ return if (conversation.conversation_avatar != null) {
+ loadProfileImage(context, conversation.conversation_avatar, shapeStyle, cornerRadius,
+ cornerRadiusRatio, size)
} else {
- return loadProfileImage(context, R.drawable.ic_profile_image_default_group, shapeStyle,
- cornerRadius, cornerRadiusRatio)
+ loadProfileImage(context, R.drawable.ic_profile_image_default_group, shapeStyle,
+ cornerRadius, cornerRadiusRatio)
}
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/ListViewExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/ListViewExtensions.kt
index 5ee7ef73c3..548671054c 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/ListViewExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/ListViewExtensions.kt
@@ -30,5 +30,5 @@ fun ListView.updateSelectionItems(menu: Menu) {
val listCount = count
menu.setItemAvailability(R.id.select_none, checkedCount > 0)
menu.setItemAvailability(R.id.select_all, checkedCount < listCount)
- menu.setItemAvailability(R.id.invert_selection, checkedCount > 0 && checkedCount < listCount)
+ menu.setItemAvailability(R.id.invert_selection, checkedCount in 1 until listCount)
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/RectExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/RectExtensions.kt
index d9e0f6b186..72882d5902 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/RectExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/RectExtensions.kt
@@ -62,17 +62,17 @@ fun Rect.offsetEndTo(x: Int, layoutDirection: Int) {
}
fun Rect.getStart(layoutDirection: Int): Int {
- if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL) {
- return this.right
+ return if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL) {
+ this.right
} else {
- return this.left
+ this.left
}
}
fun Rect.getEnd(layoutDirection: Int): Int {
- if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL) {
- return this.left
+ return if (layoutDirection == ViewCompat.LAYOUT_DIRECTION_RTL) {
+ this.left
} else {
- return this.right
+ this.right
}
}
\ No newline at end of file
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/ViewExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/ViewExtensions.kt
index a6e15aec0b..f7d42fefe4 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/ViewExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/ViewExtensions.kt
@@ -43,15 +43,19 @@ fun View.getFrame(rect: Rect) {
@UiThread
fun View.getFrameRelatedTo(rect: Rect, other: View? = null) {
this.getFrame(rect)
- if (other == null) {
- offsetToRoot(this, rect)
- } else if (other === this) {
- rect.offsetTo(0, 0)
- } else if (other !== parent) {
- offsetToRoot(this, rect)
- other.getFrame(tempRect)
- offsetToRoot(other, tempRect)
- rect.offset(-tempRect.left, -tempRect.top)
+ when {
+ other == null -> {
+ offsetToRoot(this, rect)
+ }
+ other === this -> {
+ rect.offsetTo(0, 0)
+ }
+ other !== parent -> {
+ offsetToRoot(this, rect)
+ other.getFrame(tempRect)
+ offsetToRoot(other, tempRect)
+ rect.offset(-tempRect.left, -tempRect.top)
+ }
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/mime4j/ContentTypeFieldExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/mime4j/ContentTypeFieldExtensions.kt
index b8db4482b2..d45fb1c01e 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/mime4j/ContentTypeFieldExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/mime4j/ContentTypeFieldExtensions.kt
@@ -30,5 +30,5 @@ fun ContentTypeField.getIntParameter(name: String, def: Int): Int {
}
fun ContentTypeField.getBooleanParameter(name: String): Boolean {
- return getParameter(name).toBoolean()
+ return this.getParameter(name)!!.toBoolean()
}
\ No newline at end of file
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/AccountDetailsExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/AccountDetailsExtensions.kt
index d7e20320cb..bf9a672c3a 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/AccountDetailsExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/AccountDetailsExtensions.kt
@@ -15,6 +15,7 @@ import org.mariotaku.twidere.util.InternalTwitterContentUtils
import org.mariotaku.twidere.util.text.FanfouValidator
import org.mariotaku.twidere.util.text.MastodonValidator
import org.mariotaku.twidere.util.text.TwitterValidator
+import kotlin.math.min
fun AccountDetails.isOfficial(context: Context?): Boolean {
if (context == null) {
@@ -115,10 +116,10 @@ val Array.textLimit: Int
forEach { details ->
val currentLimit = details.textLimit
if (currentLimit != 0) {
- if (limit <= 0) {
- limit = currentLimit
+ limit = if (limit <= 0) {
+ currentLimit
} else {
- limit = Math.min(limit, currentLimit)
+ min(limit, currentLimit)
}
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/AccountExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/AccountExtensions.kt
index 930b3e1287..0f641ec9ba 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/AccountExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/AccountExtensions.kt
@@ -38,7 +38,7 @@ fun Account.getCredentials(am: AccountManager): Credentials {
if (token != null) return@run token
}
return@run null
- } ?: throw NullPointerException("AuthToken is null for ${this}")
+ } ?: throw NullPointerException("AuthToken is null for $this")
return parseCredentials(authToken, getCredentialsType(am))
}
@@ -175,10 +175,10 @@ internal object AccountDataQueue {
return callable.call()
}
val future = executor.submit(callable)
- try {
- return future.get(1, TimeUnit.SECONDS)
+ return try {
+ future.get(1, TimeUnit.SECONDS)
} catch (e: TimeoutException) {
- return manager.getUserData(account, key)
+ manager.getUserData(account, key)
}
}
@@ -190,10 +190,10 @@ internal object AccountDataQueue {
return callable.call()
}
val future = executor.submit(callable)
- try {
- return future.get(1, TimeUnit.SECONDS)
+ return try {
+ future.get(1, TimeUnit.SECONDS)
} catch (e: TimeoutException) {
- return manager.peekAuthToken(account, authTokenType)
+ manager.peekAuthToken(account, authTokenType)
}
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/CredentialsExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/CredentialsExtensions.kt
index e73fbeb1aa..786a0a5744 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/CredentialsExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/CredentialsExtensions.kt
@@ -63,12 +63,11 @@ fun Credentials.getAuthorization(cls: Class<*>?): Authorization {
}
fun Credentials.getEndpoint(cls: Class<*>): Endpoint {
- val apiUrlFormat: String
val noVersionSuffix = this.no_version_suffix
- if (!TextUtils.isEmpty(this.api_url_format)) {
- apiUrlFormat = this.api_url_format
+ val apiUrlFormat: String = if (!TextUtils.isEmpty(this.api_url_format)) {
+ this.api_url_format
} else {
- apiUrlFormat = DEFAULT_TWITTER_API_URL_FORMAT
+ DEFAULT_TWITTER_API_URL_FORMAT
}
val domain: String?
val versionSuffix: String?
@@ -113,11 +112,10 @@ fun Credentials.getEndpoint(cls: Class<*>): Endpoint {
}
val endpointUrl = MicroBlogAPIFactory.getApiUrl(apiUrlFormat, domain, versionSuffix)
if (this is OAuthCredentials) {
- val signEndpointUrl: String
- if (same_oauth_signing_url) {
- signEndpointUrl = endpointUrl
+ val signEndpointUrl: String = if (same_oauth_signing_url) {
+ endpointUrl
} else {
- signEndpointUrl = MicroBlogAPIFactory.getApiUrl(DEFAULT_TWITTER_API_URL_FORMAT, domain, versionSuffix)
+ MicroBlogAPIFactory.getApiUrl(DEFAULT_TWITTER_API_URL_FORMAT, domain, versionSuffix)
}
return OAuthEndpoint(endpointUrl, signEndpointUrl)
}
@@ -180,11 +178,11 @@ internal fun Credentials.authorizationHeader(
): String {
val auth = getAuthorization(cls)
val endpoint: Endpoint
- if (auth is OAuthAuthorization) {
- endpoint = OAuthEndpoint(TwidereMediaDownloader.getEndpoint(modifiedUri),
- TwidereMediaDownloader.getEndpoint(uri))
+ endpoint = if (auth is OAuthAuthorization) {
+ OAuthEndpoint(TwidereMediaDownloader.getEndpoint(modifiedUri),
+ TwidereMediaDownloader.getEndpoint(uri))
} else {
- endpoint = Endpoint(TwidereMediaDownloader.getEndpoint(modifiedUri))
+ Endpoint(TwidereMediaDownloader.getEndpoint(modifiedUri))
}
val queries = MultiValueMap()
for (name in uri.queryParameterNames) {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/DraftExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/DraftExtensions.kt
index db37561152..792215e294 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/DraftExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/DraftExtensions.kt
@@ -122,23 +122,23 @@ fun Draft.readMimeMessageFrom(context: Context, st: InputStream): Boolean {
fun Draft.getActionName(context: Context): String? {
if (TextUtils.isEmpty(action_type)) return context.getString(R.string.update_status)
when (action_type) {
- Draft.Action.UPDATE_STATUS, Draft.Action.UPDATE_STATUS_COMPAT_1,
- Draft.Action.UPDATE_STATUS_COMPAT_2 -> {
+ Action.UPDATE_STATUS, Action.UPDATE_STATUS_COMPAT_1,
+ Action.UPDATE_STATUS_COMPAT_2 -> {
return context.getString(R.string.update_status)
}
- Draft.Action.REPLY -> {
+ Action.REPLY -> {
return context.getString(R.string.action_reply)
}
- Draft.Action.QUOTE -> {
+ Action.QUOTE -> {
return context.getString(R.string.action_quote)
}
- Draft.Action.FAVORITE -> {
+ Action.FAVORITE -> {
return context.getString(R.string.action_favorite)
}
- Draft.Action.RETWEET -> {
+ Action.RETWEET -> {
return context.getString(R.string.action_retweet)
}
- Draft.Action.SEND_DIRECT_MESSAGE, Draft.Action.SEND_DIRECT_MESSAGE_COMPAT -> {
+ Action.SEND_DIRECT_MESSAGE, Action.SEND_DIRECT_MESSAGE_COMPAT -> {
return context.getString(R.string.send_direct_message)
}
}
@@ -157,8 +157,8 @@ fun Draft.applyUpdateStatus(statusUpdate: ParcelableStatusUpdate) {
fun draftActionTypeString(@Draft.Action action: String?): String {
return when (action) {
- Draft.Action.QUOTE -> "quote"
- Draft.Action.REPLY -> "reply"
+ Action.QUOTE -> "quote"
+ Action.REPLY -> "reply"
else -> "tweet"
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/LaunchPresentationExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/LaunchPresentationExtensions.kt
index 1f4a204eeb..f3aa04b6ca 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/LaunchPresentationExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/LaunchPresentationExtensions.kt
@@ -24,6 +24,8 @@ import androidx.core.os.LocaleListCompat
import org.mariotaku.ktextension.localesCompat
import org.mariotaku.twidere.model.presentation.LaunchPresentation
import java.util.*
+import kotlin.math.abs
+import kotlin.math.roundToInt
fun LaunchPresentation.shouldShow(context: Context): Boolean {
// Check language
@@ -69,16 +71,16 @@ fun LaunchPresentation.Image.displayingScore(viewDensity: Float, viewWidth: Int,
viewWidth < width && viewHeight < height -> {
val diffW = (width / viewWidth.toFloat() - 1).coerceAtMost(0.5f)
val diffH = (height / viewHeight.toFloat() - 1).coerceAtMost(0.5f)
- 100 - Math.round(diffH * 100) - Math.round(diffW * 100)
+ 100 - (diffH * 100).roundToInt() - (diffW * 100).roundToInt()
}
else -> {
val diffW = (width / viewWidth.toFloat() - 1).coerceAtMost(0.5f)
val diffH = (height / viewHeight.toFloat() - 1).coerceAtMost(0.5f)
- 100 - Math.round(diffH * 50) - Math.round(diffW * 50)
+ 100 - (diffH * 50).roundToInt() - (diffW * 50).roundToInt()
}
}
if (this.density != 0f) {
- score += 100 - Math.round(Math.abs(this.density / viewDensity - 1).coerceAtMost(1f))
+ score += 100 - abs(this.density / viewDensity - 1).coerceAtMost(1f).roundToInt()
}
return score
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableCardEntityExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableCardEntityExtensions.kt
index e4b26e71d3..0e022fb52e 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableCardEntityExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableCardEntityExtensions.kt
@@ -46,7 +46,7 @@ fun CardEntity.toParcelable(accountKey: UserKey, accountType: String): Parcelabl
fun ParcelableCardEntity.getAsBoolean(key: String, def: Boolean): Boolean {
val value = getValue(key) ?: return def
- return value.value.toBoolean()
+ return value.value!!.toBoolean()
}
fun ParcelableCardEntity.getAsString(key: String, def: String?): String? {
@@ -71,9 +71,9 @@ fun ParcelableCardEntity.getAsLong(key: String, def: Long): Long {
fun ParcelableCardEntity.getAsDate(key: String, def: Date): Date {
val value = getValue(key) ?: return def
- try {
- return ParcelableCardEntityUtils.sISOFormat.parse(value.value)
+ return try {
+ ParcelableCardEntityUtils.sISOFormat.parse(value.value)
} catch (e: ParseException) {
- return def
+ def
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableMediaExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableMediaExtensions.kt
index 47bf150ce2..5d9c930729 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableMediaExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableMediaExtensions.kt
@@ -27,7 +27,7 @@ fun ParcelableMedia.getBestVideoUrlAndType(supportedTypes: Array): Pair<
val videoInfo = video_info ?: return Pair(mediaUrl, null)
val firstMatch = videoInfo.variants.filter { variant ->
supportedTypes.any { it.equals(variant.content_type, ignoreCase = true) }
- }.sortedByDescending(ParcelableMedia.VideoInfo.Variant::bitrate).firstOrNull() ?: return null
+ }.maxBy(ParcelableMedia.VideoInfo.Variant::bitrate) ?: return null
return Pair(firstMatch.url, firstMatch.content_type)
}
ParcelableMedia.Type.CARD_ANIMATED_GIF -> {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableMediaUpdateExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableMediaUpdateExtensions.kt
index 4c9d4627c2..6ebb887afb 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableMediaUpdateExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableMediaUpdateExtensions.kt
@@ -12,16 +12,16 @@ import org.mariotaku.twidere.util.BitmapFactoryUtils
*/
fun ParcelableMediaUpdate.getMimeType(resolver: ContentResolver): String? {
val uri = Uri.parse(this.uri)
- return resolver.getType(uri) ?: when (type) {
+ return resolver.getType(uri) ?: return when (type) {
ParcelableMedia.Type.ANIMATED_GIF -> {
- return "image/gif"
+ "image/gif"
}
ParcelableMedia.Type.IMAGE -> {
val o = BitmapFactory.Options()
o.inJustDecodeBounds = true
BitmapFactoryUtils.decodeUri(resolver, uri, opts = o)
- return o.outMimeType
+ o.outMimeType
}
- else -> return null
+ else -> null
}
}
\ No newline at end of file
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableMessageConversationExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableMessageConversationExtensions.kt
index 362d6ee7e5..6e2fd2ae7f 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableMessageConversationExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableMessageConversationExtensions.kt
@@ -53,12 +53,12 @@ val ParcelableMessageConversation.readOnly: Boolean
var ParcelableMessageConversation.notificationDisabled: Boolean
get() {
- when (conversation_extras_type) {
+ return when (conversation_extras_type) {
ExtrasType.TWITTER_OFFICIAL -> {
- return (conversation_extras as? TwitterOfficialConversationExtras)?.notificationsDisabled ?: false
+ (conversation_extras as? TwitterOfficialConversationExtras)?.notificationsDisabled ?: false
}
else -> {
- return (conversation_extras as? DefaultConversationExtras)?.notificationsDisabled ?: false
+ (conversation_extras as? DefaultConversationExtras)?.notificationsDisabled ?: false
}
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableMessageExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableMessageExtensions.kt
index e954c023dd..98626a16c8 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableMessageExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableMessageExtensions.kt
@@ -46,42 +46,42 @@ internal fun getSummaryText(context: Context, manager: UserColorNameManager, nam
} else {
res.getQuantityString(R.plurals.N_users, users.size, users.size)
}
- if (sender != null) {
- return res.getString(R.string.message_format_participants_join_added,
- manager.getDisplayName(sender, nameFirst), joinName)
+ return if (sender != null) {
+ res.getString(R.string.message_format_participants_join_added,
+ manager.getDisplayName(sender, nameFirst), joinName)
} else {
- return res.getString(R.string.message_format_participants_join, joinName)
+ res.getString(R.string.message_format_participants_join, joinName)
}
}
MessageType.PARTICIPANTS_LEAVE -> {
val users = (extras as UserArrayExtras).users
val res = context.resources
- if (users.size == 1) {
+ return if (users.size == 1) {
val displayName = manager.getDisplayName(users[0], nameFirst)
- return res.getString(R.string.message_format_participants_leave, displayName)
+ res.getString(R.string.message_format_participants_leave, displayName)
} else {
val usersName = res.getQuantityString(R.plurals.N_users, users.size, users.size)
- return res.getString(R.string.message_format_participants_leave, usersName)
+ res.getString(R.string.message_format_participants_leave, usersName)
}
}
MessageType.CONVERSATION_NAME_UPDATE -> {
extras as ConversationInfoUpdatedExtras
val res = context.resources
- if (extras.user != null) {
- return res.getString(R.string.message_format_conversation_name_update_by_user,
- manager.getDisplayName(extras.user, nameFirst), extras.name)
+ return if (extras.user != null) {
+ res.getString(R.string.message_format_conversation_name_update_by_user,
+ manager.getDisplayName(extras.user, nameFirst), extras.name)
} else {
- return res.getString(R.string.message_format_conversation_name_update, extras.name)
+ res.getString(R.string.message_format_conversation_name_update, extras.name)
}
}
MessageType.CONVERSATION_AVATAR_UPDATE -> {
extras as ConversationInfoUpdatedExtras
val res = context.resources
- if (extras.user != null) {
- return res.getString(R.string.message_format_conversation_avatar_update_by_user,
- manager.getDisplayName(extras.user, nameFirst))
+ return if (extras.user != null) {
+ res.getString(R.string.message_format_conversation_avatar_update_by_user,
+ manager.getDisplayName(extras.user, nameFirst))
} else {
- return res.getString(R.string.message_format_conversation_avatar_update)
+ res.getString(R.string.message_format_conversation_avatar_update)
}
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableUserMentionExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableUserMentionExtensions.kt
index 5849d7ecf4..af5ac2b37e 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableUserMentionExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/ParcelableUserMentionExtensions.kt
@@ -26,9 +26,9 @@ import org.mariotaku.twidere.model.UserKey
* Created by mariotaku on 2017/4/23.
*/
fun ParcelableUserMention.getAcct(accountKey: UserKey): String {
- if (accountKey.host == key.host) {
- return screen_name
+ return if (accountKey.host == key.host) {
+ screen_name
} else {
- return "$screen_name@${key.host}"
+ "$screen_name@${key.host}"
}
}
\ No newline at end of file
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/api/StatusExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/api/StatusExtensions.kt
index 768b2f2edc..d16def41d4 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/api/StatusExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/api/StatusExtensions.kt
@@ -46,6 +46,7 @@ import org.mariotaku.twidere.util.HtmlSpanBuilder
import org.mariotaku.twidere.util.InternalTwitterContentUtils
import org.mariotaku.twidere.util.InternalTwitterContentUtils.getMediaUrl
import org.mariotaku.twidere.util.InternalTwitterContentUtils.getStartEndForEntity
+import kotlin.math.max
fun Status.toParcelable(details: AccountDetails, profileImageSize: String = "normal",
updateFilterInfoAction: (Status, ParcelableStatus) -> Unit = ::updateFilterInfoDefault): ParcelableStatus {
@@ -71,6 +72,13 @@ fun Status.applyTo(accountKey: UserKey, accountType: String, profileImageSize: S
result.timestamp = createdAt?.time ?: 0
extras.external_url = inferredExternalUrl
+ extras.entities_url = entities?.urls?.map { it.expandedUrl }?.let {
+ if (isQuoteStatus) {
+ it.take(max(0, it.count() - 1))
+ } else {
+ it
+ }
+ }?.toTypedArray()
extras.support_entities = entities != null
extras.statusnet_conversation_id = statusnetConversationId
extras.conversation_id = conversationId
@@ -212,7 +220,11 @@ fun Status.applyTo(accountKey: UserKey, accountType: String, profileImageSize: S
fun Status.formattedTextWithIndices(): StatusTextWithIndices {
val source = CodePointArray(this.fullText ?: this.text!!)
- val builder = HtmlBuilder(source, false, true, false)
+ val builder = HtmlBuilder(source,
+ throwExceptions = false,
+ sourceIsEscaped = true,
+ shouldReEscape = false
+ )
builder.addEntities(this)
val textWithIndices = StatusTextWithIndices()
val (text, spans) = builder.buildWithIndices()
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/api/gnusocial/AttathmentExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/api/gnusocial/AttathmentExtensions.kt
index cd02de5ddb..2758d2a651 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/api/gnusocial/AttathmentExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/api/gnusocial/AttathmentExtensions.kt
@@ -29,14 +29,18 @@ fun Attachment.toParcelable(externalUrl: String?) : ParcelableMedia? {
val mimeType = mimetype ?: return null
val result = ParcelableMedia()
- if (mimeType.startsWith("image/")) {
- result.type = ParcelableMedia.Type.IMAGE
- } else if (mimeType.startsWith("video/")) {
- result.type = ParcelableMedia.Type.VIDEO
- } else {
- // https://github.com/TwidereProject/Twidere-Android/issues/729
- // Skip unsupported attachment
- return null
+ when {
+ mimeType.startsWith("image/") -> {
+ result.type = ParcelableMedia.Type.IMAGE
+ }
+ mimeType.startsWith("video/") -> {
+ result.type = ParcelableMedia.Type.VIDEO
+ }
+ else -> {
+ // https://github.com/TwidereProject/Twidere-Android/issues/729
+ // Skip unsupported attachment
+ return null
+ }
}
result.width = width
result.height = height
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/api/mastodon/AttachmentExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/api/mastodon/AttachmentExtensions.kt
index 4d8b5a8422..1390e82d8b 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/api/mastodon/AttachmentExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/model/api/mastodon/AttachmentExtensions.kt
@@ -38,6 +38,8 @@ fun Attachment.toParcelable(): ParcelableMedia {
"gifv" -> ParcelableMedia.Type.ANIMATED_GIF
else -> ParcelableMedia.Type.UNKNOWN
}
+ result.height = meta?.original?.height?.toInt() ?: 0
+ result.width = meta?.original?.width?.toInt() ?: 0
result.url = url ?: remoteUrl
result.media_url = result.url
result.preview_url = previewUrl
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/text/twitter/ExtractorExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/text/twitter/ExtractorExtensions.kt
index abc41c876e..47c1420d2c 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/text/twitter/ExtractorExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/text/twitter/ExtractorExtensions.kt
@@ -33,9 +33,9 @@ fun Extractor.extractMentionsAndNonMentionStartIndex(text: String, mentions: Arr
if (entity.start != nextExpectedPos) break
// Break at first mention not found in `inReplyTo.mentions`
if (mentions?.none { entity.value.equals(it.screen_name, ignoreCase = true) } == true) break
- nextExpectedPos = (entity.end..text.indices.endInclusive).firstOrNull {
+ nextExpectedPos = (entity.end..text.indices.last).firstOrNull {
!text[it].isWhitespace()
- } ?: text.indices.endInclusive + 1
+ } ?: text.indices.last + 1
}
return MentionsAndNonMentionStartIndex(entities, nextExpectedPos)
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/view/RecyclerViewExtensions.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/view/RecyclerViewExtensions.kt
index 934feef9e6..091abe5738 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/extension/view/RecyclerViewExtensions.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/extension/view/RecyclerViewExtensions.kt
@@ -22,6 +22,7 @@ package org.mariotaku.twidere.extension.view
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import androidx.recyclerview.widget.recyclerView
+import kotlin.math.max
fun RecyclerView.LayoutManager.calculateSpaceItemHeight(child: View, spaceViewType: Int, typeStart: Int): Int {
val recyclerView = recyclerView ?: return 0
@@ -39,7 +40,7 @@ fun RecyclerView.LayoutManager.calculateSpaceItemHeight(child: View, spaceViewTy
if (heightBeforeSpace != 0) {
val spaceHeight = recyclerView.measuredHeight - recyclerView.paddingTop -
recyclerView.paddingBottom - heightBeforeSpace
- return Math.max(0, spaceHeight)
+ return max(0, spaceHeight)
}
return -1
}
\ No newline at end of file
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/APIEditorDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/APIEditorDialogFragment.kt
index 2a9132c743..4efcfdfb77 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/APIEditorDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/APIEditorDialogFragment.kt
@@ -10,7 +10,6 @@ import androidx.appcompat.app.AlertDialog
import android.view.View
import android.view.ViewGroup
import android.widget.*
-import com.bumptech.glide.Glide
import com.rengwuxian.materialedittext.MaterialEditText
import org.mariotaku.twidere.R
import org.mariotaku.twidere.adapter.ArrayAdapter
@@ -43,20 +42,25 @@ class APIEditorDialogFragment : BaseDialogFragment() {
private lateinit var apiConfig: CustomAPIConfig
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setView(R.layout.dialog_api_editor)
builder.setPositiveButton(R.string.action_save) { _, _ ->
val targetFragment = this.targetFragment
val parentFragment = this.parentFragment
val host = this.host
- if (targetFragment is APIEditorCallback) {
- targetFragment.onSaveAPIConfig(applyCustomAPIConfig())
- } else if (parentFragment is APIEditorCallback) {
- parentFragment.onSaveAPIConfig(applyCustomAPIConfig())
- } else if (host is APIEditorCallback) {
- host.onSaveAPIConfig(applyCustomAPIConfig())
- } else {
- kPreferences[defaultAPIConfigKey] = applyCustomAPIConfig()
+ when {
+ targetFragment is APIEditorCallback -> {
+ targetFragment.onSaveAPIConfig(applyCustomAPIConfig())
+ }
+ parentFragment is APIEditorCallback -> {
+ parentFragment.onSaveAPIConfig(applyCustomAPIConfig())
+ }
+ host is APIEditorCallback -> {
+ host.onSaveAPIConfig(applyCustomAPIConfig())
+ }
+ else -> {
+ kPreferences[defaultAPIConfigKey] = applyCustomAPIConfig()
+ }
}
}
builder.setNegativeButton(android.R.string.cancel, null)
@@ -76,8 +80,8 @@ class APIEditorDialogFragment : BaseDialogFragment() {
accountTypeSpinner.adapter = AccountTypeSpinnerAdapter(this)
- editConsumerKey.addValidator(ConsumerKeySecretValidator(context!!.getString(R.string.invalid_consumer_key)))
- editConsumerSecret.addValidator(ConsumerKeySecretValidator(context!!.getString(R.string.invalid_consumer_secret)))
+ editConsumerKey.addValidator(ConsumerKeySecretValidator(requireContext().getString(R.string.invalid_consumer_key)))
+ editConsumerSecret.addValidator(ConsumerKeySecretValidator(requireContext().getString(R.string.invalid_consumer_secret)))
editNoVersionSuffix.setOnCheckedChangeListener { _, _ -> editNoVersionSuffixChanged = true }
editAuthType.setOnCheckedChangeListener { _, checkedId ->
@@ -95,10 +99,10 @@ class APIEditorDialogFragment : BaseDialogFragment() {
tag = "api_url_format_help")
}
- if (savedInstanceState != null) {
- apiConfig = savedInstanceState.getParcelable(EXTRA_API_CONFIG)!!
+ apiConfig = if (savedInstanceState != null) {
+ savedInstanceState.getParcelable(EXTRA_API_CONFIG)!!
} else {
- apiConfig = arguments?.getParcelable(EXTRA_API_CONFIG) ?: kPreferences[defaultAPIConfigKey]
+ arguments?.getParcelable(EXTRA_API_CONFIG) ?: kPreferences[defaultAPIConfigKey]
}
displayCustomApiConfig()
}
@@ -145,8 +149,8 @@ class APIEditorDialogFragment : BaseDialogFragment() {
private lateinit var adapter: ArrayAdapter
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- adapter = CustomAPIConfigArrayAdapter(context!!)
- val builder = AlertDialog.Builder(context!!)
+ adapter = CustomAPIConfigArrayAdapter(requireContext())
+ val builder = AlertDialog.Builder(requireContext())
builder.setAdapter(adapter, this)
loaderManager.initLoader(0, null, this)
val dialog = builder.create()
@@ -162,7 +166,7 @@ class APIEditorDialogFragment : BaseDialogFragment() {
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader> {
- return DefaultAPIConfigLoader(context!!)
+ return DefaultAPIConfigLoader(requireContext())
}
override fun onLoadFinished(loader: Loader>, data: List) {
@@ -189,7 +193,7 @@ class APIEditorDialogFragment : BaseDialogFragment() {
private class AccountTypeSpinnerAdapter(
fragment: APIEditorDialogFragment
- ) : BaseArrayAdapter(fragment.context!!, R.layout.support_simple_spinner_dropdown_item,
+ ) : BaseArrayAdapter(fragment.requireContext(), R.layout.support_simple_spinner_dropdown_item,
requestManager = fragment.requestManager) {
init {
add(AccountType.TWITTER)
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AbsActivitiesFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AbsActivitiesFragment.kt
index ac0ef27303..551bb68be7 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AbsActivitiesFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AbsActivitiesFragment.kt
@@ -103,8 +103,10 @@ abstract class AbsActivitiesFragment protected constructor() :
registerForContextMenu(recyclerView)
navigationHelper = RecyclerViewNavigationHelper(recyclerView, layoutManager, adapter,
this)
- pauseOnScrollListener = PauseRecyclerViewOnScrollListener(false, false,
- requestManager)
+ pauseOnScrollListener = PauseRecyclerViewOnScrollListener(
+ pauseOnScroll = false, pauseOnFling = false,
+ requestManager = requestManager
+ )
val loaderArgs = Bundle(arguments)
loaderArgs.putBoolean(EXTRA_FROM_USER, true)
@@ -185,7 +187,7 @@ abstract class AbsActivitiesFragment protected constructor() :
override fun onCreateLoader(id: Int, args: Bundle?): Loader> {
val fromUser = args?.getBoolean(EXTRA_FROM_USER)
args?.remove(EXTRA_FROM_USER)
- return onCreateActivitiesLoader(activity!!, args!!, fromUser!!)
+ return onCreateActivitiesLoader(requireActivity(), args!!, fromUser!!)
}
protected fun saveReadPosition() {
@@ -237,7 +239,7 @@ abstract class AbsActivitiesFragment protected constructor() :
adapter.getTimestamp(lastReadPosition)
}
lastReadViewTop = layoutManager.findViewByPosition(lastReadPosition)?.top ?: 0
- loadMore = activityRange.endInclusive in 0..lastVisibleItemPosition
+ loadMore = activityRange.last in 0..lastVisibleItemPosition
} else if (rememberPosition && readPositionTag != null) {
val syncManager = timelineSyncManager
val positionTag = this.readPositionTag
@@ -547,13 +549,13 @@ abstract class AbsActivitiesFragment protected constructor() :
(recyclerView.layoutManager as LinearLayoutManager).orientation) {
override fun isDividerEnabled(childPos: Int): Boolean {
if (childPos >= layoutManager.itemCount || childPos < 0) return false
- when (adapter.getItemViewType(childPos)) {
+ return when (adapter.getItemViewType(childPos)) {
ITEM_VIEW_TYPE_STATUS, ITEM_VIEW_TYPE_TITLE_SUMMARY, ITEM_VIEW_TYPE_GAP,
ITEM_VIEW_TYPE_STUB -> {
- return true
+ true
}
else -> {
- return false
+ false
}
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AbsContentListViewFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AbsContentListViewFragment.kt
index 96e9d0cbaa..45d6ffc1d4 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AbsContentListViewFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AbsContentListViewFragment.kt
@@ -39,6 +39,7 @@ import org.mariotaku.twidere.util.ContentScrollHandler.ContentListSupport
import org.mariotaku.twidere.util.ListViewScrollHandler
import org.mariotaku.twidere.util.ThemeUtils
import org.mariotaku.twidere.util.TwidereColorUtils
+import kotlin.math.roundToInt
/**
* Created by mariotaku on 15/4/16.
@@ -129,12 +130,12 @@ abstract class AbsContentListViewFragment : BaseFragment(),
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
- val backgroundColor = ThemeUtils.getColorBackground(context!!)
+ val backgroundColor = ThemeUtils.getColorBackground(requireContext())
val colorRes = TwidereColorUtils.getContrastYIQ(backgroundColor,
R.color.bg_refresh_progress_color_light, R.color.bg_refresh_progress_color_dark)
swipeLayout.setOnRefreshListener(this)
swipeLayout.setProgressBackgroundColorSchemeResource(colorRes)
- adapter = onCreateAdapter(context!!, requestManager)
+ adapter = onCreateAdapter(requireContext(), requestManager)
listView.setOnTouchListener { _, event ->
if (event.actionMasked == MotionEvent.ACTION_DOWN) {
updateRefreshProgressOffset()
@@ -211,10 +212,11 @@ abstract class AbsContentListViewFragment : BaseFragment(),
}
val density = resources.displayMetrics.density
val progressCircleDiameter = swipeLayout.progressCircleDiameter
- val controlBarOffsetPixels = Math.round(activity.controlBarHeight * (1 - activity.controlBarOffset))
+ val controlBarOffsetPixels =
+ (activity.controlBarHeight * (1 - activity.controlBarOffset)).roundToInt()
val swipeStart = systemWindowsInsets.top - controlBarOffsetPixels - progressCircleDiameter
// 64: SwipeRefreshLayout.DEFAULT_CIRCLE_TARGET
- val swipeDistance = Math.round(64 * density)
+ val swipeDistance = (64 * density).roundToInt()
swipeLayout.setProgressViewOffset(false, swipeStart, swipeStart + swipeDistance)
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AbsContentRecyclerViewFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AbsContentRecyclerViewFragment.kt
index 2da1262b4f..a2d4665352 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AbsContentRecyclerViewFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AbsContentRecyclerViewFragment.kt
@@ -182,13 +182,13 @@ abstract class AbsContentRecyclerViewFragment ?> {
val fromUser = args?.getBoolean(EXTRA_FROM_USER)
args?.remove(EXTRA_FROM_USER)
- return onCreateStatusesLoader(activity!!, args!!, fromUser!!)
+ return onCreateStatusesLoader(requireActivity(), args!!, fromUser!!)
}
final override fun onLoadFinished(loader: Loader?>, data: List?) {
@@ -146,7 +146,7 @@ abstract class AbsMediaStatusesFragment : AbsContentRecyclerViewFragment?> {
val fromUser = args?.getBoolean(EXTRA_FROM_USER)
args?.remove(EXTRA_FROM_USER)
- return onCreateStatusesLoader(activity!!, args!!, fromUser!!)
+ return onCreateStatusesLoader(requireActivity(), args!!, fromUser!!)
}
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
@@ -272,7 +275,7 @@ abstract class AbsStatusesFragment : AbsContentListRecyclerViewFragment {
+ -1
+ }
+ useSortIdAsReadPosition -> {
+ adapter.getStatusSortId(lastReadPosition, false)
+ }
+ else -> {
+ adapter.getStatusPositionKey(lastReadPosition)
+ }
}
lastReadViewTop = layoutManager.findViewByPosition(lastReadPosition)?.top ?: 0
- loadMore = statusRange.endInclusive in 0..lastVisibleItemPosition
+ loadMore = statusRange.last in 0..lastVisibleItemPosition
} else if (rememberPosition) {
val syncManager = timelineSyncManager
val positionTag = this.readPositionTag
@@ -465,6 +472,12 @@ abstract class AbsStatusesFragment : AbsContentListRecyclerViewFragment return MenuUtils.handleStatusClick(activity!!, this, fragmentManager!!,
+ else -> return MenuUtils.handleStatusClick(requireActivity(), this, requireFragmentManager(),
preferences, userColorNameManager, twitterWrapper, status, item)
}
}
@@ -614,15 +627,19 @@ abstract class AbsStatusesFragment : AbsContentListRecyclerViewFragment {
- if (fragment.preferences[favoriteConfirmationKey]) {
- fragment.executeAfterFragmentResumed {
- FavoriteConfirmDialogFragment.show(it.childFragmentManager,
+ when {
+ fragment.preferences[favoriteConfirmationKey] -> {
+ fragment.executeAfterFragmentResumed {
+ FavoriteConfirmDialogFragment.show(it.childFragmentManager,
status.account_key, status.id, status)
+ }
+ }
+ status.is_favorite -> {
+ fragment.twitterWrapper.destroyFavoriteAsync(status.account_key, status.id)
+ }
+ else -> {
+ holder.playLikeAnimation(DefaultOnLikedListener(fragment.twitterWrapper, status))
}
- } else if (status.is_favorite) {
- fragment.twitterWrapper.destroyFavoriteAsync(status.account_key, status.id)
- } else {
- holder.playLikeAnimation(DefaultOnLikedListener(fragment.twitterWrapper, status))
}
}
}
@@ -646,7 +663,7 @@ abstract class AbsStatusesFragment : AbsContentListRecyclerViewFragment {
+ REQUEST_FAVORITE_SELECT_ACCOUNT -> {
if (resultCode != Activity.RESULT_OK || data == null) return
val accountKey = data.getParcelableExtra(EXTRA_ACCOUNT_KEY)!!
val extras = data.getBundleExtra(EXTRA_EXTRAS)!!
@@ -660,7 +677,7 @@ abstract class AbsStatusesFragment : AbsContentListRecyclerViewFragment {
+ REQUEST_RETWEET_SELECT_ACCOUNT -> {
if (resultCode != Activity.RESULT_OK || data == null) return
val accountKey = data.getParcelableExtra(EXTRA_ACCOUNT_KEY)!!
val extras = data.getBundleExtra(EXTRA_EXTRAS)!!
@@ -712,16 +729,20 @@ abstract class AbsStatusesFragment : AbsContentListRecyclerViewFragment {
- if (fragment.preferences[favoriteConfirmationKey]) {
- fragment.executeAfterFragmentResumed {
- FavoriteConfirmDialogFragment.show(it.childFragmentManager,
+ when {
+ fragment.preferences[favoriteConfirmationKey] -> {
+ fragment.executeAfterFragmentResumed {
+ FavoriteConfirmDialogFragment.show(it.childFragmentManager,
status.account_key, status.id, status)
+ }
+ }
+ status.is_favorite -> {
+ fragment.twitterWrapper.destroyFavoriteAsync(status.account_key, status.id)
+ }
+ else -> {
+ val holder = fragment.recyclerView.findViewHolderForLayoutPosition(position) as StatusViewHolder
+ holder.playLikeAnimation(DefaultOnLikedListener(fragment.twitterWrapper, status))
}
- } else if (status.is_favorite) {
- fragment.twitterWrapper.destroyFavoriteAsync(status.account_key, status.id)
- } else {
- val holder = fragment.recyclerView.findViewHolderForLayoutPosition(position) as StatusViewHolder
- holder.playLikeAnimation(DefaultOnLikedListener(fragment.twitterWrapper, status))
}
return true
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AbsToolbarTabPagesFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AbsToolbarTabPagesFragment.kt
index a8d981b074..2baa1577b9 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AbsToolbarTabPagesFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AbsToolbarTabPagesFragment.kt
@@ -47,7 +47,7 @@ abstract class AbsToolbarTabPagesFragment : BaseFragment(), RefreshScrollTopInte
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val activity = activity
- pagerAdapter = SupportTabsAdapter(activity!!, childFragmentManager, null)
+ pagerAdapter = SupportTabsAdapter(requireActivity(), childFragmentManager, null)
viewPager.adapter = pagerAdapter
viewPager.offscreenPageLimit = 2
viewPager.addOnPageChangeListener(this)
@@ -149,7 +149,7 @@ abstract class AbsToolbarTabPagesFragment : BaseFragment(), RefreshScrollTopInte
if (height != 0) {
insets.top = height
} else {
- insets.top = ThemeUtils.getActionBarHeight(context!!)
+ insets.top = ThemeUtils.getActionBarHeight(requireContext())
}
return true
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AbsUserMuteBlockDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AbsUserMuteBlockDialogFragment.kt
index ad7a2550e1..313347bc09 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AbsUserMuteBlockDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AbsUserMuteBlockDialogFragment.kt
@@ -48,7 +48,7 @@ abstract class AbsUserMuteBlockDialogFragment : BaseDialogFragment(), DialogInte
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setTitle(getTitle(user))
builder.setView(R.layout.dialog_block_mute_filter_user_confirm)
builder.setPositiveButton(getPositiveButtonTitle(user), this)
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AccountsDashboardFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AccountsDashboardFragment.kt
index 5d97ab4ed9..42b1e12c6e 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AccountsDashboardFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AccountsDashboardFragment.kt
@@ -46,7 +46,6 @@ import androidx.appcompat.view.SupportMenuInflater
import androidx.appcompat.widget.ActionMenuView.OnMenuItemClickListener
import androidx.core.content.ContextCompat
import androidx.core.view.MenuItemCompat
-import androidx.core.view.isVisible
import androidx.loader.app.LoaderManager.LoaderCallbacks
import androidx.loader.content.FixedAsyncTaskLoader
import androidx.loader.content.Loader
@@ -259,7 +258,7 @@ class AccountsDashboardFragment : BaseFragment(), LoaderCallbacks,
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader {
- return AccountsInfoLoader(activity!!, accountsAdapter.accounts == null)
+ return AccountsInfoLoader(requireActivity(), accountsAdapter.accounts == null)
}
@@ -533,15 +532,19 @@ class AccountsDashboardFragment : BaseFragment(), LoaderCallbacks,
val width = if (bannerWidth > 0) bannerWidth else defWidth
val bannerView = accountProfileBanner.nextView as ImageView
val user = account.user
- val fallbackBanner = if (user.link_color != 0) {
- ColorDrawable(user.link_color)
- } else if (user.account_color != 0) {
- ColorDrawable(user.account_color)
- } else {
- ColorDrawable(Chameleon.getOverrideTheme(activity!!, activity).colorPrimary)
+ val fallbackBanner = when {
+ user.link_color != 0 -> {
+ ColorDrawable(user.link_color)
+ }
+ user.account_color != 0 -> {
+ ColorDrawable(user.account_color)
+ }
+ else -> {
+ ColorDrawable(Chameleon.getOverrideTheme(requireActivity(), activity).colorPrimary)
+ }
}
- requestManager.loadProfileBanner(context!!, account.user, width).fallback(fallbackBanner)
+ requestManager.loadProfileBanner(requireContext(), account.user, width).fallback(fallbackBanner)
.into(bannerView)
}
@@ -552,12 +555,12 @@ class AccountsDashboardFragment : BaseFragment(), LoaderCallbacks,
val showType = accountsAdapter.accounts?.groupBy { it.type }?.count()?.let {
it > 1
} ?: false
- accountProfileScreenNameView.spannable = if (account.type == AccountType.MASTODON) {
+ accountProfileScreenNameView.spannable = if (account.type == AccountType.MASTODON || account.type == AccountType.STATUSNET) {
account.account.name
} else {
"${if (showType) account.type else ""}@${account.user.screen_name}"
}
- requestManager.loadProfileImage(context!!, account, preferences[profileImageStyleKey],
+ requestManager.loadProfileImage(requireContext(), account, preferences[profileImageStyleKey],
accountProfileImageView.cornerRadius, accountProfileImageView.cornerRadiusRatio,
ProfileImageSize.REASONABLY_SMALL).placeholder(profileImageSnapshot).into(accountProfileImageView)
//TODO complete border color
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AccountsManagerFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AccountsManagerFragment.kt
index ab35857b5f..b87fe9f650 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AccountsManagerFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/AccountsManagerFragment.kt
@@ -60,7 +60,7 @@ class AccountsManagerFragment : BaseFragment(), LoaderManager.LoaderCallbacks
@@ -158,7 +158,7 @@ class AccountsManagerFragment : BaseFragment(), LoaderManager.LoaderCallbacks > {
- return AccountDetailsLoader(context!!)
+ return AccountDetailsLoader(requireContext())
}
override fun onLoaderReset(loader: Loader>) {
@@ -227,7 +227,7 @@ class AccountsManagerFragment : BaseFragment(), LoaderManager.LoaderCallbacks? = null
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
filterItems = filterItemsInfo
val entries = arrayOfNulls(filterItems!!.size)
val nameFirst = preferences[nameFirstKey]
- for (i in 0 until entries.size) {
+ for (i in entries.indices) {
val info = filterItems!![i]
when (info.type) {
FilterItemInfo.FILTER_TYPE_USER -> {
@@ -87,24 +87,29 @@ class AddStatusFilterDialogFragment : BaseDialogFragment() {
}
val info = filterItems!![checkPositions.keyAt(i)]
val value = info.value
- if (value is ParcelableUserMention) {
- userKeys.add(value.key)
- userValues.add(ContentValuesCreator.createFilteredUser(value))
- } else if (value is UserItem) {
- userKeys.add(value.key)
- userValues.add(createFilteredUser(value))
- } else if (info.type == FilterItemInfo.FILTER_TYPE_KEYWORD) {
- val keyword = ParseUtils.parseString(value)
- keywords.add(keyword)
- val values = ContentValues()
- values.put(Filters.Keywords.VALUE, "#$keyword")
- keywordValues.add(values)
- } else if (info.type == FilterItemInfo.FILTER_TYPE_SOURCE) {
- val source = ParseUtils.parseString(value)
- sources.add(source)
- val values = ContentValues()
- values.put(Filters.Sources.VALUE, source)
- sourceValues.add(values)
+ when {
+ value is ParcelableUserMention -> {
+ userKeys.add(value.key)
+ userValues.add(ContentValuesCreator.createFilteredUser(value))
+ }
+ value is UserItem -> {
+ userKeys.add(value.key)
+ userValues.add(createFilteredUser(value))
+ }
+ info.type == FilterItemInfo.FILTER_TYPE_KEYWORD -> {
+ val keyword = ParseUtils.parseString(value)
+ keywords.add(keyword)
+ val values = ContentValues()
+ values.put(Filters.Keywords.VALUE, "#$keyword")
+ keywordValues.add(values)
+ }
+ info.type == FilterItemInfo.FILTER_TYPE_SOURCE -> {
+ val source = ParseUtils.parseString(value)
+ sources.add(source)
+ val values = ContentValues()
+ values.put(Filters.Sources.VALUE, source)
+ sourceValues.add(values)
+ }
}
}
context?.contentResolver?.let { resolver ->
@@ -164,12 +169,15 @@ class AddStatusFilterDialogFragment : BaseDialogFragment() {
}
private fun getName(manager: UserColorNameManager, value: Any, nameFirst: Boolean): String {
- if (value is ParcelableUserMention) {
- return manager.getDisplayName(value.key, value.name, value.screen_name, nameFirst)
- } else if (value is UserItem) {
- return manager.getDisplayName(value.key, value.name, value.screen_name, nameFirst)
- } else
- return ParseUtils.parseString(value)
+ return when (value) {
+ is ParcelableUserMention -> {
+ manager.getDisplayName(value.key, value.name, value.screen_name, nameFirst)
+ }
+ is UserItem -> {
+ manager.getDisplayName(value.key, value.name, value.screen_name, nameFirst)
+ }
+ else -> ParseUtils.parseString(value)
+ }
}
internal data class FilterItemInfo(
@@ -194,7 +202,7 @@ class AddStatusFilterDialogFragment : BaseDialogFragment() {
companion object {
- val FRAGMENT_TAG = "add_status_filter"
+ const val FRAGMENT_TAG = "add_status_filter"
private fun createFilteredUser(item: UserItem): ContentValues {
val values = ContentValues()
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/BaseDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/BaseDialogFragment.kt
index 14a33c6e9a..7e4276452a 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/BaseDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/BaseDialogFragment.kt
@@ -30,7 +30,6 @@ import okhttp3.Dns
import org.mariotaku.kpreferences.KPreferences
import org.mariotaku.restfu.http.RestHttpClient
import org.mariotaku.twidere.util.AsyncTwitterWrapper
-import org.mariotaku.twidere.util.DebugModeUtils
import org.mariotaku.twidere.util.KeyboardShortcutsHandler
import org.mariotaku.twidere.util.UserColorNameManager
import org.mariotaku.twidere.util.dagger.GeneralComponent
@@ -63,7 +62,7 @@ open class BaseDialogFragment : DialogFragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
- requestManager = Glide.with(context!!)// TODO: Upgrade Glide usage
+ requestManager = Glide.with(requireContext())// TODO: Upgrade Glide usage
}
override fun onStart() {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/BaseFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/BaseFragment.kt
index dd2930912a..06953601ed 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/BaseFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/BaseFragment.kt
@@ -102,7 +102,7 @@ open class BaseFragment : Fragment(), IBaseFragment {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
- requestManager = Glide.with(context!!)// TODO: Upgrade Glide usage
+ requestManager = Glide.with(requireContext())// TODO: Upgrade Glide usage
}
override fun onStart() {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/BasePreferenceFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/BasePreferenceFragment.kt
index 436b240d8c..7d41e5af06 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/BasePreferenceFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/BasePreferenceFragment.kt
@@ -140,8 +140,8 @@ abstract class BasePreferenceFragment : PreferenceFragmentCompat(), IBaseFragmen
companion object {
- private val REQUEST_PICK_RINGTONE = 301
- private val EXTRA_RINGTONE_PREFERENCE_KEY = "internal:ringtone_preference_key"
+ private const val REQUEST_PICK_RINGTONE = 301
+ private const val EXTRA_RINGTONE_PREFERENCE_KEY = "internal:ringtone_preference_key"
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/BaseWebViewFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/BaseWebViewFragment.kt
index ec93e57b0d..14ad0d0ada 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/BaseWebViewFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/BaseWebViewFragment.kt
@@ -48,7 +48,7 @@ open class BaseWebViewFragment : BaseFragment() {
protected fun createWebViewClient(): WebViewClient {
- return DefaultWebViewClient(activity!!)
+ return DefaultWebViewClient(requireActivity())
}
/**
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ColorPickerDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ColorPickerDialogFragment.kt
index 7783736d5d..7633e296b9 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ColorPickerDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ColorPickerDialogFragment.kt
@@ -61,14 +61,11 @@ class ColorPickerDialogFragment : BaseDialogFragment(), DialogInterface.OnClickL
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val color: Int
val args = arguments
- if (savedInstanceState != null) {
- color = savedInstanceState.getInt(EXTRA_COLOR, Color.WHITE)
- } else {
- color = args!!.getInt(EXTRA_COLOR, Color.WHITE)
- }
+ color =
+ savedInstanceState?.getInt(EXTRA_COLOR, Color.WHITE) ?: args!!.getInt(EXTRA_COLOR, Color.WHITE)
val activity = activity
- val builder = AlertDialog.Builder(activity!!)
+ val builder = AlertDialog.Builder(requireActivity())
builder.setView(me.uucky.colorpicker.R.layout.cp__dialog_color_picker)
builder.setPositiveButton(android.R.string.ok, this)
if (args!!.getBoolean(EXTRA_CLEAR_BUTTON, false)) {
@@ -82,7 +79,7 @@ class ColorPickerDialogFragment : BaseDialogFragment(), DialogInterface.OnClickL
val showAlphaSlider = args.getBoolean(EXTRA_ALPHA_SLIDER, true)
for (presetColor in PRESET_COLORS) {
- controller!!.addColor(ContextCompat.getColor(context!!, presetColor))
+ controller!!.addColor(ContextCompat.getColor(requireContext(), presetColor))
}
controller!!.setAlphaEnabled(showAlphaSlider)
controller!!.setInitialColor(color)
@@ -100,7 +97,7 @@ class ColorPickerDialogFragment : BaseDialogFragment(), DialogInterface.OnClickL
override fun onSaveInstanceState(outState: Bundle) {
if (controller != null) {
- outState!!.putInt(EXTRA_COLOR, controller!!.color)
+ outState.putInt(EXTRA_COLOR, controller!!.color)
}
super.onSaveInstanceState(outState)
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CreateUserBlockDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CreateUserBlockDialogFragment.kt
index e718e0beb8..cf0f03d510 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CreateUserBlockDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CreateUserBlockDialogFragment.kt
@@ -48,7 +48,7 @@ class CreateUserBlockDialogFragment : AbsUserMuteBlockDialogFragment() {
companion object {
- val FRAGMENT_TAG = "create_user_block"
+ const val FRAGMENT_TAG = "create_user_block"
fun show(fm: FragmentManager, user: ParcelableUser): CreateUserBlockDialogFragment {
val args = Bundle()
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CreateUserListDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CreateUserListDialogFragment.kt
index ace3fe2334..7086fbaa5a 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CreateUserListDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CreateUserListDialogFragment.kt
@@ -38,7 +38,7 @@ import org.mariotaku.twidere.util.ParseUtils
class CreateUserListDialogFragment : BaseDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setView(R.layout.dialog_user_list_detail_editor)
builder.setTitle(R.string.new_user_list)
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CreateUserMuteDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CreateUserMuteDialogFragment.kt
index 49b370c1b1..804b45fb4c 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CreateUserMuteDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CreateUserMuteDialogFragment.kt
@@ -49,7 +49,7 @@ class CreateUserMuteDialogFragment : AbsUserMuteBlockDialogFragment() {
companion object {
- val FRAGMENT_TAG = "create_user_mute"
+ const val FRAGMENT_TAG = "create_user_mute"
fun show(fm: FragmentManager, user: ParcelableUser): CreateUserMuteDialogFragment {
val args = Bundle()
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CursorActivitiesFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CursorActivitiesFragment.kt
index cff0549e7b..424fd8abf8 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CursorActivitiesFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CursorActivitiesFragment.kt
@@ -51,6 +51,8 @@ import org.mariotaku.twidere.util.DataStoreUtils
import org.mariotaku.twidere.util.DataStoreUtils.getTableNameByUri
import org.mariotaku.twidere.util.ErrorInfoStore
import org.mariotaku.twidere.util.Utils
+import kotlin.math.max
+import kotlin.math.min
/**
* Displays statuses from database
@@ -59,7 +61,7 @@ import org.mariotaku.twidere.util.Utils
abstract class CursorActivitiesFragment : AbsActivitiesFragment() {
override val accountKeys: Array
- get() = Utils.getAccountKeys(context!!, arguments) ?: DataStoreUtils.getActivatedAccountKeys(context!!)
+ get() = Utils.getAccountKeys(requireContext(), arguments) ?: DataStoreUtils.getActivatedAccountKeys(requireContext())
abstract val contentUri: Uri
@@ -241,8 +243,8 @@ abstract class CursorActivitiesFragment : AbsActivitiesFragment() {
fun replaceStatusStates(result: ParcelableStatus?) {
if (result == null) return
val lm = layoutManager
- val rangeStart = Math.max(adapter.activityStartIndex, lm.findFirstVisibleItemPosition())
- val rangeEnd = Math.min(lm.findLastVisibleItemPosition(), adapter.activityStartIndex + adapter.getActivityCount(false) - 1)
+ val rangeStart = max(adapter.activityStartIndex, lm.findFirstVisibleItemPosition())
+ val rangeEnd = min(lm.findLastVisibleItemPosition(), adapter.activityStartIndex + adapter.getActivityCount(false) - 1)
loop@ for (i in rangeStart..rangeEnd) {
val activity = adapter.getActivity(i, false)
if (result.account_key == activity.account_key && result.id == activity.id) {
@@ -353,7 +355,7 @@ abstract class CursorActivitiesFragment : AbsActivitiesFragment() {
class ActivityCursor(
cursor: Cursor,
- indies: ObjectCursor.CursorIndices,
+ indies: CursorIndices,
val filteredUserIds: Array,
val filteredUserNames: Array,
val filteredUserDescriptions: Array
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CursorStatusesFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CursorStatusesFragment.kt
index 52311562e4..0fae563f0b 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CursorStatusesFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CursorStatusesFragment.kt
@@ -70,7 +70,7 @@ abstract class CursorStatusesFragment : AbsStatusesFragment() {
get() = false
override val accountKeys: Array
- get() = Utils.getAccountKeys(context!!, arguments) ?: DataStoreUtils.getActivatedAccountKeys(context!!)
+ get() = Utils.getAccountKeys(requireContext(), arguments) ?: DataStoreUtils.getActivatedAccountKeys(requireContext())
abstract val errorInfoKey: String
abstract val isFilterEnabled: Boolean
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CustomTabsFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CustomTabsFragment.kt
index 1bc4678fbd..097c55387a 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CustomTabsFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/CustomTabsFragment.kt
@@ -93,7 +93,7 @@ class CustomTabsFragment : BaseFragment(), LoaderCallbacks, MultiChoice
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
setHasOptionsMenu(true)
- adapter = CustomTabsAdapter(context!!)
+ adapter = CustomTabsAdapter(requireContext())
listView.choiceMode = ListView.CHOICE_MODE_MULTIPLE_MODAL
listView.setMultiChoiceModeListener(this)
listView.onItemClickListener = OnItemClickListener { _, _, position, _ ->
@@ -130,7 +130,7 @@ class CustomTabsFragment : BaseFragment(), LoaderCallbacks, MultiChoice
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader {
- return CursorLoader(activity!!, Tabs.CONTENT_URI, Tabs.COLUMNS, null, null, Tabs.DEFAULT_SORT_ORDER)
+ return CursorLoader(requireActivity(), Tabs.CONTENT_URI, Tabs.COLUMNS, null, null, Tabs.DEFAULT_SORT_ORDER)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
@@ -138,7 +138,7 @@ class CustomTabsFragment : BaseFragment(), LoaderCallbacks, MultiChoice
val context = this.context
val accounts = AccountUtils.getAllAccountDetails(AccountManager.get(context), false)
val itemAdd = menu.findItem(R.id.add_submenu)
- val theme = Chameleon.getOverrideTheme(context!!, context)
+ val theme = Chameleon.getOverrideTheme(requireContext(), context)
if (itemAdd != null && itemAdd.hasSubMenu()) {
val subMenu = itemAdd.subMenu
subMenu.clear()
@@ -394,7 +394,7 @@ class CustomTabsFragment : BaseFragment(), LoaderCallbacks, MultiChoice
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setView(R.layout.dialog_custom_tab_editor)
builder.setPositiveButton(R.string.action_save, null)
builder.setNegativeButton(android.R.string.cancel, null)
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DateTimePickerDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DateTimePickerDialogFragment.kt
index 279a8e056d..18db4ef160 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DateTimePickerDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DateTimePickerDialogFragment.kt
@@ -44,7 +44,7 @@ class DateTimePickerDialogFragment : BaseDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setView(R.layout.dialog_date_time_picker)
builder.setNegativeButton(android.R.string.cancel, null)
builder.setPositiveButton(android.R.string.ok, null)
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DeleteUserListMembersDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DeleteUserListMembersDialogFragment.kt
index afc2b16667..b7cc6070e6 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DeleteUserListMembersDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DeleteUserListMembersDialogFragment.kt
@@ -50,7 +50,7 @@ class DeleteUserListMembersDialogFragment : BaseDialogFragment(), DialogInterfac
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
val users = users
val userList = userList
if (users == null || userList == null) throw NullPointerException()
@@ -90,7 +90,7 @@ class DeleteUserListMembersDialogFragment : BaseDialogFragment(), DialogInterfac
companion object {
- val FRAGMENT_TAG = "destroy_user_list_member"
+ const val FRAGMENT_TAG = "destroy_user_list_member"
fun show(fm: FragmentManager, userList: ParcelableUserList,
vararg users: ParcelableUser): DeleteUserListMembersDialogFragment {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DestroyFriendshipDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DestroyFriendshipDialogFragment.kt
index 4157cb1fe3..bfae003a78 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DestroyFriendshipDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DestroyFriendshipDialogFragment.kt
@@ -48,7 +48,7 @@ class DestroyFriendshipDialogFragment : BaseDialogFragment(), DialogInterface.On
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
val nameFirst = preferences[nameFirstKey]
val displayName = userColorNameManager.getDisplayName(user, nameFirst)
builder.setTitle(getString(R.string.unfollow_user, displayName))
@@ -65,7 +65,7 @@ class DestroyFriendshipDialogFragment : BaseDialogFragment(), DialogInterface.On
companion object {
- val FRAGMENT_TAG = "destroy_friendship"
+ const val FRAGMENT_TAG = "destroy_friendship"
fun show(fm: FragmentManager, user: ParcelableUser): DestroyFriendshipDialogFragment {
val f = DestroyFriendshipDialogFragment()
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DestroySavedSearchDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DestroySavedSearchDialogFragment.kt
index d5f9fa4d71..895e4e50b5 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DestroySavedSearchDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DestroySavedSearchDialogFragment.kt
@@ -48,7 +48,7 @@ class DestroySavedSearchDialogFragment : BaseDialogFragment(), DialogInterface.O
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val context = activity
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
val name = searchName
builder.setTitle(getString(R.string.destroy_saved_search, name))
builder.setMessage(getString(R.string.destroy_saved_search_confirm_message, name))
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DestroyUserListDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DestroyUserListDialogFragment.kt
index 1409d68f14..73c08ca6e1 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DestroyUserListDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DestroyUserListDialogFragment.kt
@@ -46,7 +46,7 @@ class DestroyUserListDialogFragment : BaseDialogFragment(), DialogInterface.OnCl
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val context = activity
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
val userList = userList
builder.setTitle(getString(R.string.delete_user_list, userList.name))
builder.setMessage(getString(R.string.delete_user_list_confirm_message, userList.name))
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DestroyUserListSubscriptionDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DestroyUserListSubscriptionDialogFragment.kt
index a0c51fcf9e..3c1c4727e6 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DestroyUserListSubscriptionDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/DestroyUserListSubscriptionDialogFragment.kt
@@ -47,7 +47,7 @@ class DestroyUserListSubscriptionDialogFragment : BaseDialogFragment(), DialogIn
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val context = activity
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
val userList = userList
if (userList != null) {
builder.setTitle(getString(R.string.unsubscribe_from_user_list, userList.name))
@@ -69,7 +69,7 @@ class DestroyUserListSubscriptionDialogFragment : BaseDialogFragment(), DialogIn
companion object {
- val FRAGMENT_TAG = "destroy_user_list"
+ const val FRAGMENT_TAG = "destroy_user_list"
fun show(fm: FragmentManager,
userList: ParcelableUserList): DestroyUserListSubscriptionDialogFragment {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/EditAltTextDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/EditAltTextDialogFragment.kt
index f80d76ecb3..c05ede01aa 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/EditAltTextDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/EditAltTextDialogFragment.kt
@@ -36,11 +36,11 @@ import org.mariotaku.twidere.extension.applyTheme
class EditAltTextDialogFragment : BaseDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setTitle(R.string.edit_description)
builder.setView(R.layout.dialog_compose_edit_alt_text)
builder.setNegativeButton(android.R.string.cancel, null)
- val position = arguments!!.getInt(EXTRA_POSITION)
+ val position = requireArguments().getInt(EXTRA_POSITION)
builder.setPositiveButton(android.R.string.ok) { dialog, _ ->
val altText = (dialog as Dialog).editText.string
callback?.onSetAltText(position, altText)
@@ -51,7 +51,7 @@ class EditAltTextDialogFragment : BaseDialogFragment() {
val dialog = builder.create()
dialog.applyOnShow {
applyTheme()
- editText.setText(arguments!!.getString(EXTRA_TEXT))
+ editText.setText(requireArguments().getString(EXTRA_TEXT))
}
return dialog
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/EditUserListDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/EditUserListDialogFragment.kt
index ca89f7605e..75226fdbc6 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/EditUserListDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/EditUserListDialogFragment.kt
@@ -40,7 +40,7 @@ class EditUserListDialogFragment : BaseDialogFragment() {
private val listId: String by lazy { arguments?.getString(EXTRA_LIST_ID)!! }
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setView(R.layout.dialog_user_list_detail_editor)
builder.setTitle(R.string.title_user_list)
builder.positive(android.R.string.ok, this::onPositiveClick)
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ExtensionsListFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ExtensionsListFragment.kt
index df3ec1f1ca..28b50c5d74 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ExtensionsListFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ExtensionsListFragment.kt
@@ -57,11 +57,11 @@ class ExtensionsListFragment : AbsContentListViewFragment(),
}
override fun onCreateAdapter(context: Context, requestManager: RequestManager): ExtensionsAdapter {
- return ExtensionsAdapter(activity!!, requestManager)
+ return ExtensionsAdapter(requireActivity(), requestManager)
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader> {
- return ExtensionsListLoader(activity!!)
+ return ExtensionsListLoader(requireActivity())
}
override fun onLoadFinished(loader: Loader>, data: List) {
@@ -128,7 +128,7 @@ class ExtensionsListFragment : AbsContentListViewFragment(),
if (info.settings != null) {
intent.setClassName(info.packageName, info.settings)
} else {
- val pm = activity!!.packageManager
+ val pm = requireActivity().packageManager
val activities = pm.queryIntentActivities(intent, 0)
if (activities.isEmpty()) {
return false
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ExtraFeaturesIntroductionDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ExtraFeaturesIntroductionDialogFragment.kt
index ae8508b553..3e3377b29b 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ExtraFeaturesIntroductionDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ExtraFeaturesIntroductionDialogFragment.kt
@@ -32,7 +32,7 @@ class ExtraFeaturesIntroductionDialogFragment : BaseDialogFragment() {
val requestCode: Int get() = arguments?.getInt(EXTRA_REQUEST_CODE, 0) ?: 0
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setTitle(R.string.title_extra_features)
builder.setView(R.layout.dialog_extra_features_introduction)
builder.setPositiveButton(R.string.action_purchase) { _, _ ->
@@ -42,7 +42,7 @@ class ExtraFeaturesIntroductionDialogFragment : BaseDialogFragment() {
builder.setNegativeButton(R.string.action_later) { _, _ ->
onDialogCancelled()
}
- val restorePurchaseIntent = extraFeaturesService.createRestorePurchaseIntent(context!!, feature)
+ val restorePurchaseIntent = extraFeaturesService.createRestorePurchaseIntent(requireContext(), feature)
if (restorePurchaseIntent != null) {
builder.setNeutralButton(R.string.action_restore_purchase) { _, _ ->
startActivityForResultOnTarget(restorePurchaseIntent)
@@ -56,7 +56,7 @@ class ExtraFeaturesIntroductionDialogFragment : BaseDialogFragment() {
} else {
View.GONE
}
- val description = ExtraFeaturesService.getIntroduction(context!!, feature)
+ val description = ExtraFeaturesService.getIntroduction(requireContext(), feature)
val featureIcon = it.featureIcon
val featureDescription = it.featureDescription
featureIcon.setImageResource(description.icon)
@@ -89,14 +89,19 @@ class ExtraFeaturesIntroductionDialogFragment : BaseDialogFragment() {
}
private fun startActivityForResultOnTarget(intent: Intent) {
- if (targetFragment != null) {
- targetFragment?.startActivityForResult(intent, targetRequestCode)
- } else if (requestCode == 0) {
- startActivity(intent)
- } else if (parentFragment != null) {
- parentFragment?.startActivityForResult(intent, requestCode)
- } else {
- activity?.startActivityForResult(intent, requestCode)
+ when {
+ targetFragment != null -> {
+ targetFragment?.startActivityForResult(intent, targetRequestCode)
+ }
+ requestCode == 0 -> {
+ startActivity(intent)
+ }
+ parentFragment != null -> {
+ parentFragment?.startActivityForResult(intent, requestCode)
+ }
+ else -> {
+ activity?.startActivityForResult(intent, requestCode)
+ }
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/GroupFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/GroupFragment.kt
index 91bf87764e..4f7925964d 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/GroupFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/GroupFragment.kt
@@ -53,7 +53,7 @@ class GroupFragment : AbsToolbarTabPagesFragment(), LoaderCallbacks {
+ twitter.showGroup(groupId)
+ }
+ groupName != null -> {
+ twitter.showGroupByName(groupName)
+ }
+ else -> {
+ return SingleResponse()
+ }
}
return SingleResponse.getInstance(ParcelableGroupUtils.from(group, accountKey, 0,
group.isMember))
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/HostMappingsListFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/HostMappingsListFragment.kt
index 732f0074b0..713e631866 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/HostMappingsListFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/HostMappingsListFragment.kt
@@ -57,7 +57,7 @@ class HostMappingsListFragment : AbsContentListViewFragment?> {
- return ItemsLoader(context!!, arguments!!)
+ return ItemsLoader(requireContext(), requireArguments())
}
final override fun onLoadFinished(loader: Loader?>, data: List?) {
@@ -176,7 +175,7 @@ open class ItemsListFragment : AbsContentListRecyclerViewFragment(EXTRA_ACCOUNT_KEY)
protected fun hasMoreData(data: List?): Boolean {
- return data == null || !data.isEmpty()
+ return data == null || data.isNotEmpty()
}
override fun onLoadFinished(loader: Loader?>, data: List?) {
@@ -132,7 +131,7 @@ abstract class ParcelableGroupsFragment : AbsContentListRecyclerViewFragment?> {
val fromUser = args?.getBoolean(EXTRA_FROM_USER)
args?.remove(EXTRA_FROM_USER)
- return onCreateUserListsLoader(activity!!, args!!, fromUser!!)
+ return onCreateUserListsLoader(requireActivity(), args!!, fromUser!!)
}
override fun onLoaderReset(loader: Loader?>) {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ParcelableStatusesFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ParcelableStatusesFragment.kt
index 48504aaf31..d68cda6a79 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ParcelableStatusesFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ParcelableStatusesFragment.kt
@@ -46,6 +46,8 @@ import org.mariotaku.twidere.model.pagination.Pagination
import org.mariotaku.twidere.model.pagination.SinceMaxPagination
import org.mariotaku.twidere.util.Utils
import java.util.*
+import kotlin.math.max
+import kotlin.math.min
/**
* Created by mariotaku on 14/12/3.
@@ -193,13 +195,12 @@ abstract class ParcelableStatusesFragment : AbsStatusesFragment() {
fun removeStatus(statusId: String) {
val list = adapterData ?: return
val dataToRemove = HashSet()
- for (i in 0 until list.size) {
- val status = list[i]
- if (status.id == statusId || status.retweet_id == statusId) {
- dataToRemove.add(status)
- } else if (status.my_retweet_id == statusId) {
- status.my_retweet_id = null
- status.retweet_count = status.retweet_count - 1
+ for (element in list) {
+ if (element.id == statusId || element.retweet_id == statusId) {
+ dataToRemove.add(element)
+ } else if (element.my_retweet_id == statusId) {
+ element.my_retweet_id = null
+ element.retweet_count = element.retweet_count - 1
}
}
if (list is MutableList) {
@@ -211,8 +212,8 @@ abstract class ParcelableStatusesFragment : AbsStatusesFragment() {
fun replaceStatusStates(status: ParcelableStatus?) {
if (status == null) return
val lm = layoutManager
- val rangeStart = Math.max(adapter.statusStartIndex, lm.findFirstVisibleItemPosition())
- val rangeEnd = Math.min(lm.findLastVisibleItemPosition(), adapter.statusStartIndex + adapter.getStatusCount(false) - 1)
+ val rangeStart = max(adapter.statusStartIndex, lm.findFirstVisibleItemPosition())
+ val rangeEnd = min(lm.findLastVisibleItemPosition(), adapter.statusStartIndex + adapter.getStatusCount(false) - 1)
for (i in rangeStart..rangeEnd) {
val item = adapter.getStatus(i, false)
if (status == item) {
@@ -232,7 +233,7 @@ abstract class ParcelableStatusesFragment : AbsStatusesFragment() {
private fun updateRetweetedStatuses(status: ParcelableStatus?) {
val data = adapterData
- if (status == null || status.retweet_id == null || data == null) return
+ if (status?.retweet_id == null || data == null) return
data.forEach { orig ->
if (orig.account_key == status.account_key && TextUtils.equals(orig.id, status.retweet_id)) {
orig.my_retweet_id = status.my_retweet_id
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ParcelableUserListsFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ParcelableUserListsFragment.kt
index 0feac0981c..bc81118593 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ParcelableUserListsFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ParcelableUserListsFragment.kt
@@ -24,7 +24,6 @@ import android.os.Bundle
import androidx.loader.app.LoaderManager.LoaderCallbacks
import androidx.loader.app.hasRunningLoadersSafe
import androidx.loader.content.Loader
-import androidx.recyclerview.widget.RecyclerView
import android.view.KeyEvent
import com.bumptech.glide.RequestManager
import kotlinx.android.synthetic.main.fragment_content_recyclerview.*
@@ -74,7 +73,7 @@ abstract class ParcelableUserListsFragment : AbsContentListRecyclerViewFragment<
}
protected fun hasMoreData(data: List?): Boolean {
- return data == null || !data.isEmpty()
+ return data == null || data.isNotEmpty()
}
override fun onLoadFinished(loader: Loader>, data: List) {
@@ -137,7 +136,7 @@ abstract class ParcelableUserListsFragment : AbsContentListRecyclerViewFragment<
override fun onCreateLoader(id: Int, args: Bundle?): Loader> {
val fromUser = args?.getBoolean(EXTRA_FROM_USER)
args?.remove(EXTRA_FROM_USER)
- return onCreateUserListsLoader(activity!!, args!!, fromUser!!)
+ return onCreateUserListsLoader(requireActivity(), args!!, fromUser!!)
}
override fun onLoaderReset(loader: Loader>) {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ParcelableUsersFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ParcelableUsersFragment.kt
index 075a555683..6a32187f01 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ParcelableUsersFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ParcelableUsersFragment.kt
@@ -124,7 +124,7 @@ abstract class ParcelableUsersFragment : AbsContentListRecyclerViewFragment?> {
val fromUser = args?.getBoolean(EXTRA_FROM_USER)
args?.remove(EXTRA_FROM_USER)
- return onCreateUsersLoader(activity!!, args!!, fromUser!!).apply {
+ return onCreateUsersLoader(requireActivity(), args!!, fromUser!!).apply {
if (this is AbsRequestUsersLoader) {
pagination = args.getParcelable(EXTRA_PAGINATION)
}
@@ -270,7 +270,7 @@ abstract class ParcelableUsersFragment : AbsContentListRecyclerViewFragment?): Boolean {
- return data == null || !data.isEmpty()
+ return data == null || data.isNotEmpty()
}
protected fun createMessageBusCallback(): Any {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/PermissionRequestDialog.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/PermissionRequestDialog.kt
index a058065ede..e82845268c 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/PermissionRequestDialog.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/PermissionRequestDialog.kt
@@ -18,10 +18,10 @@ import org.mariotaku.twidere.extension.onShow
class PermissionRequestDialog : BaseDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
- val permissions = arguments!!.getStringArray(EXTRA_PERMISSIONS).orEmpty()
- val requestCode = arguments!!.getInt(EXTRA_REQUEST_CODE)
- builder.setMessage(arguments!!.getString(EXTRA_MESSAGE))
+ val builder = AlertDialog.Builder(requireContext())
+ val permissions = requireArguments().getStringArray(EXTRA_PERMISSIONS).orEmpty()
+ val requestCode = requireArguments().getInt(EXTRA_REQUEST_CODE)
+ builder.setMessage(requireArguments().getString(EXTRA_MESSAGE))
builder.setPositiveButton(android.R.string.ok) { _, _ ->
activity?.let { ActivityCompat.requestPermissions(it, permissions, requestCode) }
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/PhishingLinkWarningDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/PhishingLinkWarningDialogFragment.kt
index 464d94ddaf..e7c8bab2f6 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/PhishingLinkWarningDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/PhishingLinkWarningDialogFragment.kt
@@ -47,7 +47,7 @@ class PhishingLinkWarningDialogFragment : BaseDialogFragment(), OnClickListener
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setTitle(android.R.string.dialog_alert_title)
builder.setView(R.layout.dialog_phishing_link_warning)
builder.setPositiveButton(android.R.string.ok, this)
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ReportUserSpamDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ReportUserSpamDialogFragment.kt
index 992b3844cd..bcdc5e6a6b 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ReportUserSpamDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ReportUserSpamDialogFragment.kt
@@ -49,7 +49,7 @@ class ReportUserSpamDialogFragment : AbsUserMuteBlockDialogFragment() {
companion object {
- val FRAGMENT_TAG = "report_user_spam"
+ const val FRAGMENT_TAG = "report_user_spam"
fun show(fm: FragmentManager, user: ParcelableUser): ReportUserSpamDialogFragment {
val f = ReportUserSpamDialogFragment()
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/SavedSearchesListFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/SavedSearchesListFragment.kt
index b483dca28b..76549415ba 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/SavedSearchesListFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/SavedSearchesListFragment.kt
@@ -75,7 +75,7 @@ class SavedSearchesListFragment : AbsContentListViewFragment?> {
- return SavedSearchesLoader(activity!!, accountKey)
+ return SavedSearchesLoader(requireActivity(), accountKey)
}
override fun onItemLongClick(view: AdapterView<*>, child: View, position: Int, id: Long): Boolean {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/SensitiveContentWarningDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/SensitiveContentWarningDialogFragment.kt
index a0907a50a2..f5c7178be0 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/SensitiveContentWarningDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/SensitiveContentWarningDialogFragment.kt
@@ -55,7 +55,7 @@ class SensitiveContentWarningDialogFragment : BaseDialogFragment(), DialogInterf
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val context = activity
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setTitle(android.R.string.dialog_alert_title)
builder.setMessage(R.string.sensitive_content_warning)
builder.setPositiveButton(android.R.string.ok, this)
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/SetUserNicknameDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/SetUserNicknameDialogFragment.kt
index 4f8eb43e6e..4376dfb5b9 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/SetUserNicknameDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/SetUserNicknameDialogFragment.kt
@@ -57,7 +57,7 @@ class SetUserNicknameDialogFragment : BaseDialogFragment(), OnClickListener {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val nick = arguments?.getString(EXTRA_NAME)
val context = activity
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setTitle(R.string.title_set_nickname)
builder.setPositiveButton(android.R.string.ok, this)
if (!nick.isNullOrEmpty()) {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/SettingsDetailsFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/SettingsDetailsFragment.kt
index e98208a9f8..5d73df4cee 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/SettingsDetailsFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/SettingsDetailsFragment.kt
@@ -37,23 +37,27 @@ class SettingsDetailsFragment : BasePreferenceFragment(), OnSharedPreferenceChan
preferenceManager.sharedPreferencesName = SHARED_PREFERENCES_NAME
val defaultScreen = preferenceScreen
val preferenceScreen: PreferenceScreen
- if (defaultScreen != null) {
+ preferenceScreen = if (defaultScreen != null) {
defaultScreen.removeAll()
- preferenceScreen = defaultScreen
+ defaultScreen
} else {
- preferenceScreen = preferenceManager.createPreferenceScreen(activity)
+ preferenceManager.createPreferenceScreen(activity)
}
setPreferenceScreen(preferenceScreen)
val args = arguments
val rawResId = args?.get(EXTRA_RESID)
val resId: Int
- if (rawResId is Int) {
- resId = rawResId
- } else if (rawResId is String) {
- resId = Utils.getResId(activity, rawResId)
- } else {
- resId = 0
+ resId = when (rawResId) {
+ is Int -> {
+ rawResId
+ }
+ is String -> {
+ Utils.getResId(activity, rawResId)
+ }
+ else -> {
+ 0
+ }
}
if (resId != 0) {
addPreferencesFromResource(resId)
@@ -81,12 +85,16 @@ class SettingsDetailsFragment : BasePreferenceFragment(), OnSharedPreferenceChan
val currentActivity = activity ?: return
val extras = preference.extras
if (extras != null) {
- if (extras.containsKey(EXTRA_SHOULD_RESTART)) {
- SettingsActivity.setShouldRestart(currentActivity)
- } else if (extras.containsKey(EXTRA_SHOULD_RECREATE)) {
- SettingsActivity.setShouldRecreate(currentActivity)
- } else if (extras.containsKey(EXTRA_SHOULD_TERMINATE)) {
- SettingsActivity.setShouldTerminate(currentActivity)
+ when {
+ extras.containsKey(EXTRA_SHOULD_RESTART) -> {
+ SettingsActivity.setShouldRestart(currentActivity)
+ }
+ extras.containsKey(EXTRA_SHOULD_RECREATE) -> {
+ SettingsActivity.setShouldRecreate(currentActivity)
+ }
+ extras.containsKey(EXTRA_SHOULD_TERMINATE) -> {
+ SettingsActivity.setShouldTerminate(currentActivity)
+ }
}
if (extras.containsKey(EXTRA_RECREATE_ACTIVITY)) {
currentActivity.recreate()
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ThemedEditTextPreferenceDialogFragmentCompat.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ThemedEditTextPreferenceDialogFragmentCompat.kt
index 4c53060b02..d43fca2972 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ThemedEditTextPreferenceDialogFragmentCompat.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ThemedEditTextPreferenceDialogFragmentCompat.kt
@@ -64,7 +64,7 @@ class ThemedEditTextPreferenceDialogFragmentCompat : ThemedPreferenceDialogFragm
fun newInstance(key: String): ThemedEditTextPreferenceDialogFragmentCompat {
val fragment = ThemedEditTextPreferenceDialogFragmentCompat()
val args = Bundle()
- args.putString(PreferenceDialogFragmentCompat.ARG_KEY, key)
+ args.putString(ARG_KEY, key)
fragment.arguments = args
return fragment
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ThemedPreferenceDialogFragmentCompat.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ThemedPreferenceDialogFragmentCompat.kt
index 1329328aa7..f9e6babba5 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ThemedPreferenceDialogFragmentCompat.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/ThemedPreferenceDialogFragmentCompat.kt
@@ -29,7 +29,7 @@ abstract class ThemedPreferenceDialogFragmentCompat : PreferenceDialogFragmentCo
val context = context
val preference = preference
onClick(null, DialogInterface.BUTTON_NEGATIVE)
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
.setTitle(preference.dialogTitle)
.setIcon(preference.dialogIcon)
.setPositiveButton(preference.positiveButtonText, this)
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/TrendsSuggestionsFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/TrendsSuggestionsFragment.kt
index 87ce0ae8ba..c83a4e4a14 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/TrendsSuggestionsFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/TrendsSuggestionsFragment.kt
@@ -73,7 +73,7 @@ class TrendsSuggestionsFragment : AbsContentListViewFragment(), L
}
override fun onCreateAdapter(context: Context, requestManager: RequestManager): TrendsAdapter {
- return TrendsAdapter(activity!!)
+ return TrendsAdapter(requireActivity())
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader {
@@ -81,19 +81,18 @@ class TrendsSuggestionsFragment : AbsContentListViewFragment(), L
val loaderWhere = Expression.and(Expression.equalsArgs(CachedTrends.ACCOUNT_KEY),
Expression.equalsArgs(CachedTrends.WOEID)).sql
val loaderWhereArgs = arrayOf(accountKey?.toString().orEmpty(), woeId.toString())
- return CursorLoader(activity!!, uri, CachedTrends.COLUMNS, loaderWhere, loaderWhereArgs, CachedTrends.TREND_ORDER)
+ return CursorLoader(requireActivity(), uri, CachedTrends.COLUMNS, loaderWhere, loaderWhereArgs, CachedTrends.TREND_ORDER)
}
override fun onItemClick(view: AdapterView<*>, child: View, position: Int, id: Long) {
if (multiSelectManager.isActive) return
- val trend: String?
- if (view is ListView) {
- trend = adapter.getItem(position - view.headerViewsCount)
+ val trend: String = (if (view is ListView) {
+ adapter.getItem(position - view.headerViewsCount)
} else {
- trend = adapter.getItem(position)
+ adapter.getItem(position)
- }
- if (trend == null) return
+ })
+ ?: return
activity?.let { openTweetSearch(it, accountKey, trend) }
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserFragment.kt
index 9b759e6795..140da6573a 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserFragment.kt
@@ -96,6 +96,7 @@ import org.mariotaku.microblog.library.mastodon.Mastodon
import org.mariotaku.microblog.library.twitter.model.FriendshipUpdate
import org.mariotaku.microblog.library.twitter.model.Paging
import org.mariotaku.microblog.library.twitter.model.UserList
+import org.mariotaku.twidere.BuildConfig
import org.mariotaku.twidere.Constants.*
import org.mariotaku.twidere.R
import org.mariotaku.twidere.activity.AccountSelectorActivity
@@ -149,6 +150,8 @@ import org.mariotaku.twidere.view.TabPagerIndicator
import org.mariotaku.twidere.view.iface.IExtendedView.OnSizeChangedListener
import java.lang.ref.WeakReference
import java.util.*
+import kotlin.math.max
+import kotlin.math.roundToInt
class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
OnSizeChangedListener, OnTouchListener, DrawerCallback, SupportFragmentCallback,
@@ -241,38 +244,42 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
override fun onLoadFinished(loader: Loader>,
data: SingleResponse) {
val activity = activity ?: return
- if (data.data != null) {
- val user = data.data
- cardContent.visibility = View.VISIBLE
- errorContainer.visibility = View.GONE
- progressContainer.visibility = View.GONE
- val account: AccountDetails = data.extras.getParcelable(EXTRA_ACCOUNT)!!
- displayUser(user, account)
- if (user.is_cache) {
- val args = Bundle()
- args.putParcelable(EXTRA_ACCOUNT_KEY, user.account_key)
- args.putParcelable(EXTRA_USER_KEY, user.key)
- args.putString(EXTRA_SCREEN_NAME, user.screen_name)
- args.putBoolean(EXTRA_OMIT_INTENT_EXTRA, true)
- loaderManager.restartLoader(LOADER_ID_USER, args, this)
+ when {
+ data.data != null -> {
+ val user = data.data
+ cardContent.visibility = View.VISIBLE
+ errorContainer.visibility = View.GONE
+ progressContainer.visibility = View.GONE
+ val account: AccountDetails = data.extras.getParcelable(EXTRA_ACCOUNT)!!
+ displayUser(user, account)
+ if (user.is_cache) {
+ val args = Bundle()
+ args.putParcelable(EXTRA_ACCOUNT_KEY, user.account_key)
+ args.putParcelable(EXTRA_USER_KEY, user.key)
+ args.putString(EXTRA_SCREEN_NAME, user.screen_name)
+ args.putBoolean(EXTRA_OMIT_INTENT_EXTRA, true)
+ loaderManager.restartLoader(LOADER_ID_USER, args, this)
+ }
+ updateOptionsMenuVisibility()
}
- updateOptionsMenuVisibility()
- } else if (user?.is_cache == true) {
- cardContent.visibility = View.VISIBLE
- errorContainer.visibility = View.GONE
- progressContainer.visibility = View.GONE
- displayUser(user, account)
- updateOptionsMenuVisibility()
- } else {
- if (data.hasException()) {
- errorText.text = data.exception?.getErrorMessage(activity)
- errorText.visibility = View.VISIBLE
+ user?.is_cache == true -> {
+ cardContent.visibility = View.VISIBLE
+ errorContainer.visibility = View.GONE
+ progressContainer.visibility = View.GONE
+ displayUser(user, account)
+ updateOptionsMenuVisibility()
+ }
+ else -> {
+ if (data.hasException()) {
+ errorText.text = data.exception?.getErrorMessage(activity)
+ errorText.visibility = View.VISIBLE
+ }
+ cardContent.visibility = View.GONE
+ errorContainer.visibility = View.VISIBLE
+ progressContainer.visibility = View.GONE
+ displayUser(null, null)
+ updateOptionsMenuVisibility()
}
- cardContent.visibility = View.GONE
- errorContainer.visibility = View.VISIBLE
- progressContainer.visibility = View.GONE
- displayUser(null, null)
- updateOptionsMenuVisibility()
}
}
@@ -378,7 +385,7 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
}
override fun onPageScrollStateChanged(state: Int) {
- userProfileSwipeLayout.setEnabled(state == ViewPager.SCROLL_STATE_IDLE)
+ userProfileSwipeLayout.isEnabled = state == ViewPager.SCROLL_STATE_IDLE
}
override fun scrollBy(dy: Float) {
@@ -474,7 +481,7 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
if (user.created_at >= 0) {
val createdAt = Utils.formatToLongTimeString(activity, user.created_at)
val daysSinceCreation = (System.currentTimeMillis() - user.created_at) / 1000 / 60 / 60 / 24.toFloat()
- val dailyTweets = Math.round(user.statuses_count / Math.max(1f, daysSinceCreation))
+ val dailyTweets = (user.statuses_count / max(1f, daysSinceCreation)).roundToInt()
createdAtContainer.visibility = View.VISIBLE
createdAtContainer.createdAt.text = resources.getQuantityString(R.plurals.created_at_with_N_tweets_per_day, dailyTweets,
@@ -492,13 +499,17 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
listedContainer.visibility = if (user.listed_count < 0) View.GONE else View.VISIBLE
groupsContainer.visibility = if (user.groups_count < 0) View.GONE else View.VISIBLE
- if (user.color != 0) {
- setUiColor(user.color)
- } else if (user.link_color != 0) {
- setUiColor(user.link_color)
- } else {
- val theme = Chameleon.getOverrideTheme(activity, activity)
- setUiColor(theme.colorPrimary)
+ when {
+ user.color != 0 -> {
+ setUiColor(user.color)
+ }
+ user.link_color != 0 -> {
+ setUiColor(user.link_color)
+ }
+ else -> {
+ val theme = Chameleon.getOverrideTheme(activity, activity)
+ setUiColor(theme.colorPrimary)
+ }
}
val defWidth = resources.displayMetrics.widthPixels
val width = if (bannerWidth > 0) bannerWidth else defWidth
@@ -666,7 +677,7 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
actionBarShadowColor = 0xA0000000.toInt()
val args = arguments
val accountKey = args?.getParcelable(EXTRA_ACCOUNT_KEY) ?: run {
- activity?.finish()
+ activity.finish()
return
}
val userKey = args.getParcelable(EXTRA_USER_KEY)
@@ -687,7 +698,7 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
if (profileBannerSpace.toolbarHeight == 0) {
var toolbarHeight = toolbar.measuredHeight
if (toolbarHeight == 0) {
- toolbarHeight = ThemeUtils.getActionBarHeight(context!!)
+ toolbarHeight = ThemeUtils.getActionBarHeight(requireContext())
}
profileBannerSpace.toolbarHeight = toolbarHeight
}
@@ -813,7 +824,7 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
menu.setItemAvailability(R.id.block, !isMyself)
menu.setItemAvailability(R.id.add_to_home_screen_submenu,
- ShortcutManagerCompat.isRequestPinShortcutSupported(context!!))
+ ShortcutManagerCompat.isRequestPinShortcutSupported(requireContext()))
var canAddToList = false
var canMute = false
@@ -1130,7 +1141,7 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
return
}
val spec = pagerAdapter.get(viewPager.currentItem)
- assert(spec.type != null)
+ if (BuildConfig.DEBUG && spec.type == null) { error("Assertion failed") }
when (spec.type) {
TAB_TYPE_STATUSES, TAB_TYPE_STATUSES_WITH_REPLIES -> {
actionBar.subtitle = resources.getQuantityString(R.plurals.N_statuses,
@@ -1224,14 +1235,19 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
val userRelationship = relationship
val twitter = twitterWrapper
if (userRelationship == null) return
- if (userRelationship.blocking) {
- twitter.destroyBlockAsync(accountKey, user.key)
- } else if (userRelationship.blocked_by) {
- CreateUserBlockDialogFragment.show(childFragmentManager, user)
- } else if (userRelationship.following) {
- DestroyFriendshipDialogFragment.show(fragmentManager, user)
- } else {
- twitter.createFriendshipAsync(accountKey, user.key, user.screen_name)
+ when {
+ userRelationship.blocking -> {
+ twitter.destroyBlockAsync(accountKey, user.key)
+ }
+ userRelationship.blocked_by -> {
+ CreateUserBlockDialogFragment.show(childFragmentManager, user)
+ }
+ userRelationship.following -> {
+ DestroyFriendshipDialogFragment.show(fragmentManager, user)
+ }
+ else -> {
+ twitter.createFriendshipAsync(accountKey, user.key, user.screen_name)
+ }
}
}
}
@@ -1297,16 +1313,16 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
return true
}
TwidereLinkify.LINK_TYPE_HASHTAG -> {
- IntentUtils.openTweetSearch(activity, user.account_key, "#" + link)
+ IntentUtils.openTweetSearch(activity, user.account_key, "#$link")
return true
}
TwidereLinkify.LINK_TYPE_LINK_IN_TEXT, TwidereLinkify.LINK_TYPE_ENTITY_URL -> {
val uri = Uri.parse(link)
val intent: Intent
- if (uri.scheme != null) {
- intent = Intent(Intent.ACTION_VIEW, uri)
+ intent = if (uri.scheme != null) {
+ Intent(Intent.ACTION_VIEW, uri)
} else {
- intent = Intent(Intent.ACTION_VIEW, uri.buildUpon().scheme("http").build())
+ Intent(Intent.ACTION_VIEW, uri.buildUpon().scheme("http").build())
}
startActivity(intent)
return true
@@ -1404,18 +1420,18 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
previousActionBarItemIsDark = 0
previousTabItemIsDark = 0
setupBaseActionBar()
- if (theme.isToolbarColored) {
- primaryColor = color
+ primaryColor = if (theme.isToolbarColored) {
+ color
} else {
- primaryColor = theme.colorToolbar
+ theme.colorToolbar
}
primaryColorDark = ChameleonUtils.darkenColor(primaryColor)
actionBarBackground.color = primaryColor
val taskColor: Int
- if (theme.isToolbarColored) {
- taskColor = ColorUtils.setAlphaComponent(color, 0xFF)
+ taskColor = if (theme.isToolbarColored) {
+ ColorUtils.setAlphaComponent(color, 0xFF)
} else {
- taskColor = ColorUtils.setAlphaComponent(theme.colorToolbar, 0xFF)
+ ColorUtils.setAlphaComponent(theme.colorToolbar, 0xFF)
}
val user = this.user
if (user != null) {
@@ -1524,10 +1540,10 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
val profileContentHeight = (profileNameContainer!!.height + profileDetailsContainer.height).toFloat()
val tabOutlineAlphaFactor: Float
- if (offset - spaceHeight > 0) {
- tabOutlineAlphaFactor = 1f - ((offset - spaceHeight) / profileContentHeight).coerceIn(0f, 1f)
+ tabOutlineAlphaFactor = if (offset - spaceHeight > 0) {
+ 1f - ((offset - spaceHeight) / profileContentHeight).coerceIn(0f, 1f)
} else {
- tabOutlineAlphaFactor = 1f
+ 1f
}
actionBarBackground.apply {
@@ -1634,7 +1650,7 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
return result
}
- val microBlog = MicroBlogAPIFactory.getInstance(fragment.context!!, accountKey)
+ val microBlog = MicroBlogAPIFactory.getInstance(fragment.requireContext(), accountKey)
val ownedLists = ArrayList()
val listMemberships = microBlog.getUserListOwnerMemberships(user.key.id)
val paging = Paging()
@@ -1669,7 +1685,7 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
}
}.failUi {
val fragment = weakThis.get() ?: return@failUi
- Toast.makeText(fragment.context, it.getErrorMessage(fragment.context!!),
+ Toast.makeText(fragment.context, it.getErrorMessage(fragment.requireContext()),
Toast.LENGTH_SHORT).show()
}
}
@@ -1728,10 +1744,10 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
}
private fun updateValue() {
- val shadowAlpha = Math.round(alpha * (1 - factor).coerceIn(0f, 1f))
+ val shadowAlpha = (alpha * (1 - factor).coerceIn(0f, 1f)).roundToInt()
shadowDrawable.alpha = shadowAlpha
val hasColor = color != 0
- val colorAlpha = if (hasColor) Math.round(alpha * factor.coerceIn(0f, 1f)) else 0
+ val colorAlpha = if (hasColor) (alpha * factor.coerceIn(0f, 1f)).roundToInt() else 0
colorDrawable.alpha = colorAlpha
invalidateSelf()
}
@@ -1803,10 +1819,10 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
class AddRemoveUserListDialogFragment : BaseDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val lists = arguments!!.getTypedArray(EXTRA_USER_LISTS)
- val userKey = arguments!!.getParcelable(EXTRA_USER_KEY)!!
- val accountKey = arguments!!.getParcelable(EXTRA_ACCOUNT_KEY)!!
- val builder = AlertDialog.Builder(context!!)
+ val lists = requireArguments().getTypedArray(EXTRA_USER_LISTS)
+ val userKey = requireArguments().getParcelable(EXTRA_USER_KEY)!!
+ val accountKey = requireArguments().getParcelable(EXTRA_ACCOUNT_KEY)!!
+ val builder = AlertDialog.Builder(requireContext())
builder.setTitle(R.string.title_add_or_remove_from_list)
val entries = Array(lists.size) { idx ->
lists[idx].name
@@ -1866,7 +1882,7 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
states[pos] = checked
}
}
- Toast.makeText(context, e.getErrorMessage(context!!), Toast.LENGTH_SHORT).show()
+ Toast.makeText(context, e.getErrorMessage(requireContext()), Toast.LENGTH_SHORT).show()
}
}
d.getButton(DialogInterface.BUTTON_NEUTRAL).setOnClickListener {
@@ -1874,7 +1890,7 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
df.arguments = Bundle {
this[EXTRA_ACCOUNT_KEY] = accountKey
}
- df.show(fragmentManager!!, "create_user_list")
+ df.show(requireFragmentManager(), "create_user_list")
}
}
return dialog
@@ -1886,8 +1902,8 @@ class UserFragment : BaseFragment(), OnClickListener, OnLinkClickListener,
companion object {
private val sArgbEvaluator = ArgbEvaluator()
- private val LOADER_ID_USER = 1
- private val LOADER_ID_FRIENDSHIP = 2
+ private const val LOADER_ID_USER = 1
+ private const val LOADER_ID_FRIENDSHIP = 2
private const val TAB_POSITION_STATUSES = 0
private const val TAB_POSITION_MEDIA = 1
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserListFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserListFragment.kt
index 77b1561c91..64eb990297 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserListFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserListFragment.kt
@@ -316,7 +316,7 @@ class UserListFragment : AbsToolbarTabPagesFragment(), OnClickListener,
val listName = args.getString(EXTRA_LIST_NAME)
val screenName = args.getString(EXTRA_SCREEN_NAME)
val omitIntentExtra = args.getBoolean(EXTRA_OMIT_INTENT_EXTRA, true)
- return ParcelableUserListLoader(activity!!, omitIntentExtra, arguments, accountKey, listId,
+ return ParcelableUserListLoader(requireActivity(), omitIntentExtra, arguments, accountKey, listId,
listName, userKey, screenName)
}
@@ -372,15 +372,15 @@ class UserListFragment : AbsToolbarTabPagesFragment(), OnClickListener,
val twitter = MicroBlogAPIFactory.getInstance(context, accountKey)
?: throw MicroBlogException("No account")
val list: UserList
- when {
+ list = when {
listId != null -> {
- list = twitter.showUserList(listId)
+ twitter.showUserList(listId)
}
listName != null && userKey != null -> {
- list = twitter.showUserList(listName, userKey.id)
+ twitter.showUserList(listName, userKey.id)
}
listName != null && screenName != null -> {
- list = twitter.showUserListByScrenName(listName, screenName)
+ twitter.showUserListByScrenName(listName, screenName)
}
else -> {
return SingleResponse(MicroBlogException("Invalid argument"))
@@ -401,8 +401,8 @@ class UserListFragment : AbsToolbarTabPagesFragment(), OnClickListener,
class UserListDetailsDialogFragment : BaseDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val userList = arguments!!.getParcelable(EXTRA_USER_LIST)!!
- val builder = AlertDialog.Builder(context!!)
+ val userList = requireArguments().getParcelable(EXTRA_USER_LIST)!!
+ val builder = AlertDialog.Builder(requireContext())
builder.setTitle(userList.name)
builder.setMessage(userList.description)
builder.setPositiveButton(android.R.string.ok, null)
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserListMembershipsFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserListMembershipsFragment.kt
index f59cfcd9e4..c596488001 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserListMembershipsFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserListMembershipsFragment.kt
@@ -34,7 +34,7 @@ class UserListMembershipsFragment : ParcelableUserListsFragment() {
val accountKey = args.getParcelable(EXTRA_ACCOUNT_KEY)
val userKey = args.getParcelable(EXTRA_USER_KEY)
val screenName = args.getString(EXTRA_SCREEN_NAME)
- return UserListMembershipsLoader(activity!!, accountKey, userKey, screenName, data).apply {
+ return UserListMembershipsLoader(requireActivity(), accountKey, userKey, screenName, data).apply {
pagination = args.getParcelable(EXTRA_PAGINATION)
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserListSubscriptionsFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserListSubscriptionsFragment.kt
index ad32469892..9a1ef7deee 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserListSubscriptionsFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserListSubscriptionsFragment.kt
@@ -33,7 +33,7 @@ class UserListSubscriptionsFragment : ParcelableUserListsFragment() {
val accountKey = args.getParcelable(EXTRA_ACCOUNT_KEY)
val userKey = args.getParcelable(EXTRA_USER_KEY)
val screenName = args.getString(EXTRA_SCREEN_NAME)
- return UserListSubscriptionsLoader(activity!!, accountKey, userKey, screenName, data).apply {
+ return UserListSubscriptionsLoader(requireActivity(), accountKey, userKey, screenName, data).apply {
pagination = args.getParcelable(EXTRA_PAGINATION)
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserListsOwnershipsFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserListsOwnershipsFragment.kt
index bdad370c13..5e3e7c25a9 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserListsOwnershipsFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserListsOwnershipsFragment.kt
@@ -47,7 +47,7 @@ class UserListsOwnershipsFragment : ParcelableUserListsFragment() {
val accountKey = args.getParcelable(EXTRA_ACCOUNT_KEY)
val userKey = args.getParcelable(EXTRA_USER_KEY)
val screenName = args.getString(EXTRA_SCREEN_NAME)
- return UserListOwnershipsLoader(activity!!, accountKey, userKey, screenName, data).apply {
+ return UserListOwnershipsLoader(requireActivity(), accountKey, userKey, screenName, data).apply {
pagination = args.getParcelable(EXTRA_PAGINATION)
}
}
@@ -82,7 +82,7 @@ class UserListsOwnershipsFragment : ParcelableUserListsFragment() {
menu.setItemAvailability(R.id.new_user_list, true)
} else {
menu.setItemAvailability(R.id.new_user_list, screenName != null &&
- Utils.isMyAccount(activity!!, screenName))
+ Utils.isMyAccount(requireActivity(), screenName))
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserProfileEditorFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserProfileEditorFragment.kt
index 988e61675c..10f73a78cd 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserProfileEditorFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserProfileEditorFragment.kt
@@ -50,7 +50,6 @@ import org.mariotaku.twidere.TwidereConstants.*
import org.mariotaku.twidere.activity.ColorPickerDialogActivity
import org.mariotaku.twidere.activity.ThemedMediaPickerActivity
import org.mariotaku.twidere.annotation.AccountType
-import org.mariotaku.twidere.annotation.ImageShapeStyle
import org.mariotaku.twidere.extension.loadProfileBanner
import org.mariotaku.twidere.extension.loadProfileImage
import org.mariotaku.twidere.extension.model.api.mastodon.toParcelable
@@ -132,7 +131,10 @@ class UserProfileEditorFragment : BaseFragment(), OnSizeChangedListener,
override fun onCreateLoader(id: Int, args: Bundle?): Loader> {
progressContainer.visibility = View.VISIBLE
editProfileContent.visibility = View.GONE
- return ParcelableUserLoader(activity!!, accountKey, accountKey, null, arguments, false, false)
+ return ParcelableUserLoader(requireActivity(), accountKey, accountKey, null, arguments,
+ omitIntentExtra = false,
+ loadFromCache = false
+ )
}
override fun onLoadFinished(loader: Loader>,
@@ -175,7 +177,7 @@ class UserProfileEditorFragment : BaseFragment(), OnSizeChangedListener,
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
setHasOptionsMenu(true)
- if (!Utils.isMyAccount(activity!!, accountKey)) {
+ if (!Utils.isMyAccount(requireActivity(), accountKey)) {
activity?.finish()
return
}
@@ -232,18 +234,19 @@ class UserProfileEditorFragment : BaseFragment(), OnSizeChangedListener,
REQUEST_UPLOAD_PROFILE_BANNER_IMAGE -> {
val task = currentTask
if (task != null && !task.isFinished) return
- if (resultCode == RESULT_REMOVE_BANNER) {
- currentTask = context?.let { RemoveProfileBannerTaskInternal(it, accountKey) }
+ currentTask = if (resultCode == RESULT_REMOVE_BANNER) {
+ context?.let { RemoveProfileBannerTaskInternal(it, accountKey) }
} else {
- currentTask = UpdateProfileBannerImageTaskInternal(this, accountKey,
- data.data!!, true)
+ UpdateProfileBannerImageTaskInternal(this, accountKey,
+ data.data!!, true)
}
}
REQUEST_UPLOAD_PROFILE_BACKGROUND_IMAGE -> {
val task = currentTask
if (task != null && !task.isFinished) return
currentTask = UpdateProfileBackgroundImageTaskInternal(this, accountKey,
- data.data!!, false, true)
+ data.data!!, tile = false, deleteImage = true
+ )
}
REQUEST_UPLOAD_PROFILE_IMAGE -> {
val task = currentTask
@@ -379,7 +382,7 @@ class UserProfileEditorFragment : BaseFragment(), OnSizeChangedListener,
private val linkColor: Int,
private val backgroundColor: Int
) : AbsAccountRequestTask,
- UserProfileEditorFragment>(fragment.context!!, accountKey) {
+ UserProfileEditorFragment>(fragment.requireContext(), accountKey) {
init {
this.callback = fragment
@@ -456,7 +459,7 @@ class UserProfileEditorFragment : BaseFragment(), OnSizeChangedListener,
companion object {
- private val DIALOG_FRAGMENT_TAG = "updating_user_profile"
+ private const val DIALOG_FRAGMENT_TAG = "updating_user_profile"
}
}
@@ -490,7 +493,7 @@ class UserProfileEditorFragment : BaseFragment(), OnSizeChangedListener,
accountKey: UserKey,
imageUri: Uri,
deleteImage: Boolean
- ) : UpdateProfileBannerImageTask(fragment.context!!, accountKey, imageUri, deleteImage) {
+ ) : UpdateProfileBannerImageTask(fragment.requireContext(), accountKey, imageUri, deleteImage) {
init {
callback = fragment
@@ -513,7 +516,7 @@ class UserProfileEditorFragment : BaseFragment(), OnSizeChangedListener,
imageUri: Uri,
tile: Boolean,
deleteImage: Boolean
- ) : UpdateProfileBackgroundImageTask(fragment.context!!, accountKey, imageUri,
+ ) : UpdateProfileBackgroundImageTask(fragment.requireContext(), accountKey, imageUri,
tile, deleteImage) {
init {
@@ -538,7 +541,7 @@ class UserProfileEditorFragment : BaseFragment(), OnSizeChangedListener,
accountKey: UserKey,
imageUri: Uri,
deleteImage: Boolean
- ) : UpdateProfileImageTask(fragment.context!!, accountKey, imageUri, deleteImage) {
+ ) : UpdateProfileImageTask(fragment.requireContext(), accountKey, imageUri, deleteImage) {
init {
callback = fragment
@@ -559,16 +562,16 @@ class UserProfileEditorFragment : BaseFragment(), OnSizeChangedListener,
companion object {
- private val LOADER_ID_USER = 1
+ private const val LOADER_ID_USER = 1
- private val REQUEST_UPLOAD_PROFILE_IMAGE = 1
- private val REQUEST_UPLOAD_PROFILE_BANNER_IMAGE = 2
- private val REQUEST_UPLOAD_PROFILE_BACKGROUND_IMAGE = 3
- private val REQUEST_PICK_LINK_COLOR = 11
- private val REQUEST_PICK_BACKGROUND_COLOR = 12
+ private const val REQUEST_UPLOAD_PROFILE_IMAGE = 1
+ private const val REQUEST_UPLOAD_PROFILE_BANNER_IMAGE = 2
+ private const val REQUEST_UPLOAD_PROFILE_BACKGROUND_IMAGE = 3
+ private const val REQUEST_PICK_LINK_COLOR = 11
+ private const val REQUEST_PICK_BACKGROUND_COLOR = 12
- private val RESULT_REMOVE_BANNER = 101
- private val UPDATE_PROFILE_DIALOG_FRAGMENT_TAG = "update_profile"
+ private const val RESULT_REMOVE_BANNER = 101
+ private const val UPDATE_PROFILE_DIALOG_FRAGMENT_TAG = "update_profile"
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserQrDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserQrDialogFragment.kt
index 5c127cb023..78870607bc 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserQrDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/UserQrDialogFragment.kt
@@ -120,17 +120,17 @@ class UserQrDialogFragment : BaseDialogFragment() {
}
val profileImageSize = getString(R.string.profile_image_size)
val context = context?.applicationContext
- val requestManager = Glide.with(context!!)
+ val requestManager = Glide.with(requireContext())
val user = this.user
return task {
try {
- return@task requestManager.loadOriginalProfileImage(context!!, user, 0)
+ return@task requestManager.loadOriginalProfileImage(requireContext(), user, 0)
.into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get()
} catch (e: ExecutionException) {
// Ignore
}
// Return fallback profile image
- return@task requestManager.loadProfileImage(context!!, user, 0, size = profileImageSize)
+ return@task requestManager.loadProfileImage(requireContext(), user, 0, size = profileImageSize)
.into(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL).get()
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/drafts/DraftsListFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/drafts/DraftsListFragment.kt
index 1a874a2f0f..b266b66966 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/drafts/DraftsListFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/drafts/DraftsListFragment.kt
@@ -111,7 +111,7 @@ class DraftsListFragment : AbsContentListViewFragment(), LoaderCa
}
override fun onCreateAdapter(context: Context, requestManager: RequestManager): DraftsAdapter {
- return DraftsAdapter(activity!!, requestManager).apply {
+ return DraftsAdapter(requireActivity(), requestManager).apply {
textSize = preferences[textSizeKey].toFloat()
}
}
@@ -125,7 +125,7 @@ class DraftsListFragment : AbsContentListViewFragment(), LoaderCa
Pair(Expression.inArgs(Drafts.ACTION_TYPE, actions.size).sql, actions)
} else Pair(null, null)
val orderBy = OrderBy(Drafts.TIMESTAMP, false).sql
- return CursorLoader(activity!!, uri, cols, selection, selectionArgs, orderBy)
+ return CursorLoader(requireActivity(), uri, cols, selection, selectionArgs, orderBy)
}
override fun onLoadFinished(loader: Loader, cursor: Cursor?) {
@@ -289,7 +289,7 @@ class DraftsListFragment : AbsContentListViewFragment(), LoaderCa
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val context = activity
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setMessage(R.string.delete_drafts_confirm)
builder.setPositiveButton(android.R.string.ok, this)
builder.setNegativeButton(android.R.string.cancel, null)
@@ -337,7 +337,7 @@ class DraftsListFragment : AbsContentListViewFragment(), LoaderCa
companion object {
- private val FRAGMENT_TAG_DELETING_DRAFTS = "deleting_drafts"
+ private const val FRAGMENT_TAG_DELETING_DRAFTS = "deleting_drafts"
}
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/filter/AddEditItemFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/filter/AddEditItemFragment.kt
index 0ce37e5e9e..02e1348493 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/filter/AddEditItemFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/filter/AddEditItemFragment.kt
@@ -114,7 +114,7 @@ class AddEditItemFragment : BaseDialogFragment() {
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setView(R.layout.dialog_filter_rule_editor)
if (arguments?.getLong(EXTRA_ID, -1) ?: -1 >= 0) {
@@ -129,10 +129,10 @@ class AddEditItemFragment : BaseDialogFragment() {
applyTheme()
window!!.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE)
editText.setAdapter(when (contentUri) {
- Filters.Sources.CONTENT_URI -> SourceAutoCompleteAdapter(activity!!)
- Filters.Users.CONTENT_URI -> ComposeAutoCompleteAdapter(activity!!, requestManager).apply {
+ Filters.Sources.CONTENT_URI -> SourceAutoCompleteAdapter(requireActivity())
+ Filters.Users.CONTENT_URI -> ComposeAutoCompleteAdapter(requireActivity(), requestManager).apply {
val am = AccountManager.get(activity)
- account = AccountUtils.getDefaultAccountDetails(activity!!, am, false)
+ account = AccountUtils.getDefaultAccountDetails(requireActivity(), am, false)
}
else -> null
})
@@ -142,7 +142,7 @@ class AddEditItemFragment : BaseDialogFragment() {
advancedExpanded = !advancedExpanded
}
positiveButton.setOnClickListener(this@AddEditItemFragment::handlePositiveClick)
- advancedContainer.children.filter { it is CheckBox }.forEach {
+ advancedContainer.children.filterIsInstance().forEach {
val checkBox = it as CheckBox
checkBox.setOnClickListener onClick@ {
if (extraFeaturesService.isAdvancedFiltersEnabled) return@onClick
@@ -151,7 +151,7 @@ class AddEditItemFragment : BaseDialogFragment() {
val df = ExtraFeaturesIntroductionDialogFragment.create(
ExtraFeaturesService.FEATURE_ADVANCED_FILTERS)
df.setTargetFragment(this@AddEditItemFragment, REQUEST_CHANGE_SCOPE_PURCHASE)
- df.show(fragmentManager!!, ExtraFeaturesIntroductionDialogFragment.FRAGMENT_TAG)
+ df.show(requireFragmentManager(), ExtraFeaturesIntroductionDialogFragment.FRAGMENT_TAG)
}
}
@@ -253,7 +253,7 @@ class AddEditItemFragment : BaseDialogFragment() {
Toast.LENGTH_SHORT).show()
} else {
val idWhere = Expression.equals(Filters._ID, rowId).sql
- resolver?.update(uri, values, idWhere, null)
+ resolver.update(uri, values, idWhere, null)
}
} else {
resolver?.insert(uri, values)
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/filter/BaseFiltersFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/filter/BaseFiltersFragment.kt
index 1c8b797467..b5ca063766 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/filter/BaseFiltersFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/filter/BaseFiltersFragment.kt
@@ -179,7 +179,7 @@ abstract class BaseFiltersFragment : AbsContentListViewFragment {
val selection = Expression.isNull(Columns.Column(Filters.USER_KEY))
- return CursorLoader(activity!!, contentUri, contentColumns, selection.sql, null, sortOrder)
+ return CursorLoader(requireActivity(), contentUri, contentColumns, selection.sql, null, sortOrder)
}
override fun onLoadFinished(loader: Loader, data: Cursor?) {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/filter/BaseFiltersImportFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/filter/BaseFiltersImportFragment.kt
index e8fc94cc89..87988005aa 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/filter/BaseFiltersImportFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/filter/BaseFiltersImportFragment.kt
@@ -130,7 +130,7 @@ abstract class BaseFiltersImportFragment : AbsContentListRecyclerViewFragment?> {
val fromUser = args!!.getBoolean(EXTRA_FROM_USER)
args.remove(EXTRA_FROM_USER)
- return onCreateUsersLoader(context!!, args, fromUser)
+ return onCreateUsersLoader(requireContext(), args, fromUser)
}
override fun onLoaderReset(loader: Loader?>) {
@@ -189,7 +189,7 @@ abstract class BaseFiltersImportFragment : AbsContentListRecyclerViewFragment
if (!extraFeaturesService.isAdvancedFiltersEnabled) {
- ExtraFeaturesIntroductionDialogFragment.show(fragmentManager!!,
+ ExtraFeaturesIntroductionDialogFragment.show(requireFragmentManager(),
feature = ExtraFeaturesService.FEATURE_ADVANCED_FILTERS,
requestCode = REQUEST_PURCHASE_EXTRA_FEATURES)
return@listener false
@@ -246,7 +246,7 @@ abstract class BaseFiltersImportFragment : AbsContentListRecyclerViewFragment {
- return CursorLoader(activity!!, contentUri, contentColumns, null, null, sortOrder)
+ return CursorLoader(requireActivity(), contentUri, contentColumns, null, null, sortOrder)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
@@ -218,7 +218,7 @@ class FilteredUsersFragment : BaseFiltersFragment() {
val am = AccountManager.get(fragment.context)
val account = AccountUtils.getAccountDetails(am, accountKey, true) ?:
throw AccountNotFoundException()
- CreateUserMuteTask.muteUsers(fragment.context!!, account, items)
+ CreateUserMuteTask.muteUsers(fragment.requireContext(), account, items)
}.alwaysUi {
weakThis.get()?.dismissProgressDialog("export_to_muted")
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/filter/FiltersSubscriptionsFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/filter/FiltersSubscriptionsFragment.kt
index 3f24856d17..fffad97521 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/filter/FiltersSubscriptionsFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/filter/FiltersSubscriptionsFragment.kt
@@ -60,7 +60,7 @@ class FiltersSubscriptionsFragment : BaseFragment(), LoaderManager.LoaderCallbac
super.onActivityCreated(savedInstanceState)
setHasOptionsMenu(true)
- adapter = FilterSubscriptionsAdapter(context!!)
+ adapter = FilterSubscriptionsAdapter(requireContext())
listView.adapter = adapter
listView.choiceMode = ListView.CHOICE_MODE_MULTIPLE_MODAL
listView.setMultiChoiceModeListener(this)
@@ -137,7 +137,7 @@ class FiltersSubscriptionsFragment : BaseFragment(), LoaderManager.LoaderCallbac
R.id.refresh -> {
executeAfterFragmentResumed { fragment ->
ProgressDialogFragment.show(fragment.childFragmentManager, FRAGMENT_TAG_RREFRESH_FILTERS)
- val task = RefreshFiltersSubscriptionsTask(fragment.context!!)
+ val task = RefreshFiltersSubscriptionsTask(fragment.requireContext())
val fragmentRef = WeakReference(fragment)
task.callback = {
fragmentRef.get()?.executeAfterFragmentResumed { fragment ->
@@ -157,7 +157,7 @@ class FiltersSubscriptionsFragment : BaseFragment(), LoaderManager.LoaderCallbac
}
override fun onCreateLoader(id: Int, args: Bundle?): Loader {
- val loader = CursorLoader(context!!)
+ val loader = CursorLoader(requireContext())
loader.uri = Filters.Subscriptions.CONTENT_URI
loader.projection = Filters.Subscriptions.COLUMNS
return loader
@@ -233,7 +233,7 @@ class FiltersSubscriptionsFragment : BaseFragment(), LoaderManager.LoaderCallbac
cursor.moveToFirst()
while (!cursor.isAfterLast) {
val subscription = indices.newObject(cursor)
- subscription.instantiateComponent(context!!)?.deleteLocalData()
+ subscription.instantiateComponent(requireContext())?.deleteLocalData()
cursor.moveToNext()
}
}
@@ -284,7 +284,7 @@ class FiltersSubscriptionsFragment : BaseFragment(), LoaderManager.LoaderCallbac
class AddUrlSubscriptionDialogFragment : BaseDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setView(R.layout.dialog_add_filters_subscription)
builder.setPositiveButton(R.string.action_add_filters_subscription) { dialog, _ ->
dialog as AlertDialog
@@ -293,10 +293,10 @@ class FiltersSubscriptionsFragment : BaseFragment(), LoaderManager.LoaderCallbac
val subscription = FiltersSubscription()
subscription.name = editName.text.toString()
subscription.setupUrl(editUrl.text.toString())
- val component = subscription.instantiateComponent(context!!) ?: return@setPositiveButton
+ val component = subscription.instantiateComponent(requireContext()) ?: return@setPositiveButton
component.firstAdded()
val vc = ObjectCursor.valuesCreatorFrom(FiltersSubscription::class.java)
- context!!.contentResolver.insert(Filters.Subscriptions.CONTENT_URI, vc.create(subscription))
+ requireContext().contentResolver.insert(Filters.Subscriptions.CONTENT_URI, vc.create(subscription))
}
builder.setNegativeButton(android.R.string.cancel, null)
val dialog = builder.create()
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/media/ExoPlayerPageFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/media/ExoPlayerPageFragment.kt
index 4ea334cf4b..15ed1c8c87 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/media/ExoPlayerPageFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/media/ExoPlayerPageFragment.kt
@@ -204,9 +204,8 @@ class ExoPlayerPageFragment : MediaViewerFragment(), IBaseFragment= 0) {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/media/ImagePageFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/media/ImagePageFragment.kt
index 4e9da0c537..e2161f0946 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/media/ImagePageFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/media/ImagePageFragment.kt
@@ -24,13 +24,13 @@ import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
-import android.os.Bundle
import com.davemorrissey.labs.subscaleview.ImageSource
import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
import com.davemorrissey.labs.subscaleview.decoder.SkiaImageDecoder
import org.mariotaku.ktextension.nextPowerOf2
import org.mariotaku.mediaviewer.library.CacheDownloadLoader
import org.mariotaku.mediaviewer.library.subsampleimageview.SubsampleImageViewerFragment
+import org.mariotaku.twidere.BuildConfig
import org.mariotaku.twidere.TwidereConstants.*
import org.mariotaku.twidere.activity.MediaViewerActivity
import org.mariotaku.twidere.model.ParcelableMedia
@@ -39,6 +39,9 @@ import org.mariotaku.twidere.util.UriUtils
import org.mariotaku.twidere.util.media.MediaExtra
import java.io.IOException
import java.lang.ref.WeakReference
+import kotlin.math.ceil
+import kotlin.math.max
+import kotlin.math.min
class ImagePageFragment : SubsampleImageViewerFragment() {
@@ -50,7 +53,7 @@ class ImagePageFragment : SubsampleImageViewerFragment() {
get() = arguments?.getParcelable(EXTRA_ACCOUNT_KEY)
private val sizedResultCreator: CacheDownloadLoader.ResultCreator by lazy {
- return@lazy SizedResultCreator(context!!)
+ return@lazy SizedResultCreator(requireContext())
}
private var mediaLoadState: Int = 0
@@ -96,7 +99,7 @@ class ImagePageFragment : SubsampleImageViewerFragment() {
}
override fun getImageSource(data: CacheDownloadLoader.Result): ImageSource {
- assert(data.cacheUri != null)
+ if (BuildConfig.DEBUG && data.cacheUri == null) { error("Assertion failed") }
if (data !is SizedResult) {
return super.getImageSource(data)
}
@@ -108,7 +111,7 @@ class ImagePageFragment : SubsampleImageViewerFragment() {
override fun getPreviewImageSource(data: CacheDownloadLoader.Result): ImageSource? {
if (data !is SizedResult) return null
- assert(data.cacheUri != null)
+ if (BuildConfig.DEBUG && data.cacheUri == null) { error("Assertion failed") }
return ImageSource.uri(UriUtils.appendQueryParameters(data.cacheUri, QUERY_PARAM_PREVIEW, true))
}
@@ -150,9 +153,9 @@ class ImagePageFragment : SubsampleImageViewerFragment() {
val cr = context.contentResolver
decodeBitmap(cr, uri, o)
val dm = context.resources.displayMetrics
- val targetSize = Math.min(1024, Math.max(dm.widthPixels, dm.heightPixels))
- val sizeRatio = Math.ceil(Math.max(o.outHeight, o.outWidth) / targetSize.toDouble())
- o.inSampleSize = Math.max(1.0, sizeRatio).toInt().nextPowerOf2
+ val targetSize = min(1024, max(dm.widthPixels, dm.heightPixels))
+ val sizeRatio = ceil(max(o.outHeight, o.outWidth) / targetSize.toDouble())
+ o.inSampleSize = max(1.0, sizeRatio).toInt().nextPowerOf2
o.inJustDecodeBounds = false
return decodeBitmap(cr, uri, o) ?: throw IOException()
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/media/VideoPageFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/media/VideoPageFragment.kt
index 8edb7e9559..d78104a7d4 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/media/VideoPageFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/media/VideoPageFragment.kt
@@ -61,6 +61,7 @@ import org.mariotaku.twidere.util.promotion.PromotionService
import java.util.*
import java.util.concurrent.TimeUnit
import javax.inject.Inject
+import kotlin.math.roundToInt
class VideoPageFragment : CacheDownloadMediaViewerFragment(), IBaseFragment,
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener,
@@ -85,7 +86,7 @@ class VideoPageFragment : CacheDownloadMediaViewerFragment(), IBaseFragment {
- if (videoView.isPlaying) {
+ pausedByUser = if (videoView.isPlaying) {
videoView.pause()
- pausedByUser = true
+ true
} else {
videoView.start()
- pausedByUser = false
+ false
}
updatePlayerState()
}
@@ -358,7 +359,7 @@ class VideoPageFragment : CacheDownloadMediaViewerFragment(), IBaseFragment {
- return ConversationInfoLoader(context!!, accountKey, conversationId)
+ return ConversationInfoLoader(requireContext(), accountKey, conversationId)
}
override fun onLoaderReset(loader: Loader) {
@@ -299,7 +299,7 @@ class MessageConversationInfoFragment : BaseFragment(), IToolBarSupportFragment,
private fun performDestroyConversation() {
ProgressDialogFragment.show(childFragmentManager, "leave_conversation_progress")
val weakThis = WeakReference(this)
- val task = DestroyConversationTask(context!!, accountKey, conversationId)
+ val task = DestroyConversationTask(requireContext(), accountKey, conversationId)
task.callback = callback@ { succeed ->
val f = weakThis.get() ?: return@callback
f.dismissDialogThen("leave_conversation_progress") {
@@ -315,7 +315,7 @@ class MessageConversationInfoFragment : BaseFragment(), IToolBarSupportFragment,
private fun performClearMessages() {
ProgressDialogFragment.show(childFragmentManager, "clear_messages_progress")
val weakThis = WeakReference(this)
- val task = ClearMessagesTask(context!!, accountKey, conversationId)
+ val task = ClearMessagesTask(requireContext(), accountKey, conversationId)
task.callback = callback@ { succeed ->
val f = weakThis.get() ?: return@callback
f.dismissDialogThen("clear_messages_progress") {
@@ -330,7 +330,7 @@ class MessageConversationInfoFragment : BaseFragment(), IToolBarSupportFragment,
private fun performAddParticipant(user: ParcelableUser) {
ProgressDialogFragment.show(childFragmentManager, "add_participant_progress")
val weakThis = WeakReference(this)
- val task = AddParticipantsTask(context!!, accountKey, conversationId, listOf(user))
+ val task = AddParticipantsTask(requireContext(), accountKey, conversationId, listOf(user))
task.callback = callback@ { succeed ->
val f = weakThis.get() ?: return@callback
f.dismissDialogThen("add_participant_progress") {
@@ -343,7 +343,7 @@ class MessageConversationInfoFragment : BaseFragment(), IToolBarSupportFragment,
private fun performSetNotificationDisabled(disabled: Boolean) {
ProgressDialogFragment.show(childFragmentManager, "set_notifications_disabled_progress")
val weakThis = WeakReference(this)
- val task = SetConversationNotificationDisabledTask(context!!, accountKey, conversationId, disabled)
+ val task = SetConversationNotificationDisabledTask(requireContext(), accountKey, conversationId, disabled)
task.callback = callback@ { _ ->
val f = weakThis.get() ?: return@callback
f.dismissDialogThen("set_notifications_disabled_progress") {
@@ -457,7 +457,7 @@ class MessageConversationInfoFragment : BaseFragment(), IToolBarSupportFragment,
val fragment = weakThis.get() ?: throw InterruptedException()
val account = AccountUtils.getAccountDetails(AccountManager.get(fragment.context),
accountKey, true) ?: throw MicroBlogException("No account")
- val microBlog = account.newMicroBlogInstance(fragment.context!!, cls = MicroBlog::class.java)
+ val microBlog = account.newMicroBlogInstance(fragment.requireContext(), cls = MicroBlog::class.java)
return@task updateAction(fragment, account, microBlog)
}.then { result ->
val fragment = weakThis.get() ?: throw InterruptedException()
@@ -583,26 +583,24 @@ class MessageConversationInfoFragment : BaseFragment(), IToolBarSupportFragment,
}
override fun getItemViewType(position: Int): Int {
- val countIndex = itemCounts.getItemCountIndex(position)
- when (countIndex) {
- ITEM_INDEX_TOP_SPACE -> return VIEW_TYPE_TOP_SPACE
- ITEM_INDEX_HEADER -> return VIEW_TYPE_HEADER
- ITEM_INDEX_ITEM -> return VIEW_TYPE_USER
- ITEM_INDEX_ADD_USER -> return VIEW_TYPE_ADD_USER
- ITEM_INDEX_SPACE -> return VIEW_TYPE_BOTTOM_SPACE
+ return when (val countIndex = itemCounts.getItemCountIndex(position)) {
+ ITEM_INDEX_TOP_SPACE -> VIEW_TYPE_TOP_SPACE
+ ITEM_INDEX_HEADER -> VIEW_TYPE_HEADER
+ ITEM_INDEX_ITEM -> VIEW_TYPE_USER
+ ITEM_INDEX_ADD_USER -> VIEW_TYPE_ADD_USER
+ ITEM_INDEX_SPACE -> VIEW_TYPE_BOTTOM_SPACE
else -> throw UnsupportedCountIndexException(countIndex, position)
}
}
override fun getItemId(position: Int): Long {
- val countIndex = itemCounts.getItemCountIndex(position)
- when (countIndex) {
+ return when (val countIndex = itemCounts.getItemCountIndex(position)) {
ITEM_INDEX_ITEM -> {
val user = getUser(position)!!
- return (countIndex.toLong() shl 32) or user.hashCode().toLong()
+ (countIndex.toLong() shl 32) or user.hashCode().toLong()
}
else -> {
- return (countIndex.toLong() shl 32) or getItemViewType(position).toLong()
+ (countIndex.toLong() shl 32) or getItemViewType(position).toLong()
}
}
}
@@ -736,7 +734,7 @@ class MessageConversationInfoFragment : BaseFragment(), IToolBarSupportFragment,
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val actions = arrayOf(Action(getString(R.string.action_edit_conversation_name), "name"),
Action(getString(R.string.action_edit_conversation_avatar), "avatar"))
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setItems(actions.mapToArray(Action::title)) { _, which ->
val action = actions[which]
(parentFragment as MessageConversationInfoFragment).openEditAction(action.type)
@@ -752,7 +750,7 @@ class MessageConversationInfoFragment : BaseFragment(), IToolBarSupportFragment,
class EditNameDialogFragment : BaseDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setView(R.layout.dialog_edit_conversation_name)
builder.setNegativeButton(android.R.string.cancel, null)
builder.setPositiveButton(android.R.string.ok) { dialog, _ ->
@@ -768,7 +766,7 @@ class MessageConversationInfoFragment : BaseFragment(), IToolBarSupportFragment,
class DestroyConversationConfirmDialogFragment : BaseDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setMessage(R.string.message_destroy_conversation_confirm)
builder.setPositiveButton(R.string.action_leave_conversation) { _, _ ->
(parentFragment as MessageConversationInfoFragment).performDestroyConversation()
@@ -783,7 +781,7 @@ class MessageConversationInfoFragment : BaseFragment(), IToolBarSupportFragment,
class ClearMessagesConfirmDialogFragment : BaseDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setMessage(R.string.message_clear_messages_confirm)
builder.setPositiveButton(R.string.action_clear_messages) { _, _ ->
(parentFragment as MessageConversationInfoFragment).performClearMessages()
@@ -805,8 +803,7 @@ class MessageConversationInfoFragment : BaseFragment(), IToolBarSupportFragment,
val position = parent.getChildLayoutPosition(view)
if (position < 0) return
val itemCounts = adapter.itemCounts
- val countIndex = itemCounts.getItemCountIndex(position)
- when (countIndex) {
+ when (val countIndex = itemCounts.getItemCountIndex(position)) {
ConversationInfoAdapter.ITEM_INDEX_TOP_SPACE,
ConversationInfoAdapter.ITEM_INDEX_SPACE,
ConversationInfoAdapter.ITEM_INDEX_ADD_USER -> {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/message/MessageNewConversationFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/message/MessageNewConversationFragment.kt
index 25480b3189..43d4d1eec9 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/message/MessageNewConversationFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/message/MessageNewConversationFragment.kt
@@ -61,6 +61,7 @@ import org.mariotaku.twidere.text.MarkForDeleteSpan
import org.mariotaku.twidere.util.IntentUtils
import org.mariotaku.twidere.util.view.SimpleTextWatcher
import java.lang.ref.WeakReference
+import kotlin.math.roundToInt
/**
* Created by mariotaku on 2017/2/15.
@@ -207,7 +208,7 @@ class MessageNewConversationFragment : BaseFragment(), LoaderCallbacks?>) {
@@ -238,7 +239,7 @@ class MessageNewConversationFragment : BaseFragment(), LoaderCallbacks if (data != null) {
val mediaUris = MediaPickerActivity.getMediaUris(data)
val types = data.getBundleExtra(MediaPickerActivity.EXTRA_EXTRAS)?.getIntArray(EXTRA_TYPES)
- TaskStarter.execute(AddMediaTask(this, mediaUris, types, false, false))
+ TaskStarter.execute(AddMediaTask(this, mediaUris, types,
+ copySrc = false,
+ deleteSrc = false
+ ))
}
RESULT_SEARCH_GIF -> {
val provider = gifShareProvider ?: return
@@ -278,7 +281,7 @@ class MessagesConversationFragment : AbsContentListRecyclerViewFragment?> {
- return ConversationLoader(context!!, accountKey, conversationId)
+ return ConversationLoader(requireContext(), accountKey, conversationId)
}
override fun onLoadFinished(loader: Loader?>, data: List?) {
@@ -319,7 +322,7 @@ class MessagesConversationFragment : AbsContentListRecyclerViewFragment?) -> Unit)?>(fragment.context!!, sources, types, copySrc, deleteSrc) {
+ ) : AbsAddMediaTask<((List?) -> Unit)?>(fragment.requireContext(), sources, types, copySrc, deleteSrc) {
private val fragmentRef = WeakReference(fragment)
@@ -581,7 +586,7 @@ class MessagesConversationFragment : AbsContentListRecyclerViewFragment
- ) : AbsDeleteMediaTask(fragment.context!!,
+ ) : AbsDeleteMediaTask(fragment.requireContext(),
media.mapToArray { Uri.parse(it.uri) }) {
init {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/message/MessagesEntriesFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/message/MessagesEntriesFragment.kt
index 84ce6f35c6..fa171ce097 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/message/MessagesEntriesFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/message/MessagesEntriesFragment.kt
@@ -74,7 +74,7 @@ class MessagesEntriesFragment : AbsContentListRecyclerViewFragment by lazy {
- Utils.getAccountKeys(context!!, arguments) ?: DataStoreUtils.getActivatedAccountKeys(context!!)
+ Utils.getAccountKeys(requireContext(), arguments) ?: DataStoreUtils.getActivatedAccountKeys(requireContext())
}
private val errorInfoKey: String = ErrorInfoStore.KEY_DIRECT_MESSAGES
@@ -157,7 +157,7 @@ class MessagesEntriesFragment : AbsContentListRecyclerViewFragment = this@MessagesEntriesFragment.accountKeys
})
return true
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/search/MastodonSearchFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/search/MastodonSearchFragment.kt
index 5379df3523..da50fc7388 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/search/MastodonSearchFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/search/MastodonSearchFragment.kt
@@ -35,6 +35,6 @@ class MastodonSearchFragment : ItemsListFragment() {
get() = arguments?.getString(EXTRA_QUERY)!!
override fun onCreateLoader(id: Int, args: Bundle?): Loader?> {
- return MastodonSearchLoader(context!!, accountKey, query)
+ return MastodonSearchLoader(requireContext(), accountKey, query)
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/AbsSimpleStatusOperationDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/AbsSimpleStatusOperationDialogFragment.kt
index 4eee5bed08..84851c11c0 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/AbsSimpleStatusOperationDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/AbsSimpleStatusOperationDialogFragment.kt
@@ -46,7 +46,7 @@ abstract class AbsSimpleStatusOperationDialogFragment : BaseDialogFragment(), Di
}
final override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setTitle(title)
builder.setMessage(message)
builder.setPositiveButton(android.R.string.ok, this)
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/AbsStatusDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/AbsStatusDialogFragment.kt
index 4ad04e48c0..9ba9774185 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/AbsStatusDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/AbsStatusDialogFragment.kt
@@ -68,19 +68,19 @@ abstract class AbsStatusDialogFragment : BaseDialogFragment() {
private lateinit var adapter: DummyItemAdapter
final override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = Builder(context!!)
+ val builder = Builder(requireContext())
val accountKey = this.accountKey
builder.setupAlertDialog()
- adapter = DummyItemAdapter(context!!, requestManager = requestManager)
+ adapter = DummyItemAdapter(requireContext(), requestManager = requestManager)
adapter.showCardActions = false
adapter.showCardNumbers = false
adapter.showAccountsColor = true
val dialog = builder.create()
dialog.onShow {
- val context = it.context ?: return@onShow
+ val context = it.context
it.applyTheme()
val am = AccountManager.get(context)
@@ -97,7 +97,7 @@ abstract class AbsStatusDialogFragment : BaseDialogFragment() {
showStatus(weakHolder.get()!!, extraStatus, details, savedInstanceState)
} else promiseOnUi {
weakThis.get()?.showProgress()
- } and AbsStatusDialogFragment.showStatus(context, details, statusId, extraStatus).successUi { status ->
+ } and showStatus(context, details, statusId, extraStatus).successUi { status ->
val holder = weakHolder.get() ?: return@successUi
weakThis.get()?.showStatus(holder, status, details, savedInstanceState)
}.failUi {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/BlockStatusUsersDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/BlockStatusUsersDialogFragment.kt
index 4a2cd6d4a7..7bea40ecaa 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/BlockStatusUsersDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/BlockStatusUsersDialogFragment.kt
@@ -42,7 +42,7 @@ class BlockStatusUsersDialogFragment : BaseDialogFragment() {
private val status: ParcelableStatus get() = arguments?.getParcelable(EXTRA_STATUS)!!
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
val referencedUsers = status.referencedUsers
val nameFirst = preferences[nameFirstKey]
val displayNames = referencedUsers.map {
@@ -50,7 +50,7 @@ class BlockStatusUsersDialogFragment : BaseDialogFragment() {
}.toTypedArray()
builder.setTitle(R.string.action_status_block_users)
builder.setItems(displayNames) { _, which ->
- CreateUserBlockDialogFragment.show(fragmentManager!!, referencedUsers[which])
+ CreateUserBlockDialogFragment.show(requireFragmentManager(), referencedUsers[which])
}
val dialog = builder.create()
dialog.applyOnShow { applyTheme() }
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/DestroyStatusDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/DestroyStatusDialogFragment.kt
index 4b7542f0fb..07f5a44d9a 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/DestroyStatusDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/DestroyStatusDialogFragment.kt
@@ -38,7 +38,7 @@ class DestroyStatusDialogFragment : AbsSimpleStatusOperationDialogFragment() {
companion object {
- val FRAGMENT_TAG = "destroy_status"
+ const val FRAGMENT_TAG = "destroy_status"
fun show(fm: FragmentManager, status: ParcelableStatus): DestroyStatusDialogFragment {
val args = Bundle()
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/FavoriteConfirmDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/FavoriteConfirmDialogFragment.kt
index 39c1defe69..00ada35478 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/FavoriteConfirmDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/FavoriteConfirmDialogFragment.kt
@@ -103,7 +103,7 @@ class FavoriteConfirmDialogFragment : AbsStatusDialogFragment() {
companion object {
- val FRAGMENT_TAG = "favorite_confirm"
+ const val FRAGMENT_TAG = "favorite_confirm"
fun show(fm: FragmentManager, accountKey: UserKey, statusId: String,
status: ParcelableStatus? = null): FavoriteConfirmDialogFragment {
@@ -113,7 +113,7 @@ class FavoriteConfirmDialogFragment : AbsStatusDialogFragment() {
this[EXTRA_STATUS_ID] = statusId
this[EXTRA_STATUS] = status
}
- f.show(fm, FavoriteConfirmDialogFragment.FRAGMENT_TAG)
+ f.show(fm, FRAGMENT_TAG)
return f
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/MuteStatusUsersDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/MuteStatusUsersDialogFragment.kt
index 1dad27ccc2..d93d6306c6 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/MuteStatusUsersDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/MuteStatusUsersDialogFragment.kt
@@ -42,7 +42,7 @@ class MuteStatusUsersDialogFragment : BaseDialogFragment() {
private val status: ParcelableStatus get() = arguments?.getParcelable(EXTRA_STATUS)!!
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
val referencedUsers = status.referencedUsers
val nameFirst = preferences[nameFirstKey]
val displayNames = referencedUsers.map {
@@ -50,7 +50,7 @@ class MuteStatusUsersDialogFragment : BaseDialogFragment() {
}.toTypedArray()
builder.setTitle(R.string.action_status_mute_users)
builder.setItems(displayNames) { _, which ->
- CreateUserMuteDialogFragment.show(fragmentManager!!, referencedUsers[which])
+ CreateUserMuteDialogFragment.show(requireFragmentManager(), referencedUsers[which])
}
val dialog = builder.create()
dialog.onShow { it.applyTheme() }
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/PinStatusDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/PinStatusDialogFragment.kt
index 6ae94d09bf..112aa4fea0 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/PinStatusDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/PinStatusDialogFragment.kt
@@ -35,13 +35,13 @@ class PinStatusDialogFragment : AbsSimpleStatusOperationDialogFragment() {
get() = getString(R.string.message_pin_status_confirm)
override fun onPerformAction(status: ParcelableStatus) {
- val task = PinStatusTask(context!!, status.account_key, status.id)
+ val task = PinStatusTask(requireContext(), status.account_key, status.id)
TaskStarter.execute(task)
}
companion object {
- val FRAGMENT_TAG = "pin_status"
+ const val FRAGMENT_TAG = "pin_status"
fun show(fm: FragmentManager, status: ParcelableStatus): PinStatusDialogFragment {
val args = Bundle()
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/RetweetQuoteDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/RetweetQuoteDialogFragment.kt
index 3e0848743f..62e3182ef1 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/RetweetQuoteDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/RetweetQuoteDialogFragment.kt
@@ -58,6 +58,7 @@ import org.mariotaku.twidere.util.view.SimpleTextWatcher
import org.mariotaku.twidere.view.ComposeEditText
import org.mariotaku.twidere.view.StatusTextCountView
import java.util.*
+import kotlin.math.max
/**
* Asks user to retweet/quote a status.
@@ -228,8 +229,9 @@ class RetweetQuoteDialogFragment : AbsStatusDialogFragment() {
update.repost_status_id = status.quoted_id
}
if (FanfouValidator.calculateLength(commentText) > FanfouValidator.textLimit) {
- commentText = commentText.substring(0, Math.max(FanfouValidator.textLimit,
- editingComment.length))
+ commentText = commentText.substring(0, max(FanfouValidator.textLimit,
+ editingComment.length)
+ )
}
}
else -> {
@@ -316,7 +318,7 @@ class RetweetQuoteDialogFragment : AbsStatusDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val context = activity
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setMessage(R.string.quote_protected_status_warning_message)
builder.setPositiveButton(R.string.send_anyway, this)
builder.setNegativeButton(android.R.string.cancel, null)
@@ -344,7 +346,7 @@ class RetweetQuoteDialogFragment : AbsStatusDialogFragment() {
companion object {
private const val FRAGMENT_TAG = "retweet_quote"
- private val showProtectedConfirm = false
+ private const val showProtectedConfirm = false
fun show(fm: FragmentManager, accountKey: UserKey, statusId: String,
status: ParcelableStatus? = null, text: String? = null):
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/StatusFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/StatusFragment.kt
index 6eaa4319b8..8a71d837f4 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/StatusFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/StatusFragment.kt
@@ -107,6 +107,8 @@ import org.mariotaku.twidere.view.holder.iface.IStatusViewHolder
import org.mariotaku.twidere.view.holder.iface.IStatusViewHolder.StatusClickListener
import org.mariotaku.yandex.YandexAPIFactory
import java.lang.ref.WeakReference
+import kotlin.math.max
+import kotlin.math.min
/**
* Displays status details
@@ -149,7 +151,7 @@ class StatusFragment : BaseFragment(), LoaderCallbacks(EXTRA_ACCOUNT_KEY)
val statusId = fragmentArgs.getString(EXTRA_STATUS_ID)
- return ParcelableStatusLoader(activity!!, false, fragmentArgs, accountKey, statusId)
+ return ParcelableStatusLoader(requireActivity(), false, fragmentArgs, accountKey, statusId)
}
@@ -640,7 +642,7 @@ class StatusFragment : BaseFragment(), LoaderCallbacks
@@ -648,7 +650,7 @@ class StatusFragment : BaseFragment(), LoaderCallbacks(fragment.context!!, status.account_key) {
+ AbsAccountRequestTask(fragment.requireContext(), status.account_key) {
private val weakFragment = WeakReference(fragment)
@@ -700,15 +702,15 @@ class StatusFragment : BaseFragment(), LoaderCallbacks 0) {
@@ -861,7 +863,7 @@ class StatusFragment : BaseFragment(), LoaderCallbacks 0) {
- return Math.max((firstPosition - skippedCount) * 100 - top * 100 / height, 0)
+ return max((firstPosition - skippedCount) * 100 - top * 100 / height, 0)
}
} else {
val count = validScrollItemCount
@@ -888,7 +890,7 @@ class StatusFragment : BaseFragment(), LoaderCallbacks= statusAdapter.itemCount || childPos < 0) return false
- val itemType = statusAdapter.getItemType(childPos)
- when (itemType) {
+ when (statusAdapter.getItemType(childPos)) {
StatusDetailsAdapter.ITEM_IDX_REPLY_LOAD_MORE, StatusDetailsAdapter.ITEM_IDX_REPLY_ERROR,
StatusDetailsAdapter.ITEM_IDX_SPACE -> return false
}
@@ -956,12 +957,12 @@ class StatusFragment : BaseFragment(), LoaderCallbacks(EXTRA_LANGUAGES)?.sortedArrayWith(LanguageComparator()) ?: emptyArray()
val selectedLanguage = preferences[translationDestinationKey] ?: arguments?.getString(EXTRA_SELECTED_LANGUAGE)
val selectedIndex = languages.indexOfFirst { selectedLanguage == it.code }
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/UnpinStatusDialogFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/UnpinStatusDialogFragment.kt
index 49171f0215..0ad99ddcc5 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/UnpinStatusDialogFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/status/UnpinStatusDialogFragment.kt
@@ -35,13 +35,13 @@ class UnpinStatusDialogFragment : AbsSimpleStatusOperationDialogFragment() {
get() = getString(R.string.message_unpin_status_confirm)
override fun onPerformAction(status: ParcelableStatus) {
- val task = UnpinStatusTask(context!!, status.account_key, status.id)
+ val task = UnpinStatusTask(requireContext(), status.account_key, status.id)
TaskStarter.execute(task)
}
companion object {
- val FRAGMENT_TAG = "unpin_status"
+ const val FRAGMENT_TAG = "unpin_status"
fun show(fm: FragmentManager, status: ParcelableStatus): UnpinStatusDialogFragment {
val args = Bundle()
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/GroupTimelineFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/GroupTimelineFragment.kt
index 1afee2421e..bbff2fd2ec 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/GroupTimelineFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/GroupTimelineFragment.kt
@@ -49,12 +49,16 @@ class GroupTimelineFragment : ParcelableStatusesFragment() {
val result = ArrayList()
result.add(AUTHORITY_GROUP_TIMELINE)
result.add("account=$accountKey")
- if (groupId != null) {
- result.add("group_id=$groupId")
- } else if (groupName != null) {
- result.add("group_name=$groupName")
- } else {
- return null
+ when {
+ groupId != null -> {
+ result.add("group_id=$groupId")
+ }
+ groupName != null -> {
+ result.add("group_name=$groupName")
+ }
+ else -> {
+ return null
+ }
}
return result.toTypedArray()
}
@@ -115,7 +119,7 @@ class GroupTimelineFragment : ParcelableStatusesFragment() {
val groupName = args.getString(EXTRA_GROUP_NAME)
val tabPosition = args.getInt(EXTRA_TAB_POSITION, -1)
val loadingMore = args.getBoolean(EXTRA_LOADING_MORE, false)
- return GroupTimelineLoader(activity!!, accountKey, groupId, groupName, adapterData,
+ return GroupTimelineLoader(requireActivity(), accountKey, groupId, groupName, adapterData,
savedStatusesFileArgs, tabPosition, fromUser, loadingMore)
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/MediaStatusesSearchFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/MediaStatusesSearchFragment.kt
index d1a9d17672..6f556dea17 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/MediaStatusesSearchFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/MediaStatusesSearchFragment.kt
@@ -41,7 +41,7 @@ class MediaStatusesSearchFragment : AbsMediaStatusesFragment() {
val tabPosition = args.getInt(EXTRA_TAB_POSITION, -1)
val makeGap = args.getBoolean(EXTRA_MAKE_GAP, true)
val loadingMore = args.getBoolean(EXTRA_LOADING_MORE, false)
- return MediaStatusesSearchLoader(activity!!, accountKey, query, adapter.getData(), null, tabPosition,
+ return MediaStatusesSearchLoader(requireActivity(), accountKey, query, adapter.getData(), null, tabPosition,
fromUser, makeGap, loadingMore)
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/StatusesSearchFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/StatusesSearchFragment.kt
index 90dc609dfc..83e9accb2f 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/StatusesSearchFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/StatusesSearchFragment.kt
@@ -75,12 +75,12 @@ open class StatusesSearchFragment : ParcelableStatusesFragment() {
Loader?> {
refreshing = true
val accountKey = Utils.getAccountKey(context, args)
- val query = arguments!!.getString(EXTRA_QUERY)
- val local = arguments!!.getBoolean(EXTRA_LOCAL, false)
- val tabPosition = arguments!!.getInt(EXTRA_TAB_POSITION, -1)
+ val query = requireArguments().getString(EXTRA_QUERY)
+ val local = requireArguments().getBoolean(EXTRA_LOCAL, false)
+ val tabPosition = requireArguments().getInt(EXTRA_TAB_POSITION, -1)
val makeGap = args.getBoolean(EXTRA_MAKE_GAP, true)
val loadingMore = args.getBoolean(EXTRA_LOADING_MORE, false)
- return TweetSearchLoader(activity!!, accountKey, query, adapterData, savedStatusesFileArgs,
+ return TweetSearchLoader(requireActivity(), accountKey, query, adapterData, savedStatusesFileArgs,
tabPosition, fromUser, makeGap, local, loadingMore)
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/UserFavoritesFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/UserFavoritesFragment.kt
index 4e3429493a..d2bd819950 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/UserFavoritesFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/UserFavoritesFragment.kt
@@ -46,12 +46,16 @@ class UserFavoritesFragment : ParcelableStatusesFragment() {
val result = ArrayList()
result.add(AUTHORITY_USER_FAVORITES)
result.add("account=$accountKey")
- if (userKey != null) {
- result.add("user_id=$userKey")
- } else if (screenName != null) {
- result.add("screen_name=$screenName")
- } else {
- return null
+ when {
+ userKey != null -> {
+ result.add("user_id=$userKey")
+ }
+ screenName != null -> {
+ result.add("screen_name=$screenName")
+ }
+ else -> {
+ return null
+ }
}
return result.toTypedArray()
}
@@ -65,12 +69,16 @@ class UserFavoritesFragment : ParcelableStatusesFragment() {
val userKey = arguments.getParcelable(EXTRA_USER_KEY)
val screenName = arguments.getString(EXTRA_SCREEN_NAME)
- if (userKey != null) {
- sb.append(userKey)
- } else if (screenName != null) {
- sb.append(screenName)
- } else {
- return null
+ when {
+ userKey != null -> {
+ sb.append(userKey)
+ }
+ screenName != null -> {
+ sb.append(screenName)
+ }
+ else -> {
+ return null
+ }
}
return sb.toString()
}
@@ -90,7 +98,7 @@ class UserFavoritesFragment : ParcelableStatusesFragment() {
override fun notifyFavoriteTask(event: FavoriteTaskEvent) {
if (event.action == FavoriteTaskEvent.Action.DESTROY && event.isSucceeded) {
event.status?.let { status ->
- val args = arguments!!
+ val args = requireArguments()
val userKey = args.getParcelable(EXTRA_USER_KEY)
if (status.account_key == userKey) {
removeStatus(event.statusId)
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/UserListTimelineFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/UserListTimelineFragment.kt
index 65073c1ba1..f29290541b 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/UserListTimelineFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/UserListTimelineFragment.kt
@@ -49,17 +49,21 @@ class UserListTimelineFragment : ParcelableStatusesFragment() {
val result = ArrayList()
result.add(TwidereConstants.AUTHORITY_USER_LIST_TIMELINE)
result.add("account=$accountKey")
- if (listId != null) {
- result.add("list_id=$listId")
- } else if (listName != null) {
- if (userKey != null) {
- result.add("user_id=$userKey")
- } else if (screenName != null) {
- result.add("screen_name=$screenName")
+ when {
+ listId != null -> {
+ result.add("list_id=$listId")
+ }
+ listName != null -> {
+ if (userKey != null) {
+ result.add("user_id=$userKey")
+ } else if (screenName != null) {
+ result.add("screen_name=$screenName")
+ }
+ return null
+ }
+ else -> {
+ return null
}
- return null
- } else {
- return null
}
return result.toTypedArray()
}
@@ -72,22 +76,30 @@ class UserListTimelineFragment : ParcelableStatusesFragment() {
if (tabPosition < 0) return null
val listId = arguments.getString(EXTRA_LIST_ID)
val listName = arguments.getString(EXTRA_LIST_NAME)
- if (listId != null) {
- sb.append(listId)
- } else if (listName != null) {
- val userKey = arguments.getParcelable(EXTRA_USER_KEY)
- val screenName = arguments.getString(EXTRA_SCREEN_NAME)
- if (userKey != null) {
- sb.append(userKey)
- } else if (screenName != null) {
- sb.append(screenName)
- } else {
+ when {
+ listId != null -> {
+ sb.append(listId)
+ }
+ listName != null -> {
+ val userKey = arguments.getParcelable(EXTRA_USER_KEY)
+ val screenName = arguments.getString(EXTRA_SCREEN_NAME)
+ when {
+ userKey != null -> {
+ sb.append(userKey)
+ }
+ screenName != null -> {
+ sb.append(screenName)
+ }
+ else -> {
+ return null
+ }
+ }
+ sb.append('_')
+ sb.append(listName)
+ }
+ else -> {
return null
}
- sb.append('_')
- sb.append(listName)
- } else {
- return null
}
return sb.toString()
}
@@ -103,7 +115,7 @@ class UserListTimelineFragment : ParcelableStatusesFragment() {
val screenName = args.getString(EXTRA_SCREEN_NAME)
val tabPosition = args.getInt(EXTRA_TAB_POSITION, -1)
val loadingMore = args.getBoolean(EXTRA_LOADING_MORE, false)
- return UserListTimelineLoader(activity!!, accountKey, listId, userKey, screenName, listName,
+ return UserListTimelineLoader(requireActivity(), accountKey, listId, userKey, screenName, listName,
adapterData, savedStatusesFileArgs, tabPosition, fromUser, loadingMore, extras)
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/UserMentionsFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/UserMentionsFragment.kt
index cdae7b07b7..2219ecba73 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/UserMentionsFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/UserMentionsFragment.kt
@@ -52,7 +52,7 @@ class UserMentionsFragment : StatusesSearchFragment() {
val tabPosition = args.getInt(EXTRA_TAB_POSITION, -1)
val makeGap = args.getBoolean(EXTRA_MAKE_GAP, true)
val loadingMore = args.getBoolean(EXTRA_LOADING_MORE, false)
- return UserMentionsLoader(activity!!, accountKey, screenName, adapterData,
+ return UserMentionsLoader(requireActivity(), accountKey, screenName, adapterData,
savedStatusesFileArgs, tabPosition, fromUser, makeGap, false, loadingMore)
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/UserTimelineFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/UserTimelineFragment.kt
index 0d1d93969a..328d02dd03 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/UserTimelineFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/statuses/UserTimelineFragment.kt
@@ -61,12 +61,16 @@ class UserTimelineFragment : ParcelableStatusesFragment() {
val result = ArrayList()
result.add(AUTHORITY_USER_TIMELINE)
result.add("account=$accountKey")
- if (userKey != null) {
- result.add("user_id=$userKey")
- } else if (screenName != null) {
- result.add("screen_name=$screenName")
- } else {
- return null
+ when {
+ userKey != null -> {
+ result.add("user_id=$userKey")
+ }
+ screenName != null -> {
+ result.add("screen_name=$screenName")
+ }
+ else -> {
+ return null
+ }
}
(timelineFilter as? UserTimelineFilter)?.let {
if (it.isIncludeReplies) {
@@ -87,12 +91,16 @@ class UserTimelineFragment : ParcelableStatusesFragment() {
val userKey = arguments.getParcelable(EXTRA_USER_KEY)
val screenName = arguments.getString(EXTRA_SCREEN_NAME)
- if (userKey != null) {
- sb.append(userKey)
- } else if (screenName != null) {
- sb.append(screenName)
- } else {
- return null
+ when {
+ userKey != null -> {
+ sb.append(userKey)
+ }
+ screenName != null -> {
+ sb.append(screenName)
+ }
+ else -> {
+ return null
+ }
}
return sb.toString()
}
@@ -149,7 +157,7 @@ class UserTimelineFragment : ParcelableStatusesFragment() {
class UserTimelineFilterDialogFragment : BaseDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
val values = resources.getStringArray(R.array.values_user_timeline_filter)
val checkedItems = BooleanArray(values.size) {
val filter = preferences[userTimelineFilterKey]
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/sync/SyncSettingsFragment.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/sync/SyncSettingsFragment.kt
index 771293b5e4..7466f1a0ba 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/sync/SyncSettingsFragment.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/fragment/sync/SyncSettingsFragment.kt
@@ -94,9 +94,9 @@ class SyncSettingsFragment : BasePreferenceFragment() {
class DisconnectSyncConfirmDialogFragment : BaseDialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
val providerInfo = kPreferences[dataSyncProviderInfoKey]!!
- val entry = DataSyncProvider.Factory.getProviderEntry(context!!, providerInfo.type)!!
+ val entry = DataSyncProvider.Factory.getProviderEntry(requireContext(), providerInfo.type)!!
builder.setMessage(getString(R.string.message_sync_disconnect_from_name_confirm, entry.name))
builder.setPositiveButton(R.string.action_sync_disconnect) { _, _ ->
(parentFragment as SyncSettingsFragment).cleanupAndDisconnect()
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/graphic/WindowBackgroundDrawable.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/graphic/WindowBackgroundDrawable.kt
index 10c61e5dab..70dd94b44f 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/graphic/WindowBackgroundDrawable.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/graphic/WindowBackgroundDrawable.kt
@@ -45,7 +45,7 @@ class WindowBackgroundDrawable(private val color: Int) : Drawable() {
return PixelFormat.TRANSLUCENT
}
- override fun getConstantState(): Drawable.ConstantState {
+ override fun getConstantState(): ConstantState {
return State(color)
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/ExtensionsListLoader.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/ExtensionsListLoader.kt
index 57c477d792..b00771bc49 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/ExtensionsListLoader.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/ExtensionsListLoader.kt
@@ -111,7 +111,7 @@ class ExtensionsListLoader(
constructor(info: ApplicationInfo, pm: PackageManager) : this(
info.packageName,
- info.loadLabel(pm) ?: info.packageName,
+ info.loadLabel(pm),
info.loadDescription(pm),
info.loadIcon(pm),
info.metaData?.getString(METADATA_KEY_EXTENSION_PERMISSIONS)?.split('|')?.filterNot(String::isEmpty)?.toTypedArray(),
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/ParcelableStatusLoader.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/ParcelableStatusLoader.kt
index 18d0246636..4cf0abdc66 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/ParcelableStatusLoader.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/ParcelableStatusLoader.kt
@@ -74,12 +74,12 @@ class ParcelableStatusLoader(
}
}
if (details == null) return SingleResponse(MicroBlogException("No account"))
- try {
+ return try {
val status = DataStoreUtils.findStatus(context, accountKey, statusId)
status.updateExtraInformation(details)
val response = SingleResponse(status)
response.extras[EXTRA_ACCOUNT] = details
- return response
+ response
} catch (e: MicroBlogException) {
if (e.errorCode == ErrorInfo.STATUS_NOT_FOUND) {
// Delete all deleted status
@@ -87,7 +87,7 @@ class ParcelableStatusLoader(
DataStoreUtils.deleteStatus(cr, accountKey, statusId, null)
cr.deleteActivityStatus(accountKey, statusId, null)
}
- return SingleResponse(e)
+ SingleResponse(e)
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/AbsRequestStatusesLoader.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/AbsRequestStatusesLoader.kt
index 479a4f482b..c0cb504f71 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/AbsRequestStatusesLoader.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/AbsRequestStatusesLoader.kt
@@ -50,6 +50,7 @@ import java.io.IOException
import java.util.*
import java.util.concurrent.atomic.AtomicReference
import javax.inject.Inject
+import kotlin.math.min
abstract class AbsRequestStatusesLoader(
context: Context,
@@ -197,8 +198,7 @@ abstract class AbsRequestStatusesLoader(
}
protected open fun List.foundInPagination(): Boolean {
- val pagination = this@AbsRequestStatusesLoader.pagination
- return when (pagination) {
+ return when (val pagination = this@AbsRequestStatusesLoader.pagination) {
is SinceMaxPagination -> return any { it.id == pagination.maxId }
else -> false
}
@@ -212,7 +212,7 @@ abstract class AbsRequestStatusesLoader(
if (key == null || data == null) return
val databaseItemLimit = preferences[loadItemLimitKey]
try {
- val statuses = data.subList(0, Math.min(databaseItemLimit, data.size))
+ val statuses = data.subList(0, min(databaseItemLimit, data.size))
jsonCache.saveList(key, statuses, ParcelableStatus::class.java)
} catch (e: Exception) {
// Ignore
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/MediaTimelineLoader.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/MediaTimelineLoader.kt
index f432a39b45..bc76087fec 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/MediaTimelineLoader.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/MediaTimelineLoader.kt
@@ -60,11 +60,11 @@ class MediaTimelineLoader(
private val isMyTimeline: Boolean
get() {
val accountKey = accountKey ?: return false
- if (userKey != null) {
- return userKey.maybeEquals(accountKey)
+ return if (userKey != null) {
+ userKey.maybeEquals(accountKey)
} else {
val accountScreenName = DataStoreUtils.getAccountScreenName(context, accountKey)
- return accountScreenName != null && accountScreenName.equals(screenName, ignoreCase = true)
+ accountScreenName != null && accountScreenName.equals(screenName, ignoreCase = true)
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/NetworkPublicTimelineLoader.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/NetworkPublicTimelineLoader.kt
index 37477bdc48..b9f33dafb1 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/NetworkPublicTimelineLoader.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/NetworkPublicTimelineLoader.kt
@@ -50,16 +50,16 @@ class NetworkPublicTimelineLoader(
@Throws(MicroBlogException::class)
override fun getStatuses(account: AccountDetails, paging: Paging): PaginatedList {
- when (account.type) {
+ return when (account.type) {
AccountType.MASTODON -> {
val mastodon = account.newMicroBlogInstance(context, Mastodon::class.java)
- return mastodon.getPublicTimeline(paging, false).mapToPaginated {
+ mastodon.getPublicTimeline(paging, false).mapToPaginated {
it.toParcelable(account)
}
}
AccountType.STATUSNET -> {
val microBlog = account.newMicroBlogInstance(context, MicroBlog::class.java)
- return microBlog.getNetworkPublicTimeline(paging).mapMicroBlogToPaginated {
+ microBlog.getNetworkPublicTimeline(paging).mapMicroBlogToPaginated {
it.toParcelable(account, profileImageSize = profileImageSize)
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/PublicTimelineLoader.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/PublicTimelineLoader.kt
index c92e195038..69ae9af5bd 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/PublicTimelineLoader.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/PublicTimelineLoader.kt
@@ -49,16 +49,16 @@ class PublicTimelineLoader(
@Throws(MicroBlogException::class)
override fun getStatuses(account: AccountDetails, paging: Paging): PaginatedList {
- when (account.type) {
+ return when (account.type) {
AccountType.MASTODON -> {
val mastodon = account.newMicroBlogInstance(context, Mastodon::class.java)
- return mastodon.getPublicTimeline(paging, true).mapToPaginated {
+ mastodon.getPublicTimeline(paging, true).mapToPaginated {
it.toParcelable(account)
}
}
else -> {
val microBlog = account.newMicroBlogInstance(context, MicroBlog::class.java)
- return microBlog.getPublicTimeline(paging).mapMicroBlogToPaginated {
+ microBlog.getPublicTimeline(paging).mapMicroBlogToPaginated {
it.toParcelable(account, profileImageSize = profileImageSize)
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/UserListTimelineLoader.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/UserListTimelineLoader.kt
index 87a49b9b1a..0a142a01dc 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/UserListTimelineLoader.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/UserListTimelineLoader.kt
@@ -68,15 +68,15 @@ class UserListTimelineLoader(
private fun getMicroBlogStatuses(account: AccountDetails, paging: Paging): ResponseList {
val microBlog = account.newMicroBlogInstance(context, MicroBlog::class.java)
- when {
+ return when {
listId != null -> {
- return microBlog.getUserListStatuses(listId, paging)
+ microBlog.getUserListStatuses(listId, paging)
}
listName != null && userKey != null -> {
- return microBlog.getUserListStatuses(listName.replace(' ', '-'), userKey.id, paging)
+ microBlog.getUserListStatuses(listName.replace(' ', '-'), userKey.id, paging)
}
listName != null && screenName != null -> {
- return microBlog.getUserListStatuses(listName.replace(' ', '-'), screenName, paging)
+ microBlog.getUserListStatuses(listName.replace(' ', '-'), screenName, paging)
}
else -> {
throw MicroBlogException("User id or screen name is required for list name")
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/UserTimelineLoader.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/UserTimelineLoader.kt
index beaf6f6903..43b30c8809 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/UserTimelineLoader.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/statuses/UserTimelineLoader.kt
@@ -140,20 +140,24 @@ class UserTimelineLoader(
option.setExcludeReplies(!timelineFilter.isIncludeReplies)
option.setIncludeRetweets(timelineFilter.isIncludeRetweets)
}
- if (userKey != null) {
- if (account.type == AccountType.STATUSNET && userKey.host != account.key.host
+ when {
+ userKey != null -> {
+ if (account.type == AccountType.STATUSNET && userKey.host != account.key.host
&& profileUrl != null) {
- try {
- return showStatusNetExternalTimeline(profileUrl, paging)
- } catch (e: IOException) {
- throw MicroBlogException(e)
+ try {
+ return showStatusNetExternalTimeline(profileUrl, paging)
+ } catch (e: IOException) {
+ throw MicroBlogException(e)
+ }
}
+ return microBlog.getUserTimeline(userKey.id, paging, option)
+ }
+ screenName != null -> {
+ return microBlog.getUserTimelineByScreenName(screenName, paging, option)
+ }
+ else -> {
+ throw MicroBlogException("Invalid user")
}
- return microBlog.getUserTimeline(userKey.id, paging, option)
- } else if (screenName != null) {
- return microBlog.getUserTimelineByScreenName(screenName, paging, option)
- } else {
- throw MicroBlogException("Invalid user")
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/users/AbsRequestUsersLoader.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/users/AbsRequestUsersLoader.kt
index a90dffced5..974c9309d0 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/users/AbsRequestUsersLoader.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/users/AbsRequestUsersLoader.kt
@@ -93,7 +93,7 @@ abstract class AbsRequestUsersLoader(
}
protected open fun processUsersData(details: AccountDetails, list: MutableList) {
- Collections.sort(data)
+ data.sort()
}
protected open fun processPaging(paging: Paging, details: AccountDetails, loadItemLimit: Int) {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/users/GroupMembersLoader.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/users/GroupMembersLoader.kt
index 13243933dc..bec4b14dae 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/users/GroupMembersLoader.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/users/GroupMembersLoader.kt
@@ -51,9 +51,9 @@ class GroupMembersLoader(
private fun getMicroBlogUsers(details: AccountDetails, paging: Paging): ResponseList {
val microBlog = details.newMicroBlogInstance(context, MicroBlog::class.java)
- when {
- groupId != null -> return microBlog.getGroupMembers(groupId, paging)
- groupName != null -> return microBlog.getGroupMembersByName(groupName, paging)
+ return when {
+ groupId != null -> microBlog.getGroupMembers(groupId, paging)
+ groupName != null -> microBlog.getGroupMembersByName(groupName, paging)
else -> throw MicroBlogException("groupId or groupName required")
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/users/MutesUsersLoader.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/users/MutesUsersLoader.kt
index c7e03fe984..676eb288c0 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/loader/users/MutesUsersLoader.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/loader/users/MutesUsersLoader.kt
@@ -48,16 +48,16 @@ class MutesUsersLoader(
@Throws(MicroBlogException::class)
override fun getUsers(details: AccountDetails, paging: Paging): PaginatedList {
- when (details.type) {
+ return when (details.type) {
AccountType.MASTODON -> {
val mastodon = details.newMicroBlogInstance(context, Mastodon::class.java)
- return mastodon.getMutes(paging).mapToPaginated {
+ mastodon.getMutes(paging).mapToPaginated {
it.toParcelable(details)
}
}
else -> {
val microBlog = details.newMicroBlogInstance(context, MicroBlog::class.java)
- return microBlog.getMutesUsersList(paging).mapToPaginated {
+ microBlog.getMutesUsersList(paging).mapToPaginated {
it.toParcelable(details, profileImageSize = profileImageSize)
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/menu/AccountActionProvider.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/menu/AccountActionProvider.kt
index f25c791f5d..e76314cff7 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/menu/AccountActionProvider.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/menu/AccountActionProvider.kt
@@ -51,7 +51,7 @@ class AccountActionProvider(
companion object {
- val MENU_GROUP = 201
+ const val MENU_GROUP = 201
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/menu/FavoriteItemProvider.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/menu/FavoriteItemProvider.kt
index 4c4bd3d772..c151b7b26f 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/menu/FavoriteItemProvider.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/menu/FavoriteItemProvider.kt
@@ -29,6 +29,7 @@ import androidx.appcompat.widget.ActionMenuView
import android.view.MenuItem
import android.view.View
import org.mariotaku.ktextension.weak
+import org.mariotaku.twidere.BuildConfig
import org.mariotaku.twidere.extension.view.findItemView
import org.mariotaku.twidere.graphic.like.LikeAnimationDrawable
import org.mariotaku.twidere.graphic.like.LikeAnimationDrawable.Style
@@ -52,7 +53,7 @@ class FavoriteItemProvider(context: Context) : ActionProvider(context) {
}
fun init(menuBar: ActionMenuView, item: MenuItem) {
- assert(MenuItemCompat.getActionProvider(item) === this)
+ if (BuildConfig.DEBUG && MenuItemCompat.getActionProvider(item) !== this) { error("Assertion failed") }
val icon = ContextCompat.getDrawable(context, this.icon)
val drawable = LikeAnimationDrawable(icon, defaultColor, activatedColor,
if (useStar) Style.FAVORITE else Style.LIKE)
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/menu/RetweetItemProvider.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/menu/RetweetItemProvider.kt
index 483694cfd6..913a931ced 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/menu/RetweetItemProvider.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/menu/RetweetItemProvider.kt
@@ -24,6 +24,7 @@ import androidx.core.view.ActionProvider
import androidx.core.view.MenuItemCompat
import androidx.appcompat.widget.ActionMenuView
import android.view.MenuItem
+import org.mariotaku.twidere.BuildConfig
import org.mariotaku.twidere.extension.view.findItemView
/**
@@ -35,7 +36,7 @@ class RetweetItemProvider(context: Context) : ActionProvider(context) {
override fun onCreateActionView() = null
fun init(menuBar: ActionMenuView, item: MenuItem) {
- assert(MenuItemCompat.getActionProvider(item) === this)
+ if (BuildConfig.DEBUG && MenuItemCompat.getActionProvider(item) !== this) { error("Assertion failed") }
val menuView = menuBar.findItemView(item)
menuView?.setOnLongClickListener { longClickListener?.invoke() == true }
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/model/AccountPreferences.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/model/AccountPreferences.kt
index 0d1e64632b..cd3255b189 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/model/AccountPreferences.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/model/AccountPreferences.kt
@@ -44,11 +44,7 @@ class AccountPreferences(
val defaultNotificationLightColor: Int
get() {
val a = AccountUtils.getAccountDetails(AccountManager.get(context), accountKey, true)
- if (a != null) {
- return a.color
- } else {
- return ContextCompat.getColor(context, R.color.branding_color)
- }
+ return a?.color ?: ContextCompat.getColor(context, R.color.branding_color)
}
val directMessagesNotificationType: Int
@@ -70,10 +66,10 @@ class AccountPreferences(
val notificationRingtone: Uri
get() {
val ringtone = accountPreferences.getString(KEY_NOTIFICATION_RINGTONE, null)
- if (TextUtils.isEmpty(ringtone)) {
- return RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
+ return if (TextUtils.isEmpty(ringtone)) {
+ RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
} else {
- return Uri.parse(ringtone)
+ Uri.parse(ringtone)
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/model/ActivityTitleSummaryMessage.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/model/ActivityTitleSummaryMessage.kt
index 1efd9b6a06..52e3e3da76 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/model/ActivityTitleSummaryMessage.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/model/ActivityTitleSummaryMessage.kt
@@ -119,17 +119,17 @@ class ActivityTitleSummaryMessage private constructor(val icon: Int, val color:
Activity.Action.LIST_MEMBER_ADDED -> {
val title: CharSequence
val icon = R.drawable.ic_activity_action_list_added
- if (sources.size == 1 && activity.summary_line?.size == 1) {
+ title = if (sources.size == 1 && activity.summary_line?.size == 1) {
val firstDisplayName = SpannableString(manager.getDisplayName(
- sources[0], nameFirst))
+ sources[0], nameFirst))
val listName = SpannableString(activity.summary_line[0].content)
firstDisplayName.setSpan(StyleSpan(Typeface.BOLD), 0, firstDisplayName.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
listName.setSpan(StyleSpan(Typeface.BOLD), 0, listName.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
val format = context.getString(R.string.activity_about_me_list_member_added_with_name)
- title = SpanFormatter.format(format, firstDisplayName, listName)
+ SpanFormatter.format(format, firstDisplayName, listName)
} else {
- title = getTitleStringAboutMe(resources, manager, R.string.activity_about_me_list_member_added,
- R.string.activity_about_me_list_member_added_multi, sources, nameFirst)
+ getTitleStringAboutMe(resources, manager, R.string.activity_about_me_list_member_added,
+ R.string.activity_about_me_list_member_added_multi, sources, nameFirst)
}
return ActivityTitleSummaryMessage(icon, defaultColor, title, null)
}
@@ -229,22 +229,26 @@ class ActivityTitleSummaryMessage private constructor(val icon: Int, val color:
nameFirst))
firstDisplayName.setSpan(StyleSpan(Typeface.BOLD), 0, firstDisplayName.length,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
- if (sources.size == 1) {
- val format = resources.getString(stringRes)
- return SpanFormatter.format(format, firstDisplayName)
- } else if (sources.size == 2) {
- val format = resources.getString(stringResMulti)
- val secondDisplayName = SpannableString(manager.getDisplayName(sources[1],
+ when (sources.size) {
+ 1 -> {
+ val format = resources.getString(stringRes)
+ return SpanFormatter.format(format, firstDisplayName)
+ }
+ 2 -> {
+ val format = resources.getString(stringResMulti)
+ val secondDisplayName = SpannableString(manager.getDisplayName(sources[1],
nameFirst))
- secondDisplayName.setSpan(StyleSpan(Typeface.BOLD), 0, secondDisplayName.length,
+ secondDisplayName.setSpan(StyleSpan(Typeface.BOLD), 0, secondDisplayName.length,
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
- return SpanFormatter.format(format, firstDisplayName,
+ return SpanFormatter.format(format, firstDisplayName,
secondDisplayName)
- } else {
- val othersCount = sources.size - 1
- val nOthers = resources.getQuantityString(R.plurals.N_others, othersCount, othersCount)
- val format = resources.getString(stringResMulti)
- return SpanFormatter.format(format, firstDisplayName, nOthers)
+ }
+ else -> {
+ val othersCount = sources.size - 1
+ val nOthers = resources.getQuantityString(R.plurals.N_others, othersCount, othersCount)
+ val format = resources.getString(stringResMulti)
+ return SpanFormatter.format(format, firstDisplayName, nOthers)
+ }
}
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/model/analyzer/UpdateStatus.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/model/analyzer/UpdateStatus.kt
index deed27cd50..c5cfce4ede 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/model/analyzer/UpdateStatus.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/model/analyzer/UpdateStatus.kt
@@ -39,8 +39,7 @@ data class UpdateStatus(
is UpdateStatusTask.UploaderNotFoundException ->
return "extension not found"
else -> {
- val cause = ex.cause
- when (cause) {
+ when (val cause = ex.cause) {
is UpdateStatusTask.ExtensionVersionMismatchException ->
return "extension version mismatch"
is IOException ->
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/model/filter/FilterScopeStringMap.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/model/filter/FilterScopeStringMap.kt
index 5cd57181b4..43c25e93a4 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/model/filter/FilterScopeStringMap.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/model/filter/FilterScopeStringMap.kt
@@ -52,7 +52,7 @@ object FilterScopeStringMap {
var tmp = scope
while (tmp != 0) {
val mapping = mappings.firstOrNull { (v, _) -> v in tmp } ?: break
- if (!result.isEmpty()) {
+ if (result.isNotEmpty()) {
result.append('|')
}
result.append(mapping.name)
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/FavoriteTimelineTabConfiguration.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/FavoriteTimelineTabConfiguration.kt
index 0be1097c4b..f7d1c15fa4 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/FavoriteTimelineTabConfiguration.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/FavoriteTimelineTabConfiguration.kt
@@ -53,7 +53,7 @@ class FavoriteTimelineTabConfiguration : TabConfiguration() {
UserExtraConfiguration(EXTRA_USER).headerTitle(R.string.title_user)
)
- override fun applyExtraConfigurationTo(tab: Tab, extraConf: TabConfiguration.ExtraConfiguration): Boolean {
+ override fun applyExtraConfigurationTo(tab: Tab, extraConf: ExtraConfiguration): Boolean {
val arguments = tab.arguments as UserArguments
when (extraConf.key) {
EXTRA_USER -> {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/HomeTabConfiguration.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/HomeTabConfiguration.kt
index 4098ef98ba..52e739a34e 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/HomeTabConfiguration.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/HomeTabConfiguration.kt
@@ -52,7 +52,7 @@ class HomeTabConfiguration : TabConfiguration() {
BooleanExtraConfiguration(EXTRA_HIDE_REPLIES, R.string.hide_replies, false).mutable(true)
)
- override fun applyExtraConfigurationTo(tab: Tab, extraConf: TabConfiguration.ExtraConfiguration): Boolean {
+ override fun applyExtraConfigurationTo(tab: Tab, extraConf: ExtraConfiguration): Boolean {
val extras = tab.extras as HomeTabExtras
when (extraConf.key) {
EXTRA_HIDE_RETWEETS -> {
@@ -68,7 +68,7 @@ class HomeTabConfiguration : TabConfiguration() {
return true
}
- override fun readExtraConfigurationFrom(tab: Tab, extraConf: TabConfiguration.ExtraConfiguration): Boolean {
+ override fun readExtraConfigurationFrom(tab: Tab, extraConf: ExtraConfiguration): Boolean {
val extras = tab.extras as? HomeTabExtras ?: return false
when (extraConf.key) {
EXTRA_HIDE_RETWEETS -> {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/InteractionsTabConfiguration.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/InteractionsTabConfiguration.kt
index fe8c7a7a71..bdf9d1df6a 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/InteractionsTabConfiguration.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/InteractionsTabConfiguration.kt
@@ -60,7 +60,7 @@ class InteractionsTabConfiguration : TabConfiguration() {
MentionsOnlyExtraConfiguration(EXTRA_MENTIONS_ONLY).mutable(true)
)
- override fun applyExtraConfigurationTo(tab: Tab, extraConf: TabConfiguration.ExtraConfiguration): Boolean {
+ override fun applyExtraConfigurationTo(tab: Tab, extraConf: ExtraConfiguration): Boolean {
val extras = tab.extras as InteractionsTabExtras
when (extraConf.key) {
EXTRA_MY_FOLLOWING_ONLY -> {
@@ -73,7 +73,7 @@ class InteractionsTabConfiguration : TabConfiguration() {
return true
}
- override fun readExtraConfigurationFrom(tab: Tab, extraConf: TabConfiguration.ExtraConfiguration): Boolean {
+ override fun readExtraConfigurationFrom(tab: Tab, extraConf: ExtraConfiguration): Boolean {
val extras = tab.extras as? InteractionsTabExtras ?: return false
when (extraConf.key) {
EXTRA_MY_FOLLOWING_ONLY -> {
@@ -88,7 +88,7 @@ class InteractionsTabConfiguration : TabConfiguration() {
private class MentionsOnlyExtraConfiguration(key: String) : BooleanExtraConfiguration(key,
StringHolder.resource(R.string.mentions_only),
- MentionsOnlyExtraConfiguration.InteractionsAvailableBooleanHolder()) {
+ InteractionsAvailableBooleanHolder()) {
private var valueBackup: Boolean = false
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/SearchTabConfiguration.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/SearchTabConfiguration.kt
index c1fe5f62a7..2481c4983f 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/SearchTabConfiguration.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/SearchTabConfiguration.kt
@@ -49,7 +49,7 @@ class SearchTabConfiguration : TabConfiguration() {
StringExtraConfiguration(EXTRA_QUERY, R.string.search_statuses, null).maxLines(1).headerTitle(R.string.query)
)
- override fun applyExtraConfigurationTo(tab: Tab, extraConf: TabConfiguration.ExtraConfiguration): Boolean {
+ override fun applyExtraConfigurationTo(tab: Tab, extraConf: ExtraConfiguration): Boolean {
val arguments = tab.arguments as TextQueryArguments
when (extraConf.key) {
EXTRA_QUERY -> {
@@ -60,7 +60,7 @@ class SearchTabConfiguration : TabConfiguration() {
return true
}
- override fun readExtraConfigurationFrom(tab: Tab, extraConf: TabConfiguration.ExtraConfiguration): Boolean {
+ override fun readExtraConfigurationFrom(tab: Tab, extraConf: ExtraConfiguration): Boolean {
val arguments = tab.arguments as? TextQueryArguments ?: return false
when (extraConf.key) {
EXTRA_QUERY -> {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/TrendsTabConfiguration.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/TrendsTabConfiguration.kt
index 5dddcd2601..88330a978a 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/TrendsTabConfiguration.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/TrendsTabConfiguration.kt
@@ -52,7 +52,7 @@ class TrendsTabConfiguration : TabConfiguration() {
TrendsLocationExtraConfiguration(EXTRA_PLACE, R.string.trends_location).mutable(true)
)
- override fun applyExtraConfigurationTo(tab: Tab, extraConf: TabConfiguration.ExtraConfiguration): Boolean {
+ override fun applyExtraConfigurationTo(tab: Tab, extraConf: ExtraConfiguration): Boolean {
val extras = tab.extras as TrendsTabExtras
when (extraConf.key) {
EXTRA_PLACE -> {
@@ -70,7 +70,7 @@ class TrendsTabConfiguration : TabConfiguration() {
return true
}
- override fun readExtraConfigurationFrom(tab: Tab, extraConf: TabConfiguration.ExtraConfiguration): Boolean {
+ override fun readExtraConfigurationFrom(tab: Tab, extraConf: ExtraConfiguration): Boolean {
val extras = tab.extras as? TrendsTabExtras ?: return false
when (extraConf.key) {
EXTRA_PLACE -> {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/UserListTimelineTabConfiguration.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/UserListTimelineTabConfiguration.kt
index dbae1654cf..c38ef47b87 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/UserListTimelineTabConfiguration.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/UserListTimelineTabConfiguration.kt
@@ -62,7 +62,7 @@ class UserListTimelineTabConfiguration : TabConfiguration() {
// BooleanExtraConfiguration(EXTRA_HIDE_REPLIES, R.string.hide_replies, false).mutable(true)
)
- override fun applyExtraConfigurationTo(tab: Tab, extraConf: TabConfiguration.ExtraConfiguration): Boolean {
+ override fun applyExtraConfigurationTo(tab: Tab, extraConf: ExtraConfiguration): Boolean {
val arguments = tab.arguments as UserListArguments
when (extraConf.key) {
EXTRA_USER_LIST -> {
@@ -85,7 +85,7 @@ class UserListTimelineTabConfiguration : TabConfiguration() {
return true
}
- override fun readExtraConfigurationFrom(tab: Tab, extraConf: TabConfiguration.ExtraConfiguration): Boolean {
+ override fun readExtraConfigurationFrom(tab: Tab, extraConf: ExtraConfiguration): Boolean {
val extras = tab.extras as? HomeTabExtras ?: return false
when (extraConf.key) {
EXTRA_HIDE_RETWEETS -> {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/UserTimelineTabConfiguration.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/UserTimelineTabConfiguration.kt
index abb6fb35fc..3019fdbb73 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/UserTimelineTabConfiguration.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/model/tab/impl/UserTimelineTabConfiguration.kt
@@ -49,7 +49,7 @@ class UserTimelineTabConfiguration : TabConfiguration() {
UserExtraConfiguration(EXTRA_USER).headerTitle(R.string.title_user)
)
- override fun applyExtraConfigurationTo(tab: Tab, extraConf: TabConfiguration.ExtraConfiguration): Boolean {
+ override fun applyExtraConfigurationTo(tab: Tab, extraConf: ExtraConfiguration): Boolean {
val arguments = tab.arguments as UserArguments
when (extraConf.key) {
EXTRA_USER -> {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/model/util/ParcelableMediaUtils.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/model/util/ParcelableMediaUtils.kt
index 847457ed7e..3e102ea19d 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/model/util/ParcelableMediaUtils.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/model/util/ParcelableMediaUtils.kt
@@ -157,10 +157,10 @@ object ParcelableMediaUtils {
}
fun getPrimaryMedia(status: ParcelableStatus): Array? {
- if (status.is_quote && status.media.isNullOrEmpty()) {
- return status.quoted_media
+ return if (status.is_quote && status.media.isNullOrEmpty()) {
+ status.quoted_media
} else {
- return status.media
+ status.media
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/model/util/ParcelableStatusUpdateUtils.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/model/util/ParcelableStatusUpdateUtils.kt
index 2bbd02d755..29980db1b1 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/model/util/ParcelableStatusUpdateUtils.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/model/util/ParcelableStatusUpdateUtils.kt
@@ -25,8 +25,7 @@ object ParcelableStatusUpdateUtils {
statusUpdate.text = draft.text
statusUpdate.location = draft.location
statusUpdate.media = draft.media
- val actionExtras = draft.action_extras
- when (actionExtras) {
+ when (val actionExtras = draft.action_extras) {
is UpdateStatusActionExtras -> {
statusUpdate.in_reply_to_status = actionExtras.inReplyToStatus
statusUpdate.is_possibly_sensitive = actionExtras.isPossiblySensitive
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/model/util/ParcelableUserUtils.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/model/util/ParcelableUserUtils.kt
index 34568f2782..d39723e4f8 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/model/util/ParcelableUserUtils.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/model/util/ParcelableUserUtils.kt
@@ -17,7 +17,7 @@ object ParcelableUserUtils {
if (colorString == null) return 0
var str: String = colorString
if (!str.startsWith("#")) {
- str = "#" + str
+ str = "#$str"
}
return ParseUtils.parseColor(str, 0)
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/preference/AccountsListPreference.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/preference/AccountsListPreference.kt
index b97828778b..fd5b39e760 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/preference/AccountsListPreference.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/preference/AccountsListPreference.kt
@@ -117,11 +117,11 @@ abstract class AccountsListPreference(context: Context, attrs: AttributeSet? = n
}
val titleView = holder.findViewById(android.R.id.title)
if (titleView is TextView) {
- titleView.setSingleLine(true)
+ titleView.isSingleLine = true
}
val summaryView = holder.findViewById(android.R.id.summary)
if (summaryView is TextView) {
- summaryView.setSingleLine(true)
+ summaryView.isSingleLine = true
}
val switchView = holder.findViewById(android.R.id.toggle) as SwitchCompat
if (switchKey != null) {
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/preference/AutoRefreshAccountsListPreference.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/preference/AutoRefreshAccountsListPreference.kt
index 54f880f755..075be93643 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/preference/AutoRefreshAccountsListPreference.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/preference/AutoRefreshAccountsListPreference.kt
@@ -28,7 +28,7 @@ import org.mariotaku.twidere.model.AccountDetails
class AutoRefreshAccountsListPreference(context: Context, attrs: AttributeSet? = null) : AccountsListPreference(context, attrs) {
- override fun setupPreference(preference: AccountsListPreference.AccountItemPreference, account: AccountDetails) {
+ override fun setupPreference(preference: AccountItemPreference, account: AccountDetails) {
preference.fragment = AccountRefreshSettingsFragment::class.java.name
val args = preference.extras
args.putParcelable(EXTRA_ACCOUNT, account)
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/preference/ColorPickerPreference.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/preference/ColorPickerPreference.kt
index 23ecc79c35..fe46be5ae4 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/preference/ColorPickerPreference.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/preference/ColorPickerPreference.kt
@@ -97,7 +97,7 @@ class ColorPickerPreference(context: Context, attrs: AttributeSet? = null) :
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val preference = preference as ColorPickerPreference
val context = context
- val builder = AlertDialog.Builder(context!!)
+ val builder = AlertDialog.Builder(requireContext())
builder.setTitle(preference.dialogTitle)
builder.setView(R.layout.cp__dialog_color_picker)
builder.setPositiveButton(android.R.string.ok, this)
@@ -122,7 +122,7 @@ class ColorPickerPreference(context: Context, attrs: AttributeSet? = null) :
val preference = preference as ColorPickerPreference
val alertDialog = dialog as AlertDialog
alertDialog.applyTheme()
- val windowView = alertDialog.window!!.decorView ?: return
+ val windowView = alertDialog.window!!.decorView
controller = ColorPickerDialog.Controller(context, windowView)
controller.setAlphaEnabled(preference.isAlphaSliderEnabled)
for (presetColor in PRESET_COLORS) {
@@ -137,7 +137,7 @@ class ColorPickerPreference(context: Context, attrs: AttributeSet? = null) :
fun newInstance(key: String): ColorPickerPreferenceDialogFragment {
val df = ColorPickerPreferenceDialogFragment()
val args = Bundle()
- args.putString(PreferenceDialogFragmentCompat.ARG_KEY, key)
+ args.putString(ARG_KEY, key)
df.arguments = args
return df
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/preference/KeyboardShortcutPreference.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/preference/KeyboardShortcutPreference.kt
index 5fd786a231..7305098ac8 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/preference/KeyboardShortcutPreference.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/preference/KeyboardShortcutPreference.kt
@@ -161,7 +161,7 @@ class KeyboardShortcutPreference(context: Context, attrs: AttributeSet? = null)
fun newInstance(key: String): KeyboardShortcutDialogFragment {
val df = KeyboardShortcutDialogFragment()
val args = Bundle()
- args.putString(PreferenceDialogFragmentCompat.ARG_KEY, key)
+ args.putString(ARG_KEY, key)
df.arguments = args
return df
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/preference/LanguageListPreference.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/preference/LanguageListPreference.kt
index d8d70ecf5d..795c730774 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/preference/LanguageListPreference.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/preference/LanguageListPreference.kt
@@ -8,7 +8,14 @@ import java.util.*
class LanguageListPreference(context: Context, attrs: AttributeSet? = null) : EntrySummaryListPreference(context, attrs) {
init {
- val locales = BuildConfig.TRANSLATION_ARRAY.map { Locale(it.split('-')[0], it.split('-')[1]) }.let {
+ val locales = BuildConfig.TRANSLATION_ARRAY.map {
+ val splits = it.split('-')
+ if (splits.count() > 1) {
+ Locale(splits[0], splits[1])
+ } else {
+ Locale(it)
+ }
+ }.let {
it + Locale.US
}.sortedBy {
it.getDisplayName(it)
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/preference/NotificationAccountsListPreference.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/preference/NotificationAccountsListPreference.kt
index cd8ac82b1d..2163219516 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/preference/NotificationAccountsListPreference.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/preference/NotificationAccountsListPreference.kt
@@ -27,7 +27,7 @@ import org.mariotaku.twidere.model.AccountDetails
class NotificationAccountsListPreference(context: Context, attrs: AttributeSet? = null) : AccountsListPreference(context, attrs) {
- override fun setupPreference(preference: AccountsListPreference.AccountItemPreference, account: AccountDetails) {
+ override fun setupPreference(preference: AccountItemPreference, account: AccountDetails) {
preference.fragment = AccountNotificationSettingsFragment::class.java.name
val args = preference.extras
args.putParcelable(EXTRA_ACCOUNT, account)
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/preference/RefreshIntervalPreference.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/preference/RefreshIntervalPreference.kt
index 4957ef174a..37af72f4fb 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/preference/RefreshIntervalPreference.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/preference/RefreshIntervalPreference.kt
@@ -58,7 +58,7 @@ class RefreshIntervalPreference(
}
val valueMinutes = value.toLongOr(-1)
val minValue = entryValues.firstOrNull()?.toString().toLongOr(-1)
- if (valueMinutes > 0 && valueMinutes < minValue) {
+ if (valueMinutes in 1 until minValue) {
value = minValue.toString()
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/provider/CacheProvider.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/provider/CacheProvider.kt
index 761bbe6c91..2ed703e311 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/provider/CacheProvider.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/provider/CacheProvider.kt
@@ -8,14 +8,12 @@ import android.database.Cursor
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.ParcelFileDescriptor
-import okio.ByteString
import okio.ByteString.Companion.decodeBase64
import okio.ByteString.Companion.encodeUtf8
import org.mariotaku.mediaviewer.library.FileCache
import org.mariotaku.twidere.TwidereConstants.AUTHORITY_TWIDERE_CACHE
import org.mariotaku.twidere.TwidereConstants.QUERY_PARAM_TYPE
import org.mariotaku.twidere.annotation.CacheFileType
-import org.mariotaku.twidere.extension.get
import org.mariotaku.twidere.model.CacheMetadata
import org.mariotaku.twidere.task.SaveFileTask
import org.mariotaku.twidere.util.JsonSerializer
@@ -48,8 +46,7 @@ class CacheProvider : ContentProvider() {
if (metadata != null) {
return metadata.contentType
}
- val type = uri.getQueryParameter(QUERY_PARAM_TYPE)
- when (type) {
+ when (uri.getQueryParameter(QUERY_PARAM_TYPE)) {
CacheFileType.IMAGE -> {
val file = fileCache.get(getCacheKey(uri)) ?: return null
return BitmapFactory.Options().apply {
@@ -170,21 +167,19 @@ class CacheProvider : ContentProvider() {
* Copied from ContentResolver.java
*/
private fun modeToMode(mode: String): Int {
- val modeBits: Int
- if ("r" == mode) {
- modeBits = ParcelFileDescriptor.MODE_READ_ONLY
+ return if ("r" == mode) {
+ ParcelFileDescriptor.MODE_READ_ONLY
} else if ("w" == mode || "wt" == mode) {
- modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY or ParcelFileDescriptor.MODE_CREATE or ParcelFileDescriptor.MODE_TRUNCATE
+ ParcelFileDescriptor.MODE_WRITE_ONLY or ParcelFileDescriptor.MODE_CREATE or ParcelFileDescriptor.MODE_TRUNCATE
} else if ("wa" == mode) {
- modeBits = ParcelFileDescriptor.MODE_WRITE_ONLY or ParcelFileDescriptor.MODE_CREATE or ParcelFileDescriptor.MODE_APPEND
+ ParcelFileDescriptor.MODE_WRITE_ONLY or ParcelFileDescriptor.MODE_CREATE or ParcelFileDescriptor.MODE_APPEND
} else if ("rw" == mode) {
- modeBits = ParcelFileDescriptor.MODE_READ_WRITE or ParcelFileDescriptor.MODE_CREATE
+ ParcelFileDescriptor.MODE_READ_WRITE or ParcelFileDescriptor.MODE_CREATE
} else if ("rwt" == mode) {
- modeBits = ParcelFileDescriptor.MODE_READ_WRITE or ParcelFileDescriptor.MODE_CREATE or ParcelFileDescriptor.MODE_TRUNCATE
+ ParcelFileDescriptor.MODE_READ_WRITE or ParcelFileDescriptor.MODE_CREATE or ParcelFileDescriptor.MODE_TRUNCATE
} else {
- throw IllegalArgumentException("Invalid mode: " + mode)
+ throw IllegalArgumentException("Invalid mode: $mode")
}
- return modeBits
}
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/provider/TwidereDataProvider.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/provider/TwidereDataProvider.kt
index 5b152db4b9..015b49cbf4 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/provider/TwidereDataProvider.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/provider/TwidereDataProvider.kt
@@ -343,8 +343,7 @@ class TwidereDataProvider : ContentProvider(), LazyLoadCallback {
}
private fun deleteInternal(uri: Uri, selection: String?, selectionArgs: Array?): Int {
- val tableId = DataStoreUtils.getTableId(uri)
- when (tableId) {
+ when (val tableId = DataStoreUtils.getTableId(uri)) {
VIRTUAL_TABLE_ID_DRAFTS_NOTIFICATIONS -> {
notificationManager.cancel(uri.toString(), NOTIFICATION_ID_DRAFTS)
return 1
@@ -415,13 +414,17 @@ class TwidereDataProvider : ContentProvider(), LazyLoadCallback {
}
else -> {
val conflictAlgorithm = getConflictAlgorithm(tableId)
- if (conflictAlgorithm != SQLiteDatabase.CONFLICT_NONE) {
- rowId = databaseWrapper.insertWithOnConflict(table, null, values,
+ rowId = when {
+ conflictAlgorithm != SQLiteDatabase.CONFLICT_NONE -> {
+ databaseWrapper.insertWithOnConflict(table, null, values,
conflictAlgorithm)
- } else if (table != null) {
- rowId = databaseWrapper.insert(table, null, values)
- } else {
- return null
+ }
+ table != null -> {
+ databaseWrapper.insert(table, null, values)
+ }
+ else -> {
+ return null
+ }
}
}
}
diff --git a/twidere/src/main/kotlin/org/mariotaku/twidere/service/LengthyOperationsService.kt b/twidere/src/main/kotlin/org/mariotaku/twidere/service/LengthyOperationsService.kt
index 13ffdeb62d..92e1292edc 100644
--- a/twidere/src/main/kotlin/org/mariotaku/twidere/service/LengthyOperationsService.kt
+++ b/twidere/src/main/kotlin/org/mariotaku/twidere/service/LengthyOperationsService.kt
@@ -70,6 +70,7 @@ import org.mariotaku.twidere.util.deleteDrafts
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.util.concurrent.TimeUnit
+import kotlin.math.min
/**
* Intent service for lengthy operations like update status/send DM.
@@ -215,15 +216,13 @@ class LengthyOperationsService : BaseIntentService("lengthy_operations") {
private fun handleUpdateStatusIntent(intent: Intent) {
val status = intent.getParcelableExtra(EXTRA_STATUS)
- val statusParcelables = intent.getNullableTypedArrayExtra(EXTRA_STATUSES)
val scheduleInfo = intent.getParcelableExtra(EXTRA_SCHEDULE_INFO)
val statuses: Array