1
0
mirror of https://github.com/TwidereProject/Twidere-Android synced 2025-02-12 09:40:50 +01:00

removed unused files

This commit is contained in:
Mariotaku Lee 2016-08-25 10:10:53 +08:00
parent d2acb9c7c3
commit 7988df19f6
26 changed files with 80 additions and 649 deletions

View File

@ -20,6 +20,7 @@
package org.mariotaku.twidere.util;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import org.mariotaku.twidere.fragment.OpenStreetMapViewerFragment;
@ -29,7 +30,7 @@ import org.mariotaku.twidere.fragment.OpenStreetMapViewerFragment;
*/
public class MapFragmentFactoryImpl extends MapFragmentFactory {
@Override
public Fragment createMapFragment(Context context) {
public Fragment createMapFragment(@NonNull Context context) {
return new OpenStreetMapViewerFragment();
}
}

View File

@ -62,11 +62,7 @@ public final class CRLFLineReader extends BufferedReader
if (prevWasCR && intch == LF) {
return sb.substring(0, sb.length()-1);
}
if (intch == CR) {
prevWasCR = true;
} else {
prevWasCR = false;
}
prevWasCR = intch == CR;
sb.append((char) intch);
}
}

View File

@ -45,8 +45,7 @@ public class UnreadItem {
if (!(obj instanceof UnreadItem)) return false;
final UnreadItem other = (UnreadItem) obj;
if (account_id != other.account_id) return false;
if (id != other.id) return false;
return true;
return id == other.id;
}
@Override

View File

@ -20,7 +20,7 @@ import org.mariotaku.restfu.RestFuUtils;
import org.mariotaku.twidere.TwidereConstants;
import org.mariotaku.twidere.model.CacheMetadata;
import org.mariotaku.twidere.task.SaveFileTask;
import org.mariotaku.twidere.util.Utils;
import org.mariotaku.twidere.util.BitmapUtils;
import org.mariotaku.twidere.util.dagger.GeneralComponentHelper;
import java.io.File;
@ -100,7 +100,7 @@ public class CacheProvider extends ContentProvider implements TwidereConstants {
case Type.IMAGE: {
final File file = mSimpleDiskCache.get(getCacheKey(uri));
if (file == null) return null;
return Utils.getImageMimeType(file);
return BitmapUtils.getImageMimeType(file);
}
case Type.VIDEO: {
return "video/mp4";

View File

@ -1358,7 +1358,7 @@ public final class TwidereDataProvider extends ContentProvider implements Consta
applyNotificationPreferences(builder, pref, pref.getHomeTimelineNotificationType());
try {
nm.notify("home_" + accountKey, Utils.getNotificationId(NOTIFICATION_ID_HOME_TIMELINE, accountKey), builder.build());
Utils.sendPebbleNotification(context, notificationContent);
Utils.sendPebbleNotification(context, null, notificationContent);
} catch (SecurityException e) {
// Silently ignore
}

View File

@ -124,7 +124,7 @@ class UpdateStatusTask(
val cr = context.contentResolver
if (hasError) {
val values = ContentValues()
values.put(Drafts.ACCOUNT_KEYS, CollectionUtils.toString(failedAccounts, ',', false))
values.put(Drafts.ACCOUNT_KEYS, failedAccounts.joinToString(","))
cr.update(Drafts.CONTENT_URI, values, where, whereArgs)
// TODO show error message
} else {

View File

@ -16,6 +16,7 @@
package org.mariotaku.twidere.util;
import android.content.ContentResolver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
@ -25,85 +26,18 @@ import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import com.nostra13.universalimageloader.utils.IoUtils;
import org.mariotaku.twidere.TwidereConstants;
import android.net.Uri;
import android.support.annotation.Nullable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class BitmapUtils {
private BitmapUtils() {
}
// Find the max x that 1 / x <= scale.
public static int computeSampleSize(final float scale) {
if (scale <= 0) return 1;
final int initialSize = Math.max(1, (int) Math.ceil(1 / scale));
return initialSize <= 8 ? TwidereMathUtils.nextPowerOf2(initialSize) : (initialSize + 7) / 8 * 8;
}
// This computes a sample size which makes the longer side at least
// minSideLength long. If that's not possible, return 1.
public static int computeSampleSizeLarger(final int w, final int h, final int minSideLength) {
final int initialSize = Math.max(w / minSideLength, h / minSideLength);
if (initialSize <= 1) return 1;
return initialSize <= 8 ? TwidereMathUtils.prevPowerOf2(initialSize) : initialSize / 8 * 8;
}
public static boolean downscaleImageIfNeeded(final File imageFile, final int quality) {
if (imageFile == null || !imageFile.isFile()) return false;
final String path = imageFile.getAbsolutePath();
final BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// Corrupted image, so return now.
if (o.outWidth <= 0 || o.outHeight <= 0) return false;
// Ignore for GIF image
if ("image/gif".equals(o.outMimeType)) return true;
o.inJustDecodeBounds = false;
if (o.outWidth > TwidereConstants.TWITTER_MAX_IMAGE_WIDTH || o.outHeight > TwidereConstants.TWITTER_MAX_IMAGE_HEIGHT) {
// The image dimension is larger than Twitter's limit.
o.inSampleSize = Utils.calculateInSampleSize(o.outWidth, o.outHeight, TwidereConstants.TWITTER_MAX_IMAGE_WIDTH,
TwidereConstants.TWITTER_MAX_IMAGE_HEIGHT);
FileOutputStream fos = null;
try {
final Bitmap b = BitmapDecodeHelper.decode(path, o);
final Bitmap.CompressFormat format = Utils.getBitmapCompressFormatByMimeType(o.outMimeType,
Bitmap.CompressFormat.PNG);
fos = new FileOutputStream(imageFile);
return b.compress(format, quality, fos);
} catch (final OutOfMemoryError e) {
return false;
} catch (final FileNotFoundException e) {
// This shouldn't happen.
} catch (final IllegalArgumentException e) {
return false;
} finally {
IoUtils.closeSilently(fos);
}
} else if (imageFile.length() > TwidereConstants.TWITTER_MAX_IMAGE_SIZE) {
// The file size is larger than Twitter's limit.
FileOutputStream fos = null;
try {
final Bitmap b = BitmapDecodeHelper.decode(path, o);
fos = new FileOutputStream(imageFile);
return b.compress(Bitmap.CompressFormat.JPEG, 80, fos);
} catch (final OutOfMemoryError e) {
return false;
} catch (final FileNotFoundException e) {
// This shouldn't happen.
} finally {
IoUtils.closeSilently(fos);
}
}
return true;
}
public static Bitmap getCircleBitmap(Bitmap bitmap) {
final Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
Bitmap.Config.ARGB_8888);
@ -125,35 +59,28 @@ public class BitmapUtils {
return output;
}
// Resize the bitmap if each side is >= targetSize * 2
public static Bitmap resizeDownIfTooBig(final Bitmap bitmap, final int targetSize, final boolean recycle) {
final int srcWidth = bitmap.getWidth();
final int srcHeight = bitmap.getHeight();
final float scale = Math.max((float) targetSize / srcWidth, (float) targetSize / srcHeight);
if (scale > 0.5f) return bitmap;
return resizeBitmapByScale(bitmap, scale, recycle);
@Nullable
public static String getImageMimeType(ContentResolver cr, final Uri uri) {
if (uri == null) return null;
final BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
InputStream is = null;
try {
is = cr.openInputStream(uri);
BitmapFactory.decodeStream(is, null, o);
return o.outMimeType;
} catch (IOException e) {
return null;
} finally {
Utils.closeSilently(is);
}
}
private static Bitmap.Config getConfig(final Bitmap bitmap) {
Bitmap.Config config = bitmap.getConfig();
if (config == null) {
config = Bitmap.Config.RGB_565;
}
return config;
}
private static Bitmap resizeBitmapByScale(final Bitmap bitmap, final float scale, final boolean recycle) {
final int width = Math.round(bitmap.getWidth() * scale);
final int height = Math.round(bitmap.getHeight() * scale);
if (width == bitmap.getWidth() && height == bitmap.getHeight()) return bitmap;
final Bitmap target = Bitmap.createBitmap(width, height, getConfig(bitmap));
final Canvas canvas = new Canvas(target);
canvas.scale(scale, scale);
final Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG);
canvas.drawBitmap(bitmap, 0, 0, paint);
if (recycle) {
bitmap.recycle();
}
return target;
public static String getImageMimeType(final File image) {
if (image == null) return null;
final BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image.getPath(), o);
return o.outMimeType;
}
}

View File

@ -1,73 +0,0 @@
package org.mariotaku.twidere.util;
import android.os.Environment;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
public class BuildProperties {
private final Properties properties;
private BuildProperties() throws IOException {
properties = new Properties();
final InputStream is = new FileInputStream(new File(Environment.getRootDirectory(), "build.prop"));
try {
properties.load(is);
} finally {
Utils.closeSilently(is);
}
}
public boolean containsKey(final Object key) {
return properties.containsKey(key);
}
public boolean containsValue(final Object value) {
return properties.containsValue(value);
}
public Set<Entry<Object, Object>> entrySet() {
return properties.entrySet();
}
public String getProperty(final String name) {
return properties.getProperty(name);
}
public String getProperty(final String name, final String defaultValue) {
return properties.getProperty(name, defaultValue);
}
public boolean isEmpty() {
return properties.isEmpty();
}
public Enumeration<Object> keys() {
return properties.keys();
}
public Set<Object> keySet() {
return properties.keySet();
}
public int size() {
return properties.size();
}
public Collection<Object> values() {
return properties.values();
}
public static BuildProperties newInstance() throws IOException {
return new BuildProperties();
}
}

View File

@ -43,10 +43,7 @@ public class CheckUtils {
return false;
}
if (start < 0 || end < 0) {
return false;
}
return true;
return !(start < 0 || end < 0);
}
public static boolean isValidLocale(String locale) {

View File

@ -237,7 +237,7 @@ public class TwitterWrapper implements Constants {
final ContentResolver cr = context.getContentResolver();
String type = cr.getType(imageUri);
if (type == null) {
type = Utils.getImageMimeType(cr, imageUri);
type = BitmapUtils.getImageMimeType(cr, imageUri);
}
final ContentType contentType;
final String extension;

View File

@ -36,15 +36,9 @@ import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.PorterDuff.Mode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.graphics.drawable.TransitionDrawable;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
@ -65,13 +59,8 @@ import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.StringRes;
import android.support.annotation.WorkerThread;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.ListFragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.net.ConnectivityManagerCompat;
import android.support.v4.util.Pair;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.accessibility.AccessibilityEventCompat;
import android.support.v7.app.AppCompatActivity;
@ -95,11 +84,8 @@ import android.view.View;
import android.view.Window;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.webkit.MimeTypeMap;
import android.widget.AbsListView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.commons.lang3.ArrayUtils;
@ -155,12 +141,10 @@ import org.mariotaku.twidere.fragment.UserMediaTimelineFragment;
import org.mariotaku.twidere.fragment.UserMentionsFragment;
import org.mariotaku.twidere.fragment.UserProfileEditorFragment;
import org.mariotaku.twidere.fragment.UserTimelineFragment;
import org.mariotaku.twidere.fragment.iface.IBaseFragment.SystemWindowsInsetsCallback;
import org.mariotaku.twidere.graphic.PaddingDrawable;
import org.mariotaku.twidere.model.AccountPreferences;
import org.mariotaku.twidere.model.ParcelableAccount;
import org.mariotaku.twidere.model.ParcelableCredentials;
import org.mariotaku.twidere.model.ParcelableCredentialsCursorIndices;
import org.mariotaku.twidere.model.ParcelableDirectMessage;
import org.mariotaku.twidere.model.ParcelableDirectMessageCursorIndices;
import org.mariotaku.twidere.model.ParcelableStatus;
@ -193,18 +177,13 @@ import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.CRC32;
import javax.net.ssl.SSLException;
@ -215,7 +194,6 @@ import static org.mariotaku.twidere.provider.TwidereDataStore.DIRECT_MESSAGES_UR
import static org.mariotaku.twidere.provider.TwidereDataStore.STATUSES_URIS;
import static org.mariotaku.twidere.util.TwidereLinkify.PATTERN_TWITTER_PROFILE_IMAGES;
@SuppressWarnings("unused")
public final class Utils implements Constants {
public static final Pattern PATTERN_XML_RESOURCE_IDENTIFIER = Pattern.compile("res/xml/([\\w_]+)\\.xml");
@ -372,32 +350,6 @@ public final class Utils implements Constants {
return Math.max(1, result);
}
public static boolean checkActivityValidity(final Context context, final Intent intent) {
final PackageManager pm = context.getPackageManager();
return !pm.queryIntentActivities(intent, 0).isEmpty();
}
public static void clearListViewChoices(final AbsListView view) {
if (view == null) return;
final ListAdapter adapter = view.getAdapter();
if (adapter == null) return;
view.clearChoices();
for (int i = 0, j = view.getChildCount(); i < j; i++) {
view.setItemChecked(i, false);
}
view.post(new Runnable() {
@Override
public void run() {
view.setChoiceMode(AbsListView.CHOICE_MODE_NONE);
}
});
// Workaround for Android bug
// http://stackoverflow.com/questions/9754170/listview-selection-remains-persistent-after-exiting-choice-mode
// final int position = view.getFirstVisiblePosition(), offset = Utils.getFirstChildOffset(view);
// view.setAdapter(adapter);
// Utils.scrollListToPosition(view, position, offset);
}
public static boolean closeSilently(final Closeable c) {
if (c == null) return false;
try {
@ -845,28 +797,6 @@ public final class Utils implements Constants {
return tag + "_" + accountKey;
}
public static String encodeQueryParams(final String value) throws IOException {
final String encoded = URLEncoder.encode(value, "UTF-8");
final StringBuilder buf = new StringBuilder();
final int length = encoded.length();
char focus;
for (int i = 0; i < length; i++) {
focus = encoded.charAt(i);
if (focus == '*') {
buf.append("%2A");
} else if (focus == '+') {
buf.append("%20");
} else if (focus == '%' && i + 1 < encoded.length() && encoded.charAt(i + 1) == '7'
&& encoded.charAt(i + 2) == 'E') {
buf.append('~');
i += 2;
} else {
buf.append(focus);
}
}
return buf.toString();
}
public static ParcelableDirectMessage findDirectMessageInDatabases(final Context context,
final UserKey accountKey,
final long messageId) {
@ -943,33 +873,6 @@ public final class Utils implements Constants {
return DateUtils.formatDateTime(context, timestamp, DateUtils.FORMAT_SHOW_DATE);
}
@SuppressWarnings("deprecation")
public static String formatTimeStampString(final Context context, final long timestamp) {
if (context == null) return null;
final Time then = new Time();
then.set(timestamp);
final Time now = new Time();
now.setToNow();
int format_flags = DateUtils.FORMAT_NO_NOON_MIDNIGHT | DateUtils.FORMAT_ABBREV_ALL | DateUtils.FORMAT_CAP_AMPM;
if (then.year != now.year) {
format_flags |= DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_SHOW_DATE;
} else if (then.yearDay != now.yearDay) {
format_flags |= DateUtils.FORMAT_SHOW_DATE;
} else {
format_flags |= DateUtils.FORMAT_SHOW_TIME;
}
return DateUtils.formatDateTime(context, timestamp, format_flags);
}
@SuppressWarnings("deprecation")
public static String formatTimeStampString(final Context context, final String date_time) {
if (context == null) return null;
return formatTimeStampString(context, Date.parse(date_time));
}
@SuppressWarnings("deprecation")
public static String formatToLongTimeString(final Context context, final long timestamp) {
if (context == null) return null;
@ -985,10 +888,6 @@ public final class Utils implements Constants {
return DateUtils.formatDateTime(context, timestamp, format_flags);
}
public static int getAccountNotificationId(final int notificationType, final long accountId) {
return Arrays.hashCode(new long[]{notificationType, accountId});
}
public static boolean isComposeNowSupported(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN || context == null) return false;
return hasNavBar(context);
@ -1014,16 +913,6 @@ public final class Utils implements Constants {
return isOAuth && TwitterContentUtils.isOfficialKey(context, consumerKey, consumerSecret);
}
public static TextView newSectionView(final Context context, final int titleRes) {
return newSectionView(context, titleRes != 0 ? context.getString(titleRes) : null);
}
public static TextView newSectionView(final Context context, final CharSequence title) {
final TextView textView = new TextView(context, null, android.R.attr.listSeparatorTextViewStyle);
textView.setText(title);
return textView;
}
public static boolean setLastSeen(Context context, ParcelableUserMention[] entities, long time) {
if (entities == null) return false;
boolean result = false;
@ -1047,61 +936,6 @@ public final class Utils implements Constants {
return cr.update(CachedUsers.CONTENT_URI, values, where, selectionArgs) > 0;
}
public static File getBestCacheDir(final Context context, final String cacheDirName) {
if (context == null) throw new NullPointerException();
final File extCacheDir;
try {
// Workaround for https://github.com/mariotaku/twidere/issues/138
extCacheDir = context.getExternalCacheDir();
} catch (final Exception e) {
return new File(context.getCacheDir(), cacheDirName);
}
if (extCacheDir != null && extCacheDir.isDirectory()) {
final File cacheDir = new File(extCacheDir, cacheDirName);
if (cacheDir.isDirectory() || cacheDir.mkdirs()) return cacheDir;
}
return new File(context.getCacheDir(), cacheDirName);
}
public static String getBiggerTwitterProfileImage(final String url) {
return getTwitterProfileImageOfSize(url, "bigger");
}
public static Bitmap getBitmap(final Drawable drawable) {
if (drawable instanceof NinePatchDrawable) return null;
if (drawable instanceof BitmapDrawable)
return ((BitmapDrawable) drawable).getBitmap();
else if (drawable instanceof TransitionDrawable) {
final int layer_count = ((TransitionDrawable) drawable).getNumberOfLayers();
for (int i = 0; i < layer_count; i++) {
final Drawable layer = ((TransitionDrawable) drawable).getDrawable(i);
if (layer instanceof BitmapDrawable) return ((BitmapDrawable) layer).getBitmap();
}
}
return null;
}
public static Bitmap.CompressFormat getBitmapCompressFormatByMimeType(final String mimeType,
final Bitmap.CompressFormat def) {
final String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
if ("jpeg".equalsIgnoreCase(extension) || "jpg".equalsIgnoreCase(extension))
return Bitmap.CompressFormat.JPEG;
else if ("png".equalsIgnoreCase(extension))
return Bitmap.CompressFormat.PNG;
else if ("webp".equalsIgnoreCase(extension)) return Bitmap.CompressFormat.WEBP;
return def;
}
public static int getCardHighlightColor(final Context context, final boolean isMention,
final boolean isFavorite, final boolean isRetweet) {
if (isMention)
return ContextCompat.getColor(context, R.color.highlight_reply);
else if (isFavorite)
return ContextCompat.getColor(context, R.color.highlight_like);
else if (isRetweet) ContextCompat.getColor(context, R.color.highlight_retweet);
return Color.TRANSPARENT;
}
public static Selectable getColumnsFromProjection(final String... projection) {
if (projection == null) return new AllColumns();
@ -1168,48 +1002,6 @@ public final class Utils implements Constants {
return t.getMessage();
}
public static int getFirstChildOffset(final AbsListView list) {
if (list == null || list.getChildCount() == 0) return 0;
final View child = list.getChildAt(0);
final int[] location = new int[2];
child.getLocationOnScreen(location);
Log.d(LOGTAG, String.format("getFirstChildOffset %d vs %d", child.getTop(), location[1]));
return child.getTop();
}
public static String getImageMimeType(final File image) {
if (image == null) return null;
final BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(image.getPath(), o);
return o.outMimeType;
}
public static String getImageMimeType(final InputStream is) {
if (is == null) return null;
final BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, o);
return o.outMimeType;
}
@Nullable
public static String getImageMimeType(ContentResolver cr, final Uri uri) {
if (uri == null) return null;
final BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
InputStream is = null;
try {
is = cr.openInputStream(uri);
BitmapFactory.decodeStream(is, null, o);
return o.outMimeType;
} catch (IOException e) {
return null;
} finally {
closeSilently(is);
}
}
public static String getImagePathFromUri(final Context context, final Uri uri) {
if (context == null || uri == null) return null;
@ -1262,17 +1054,6 @@ public final class Utils implements Constants {
return new File(context.getCacheDir(), cacheDirName);
}
public static String getLinkHighlightingStyleName(final Context context) {
if (context == null) return null;
final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
return prefs.getString(KEY_LINK_HIGHLIGHT_OPTION, VALUE_LINK_HIGHLIGHT_OPTION_NONE);
}
@HighlightStyle
public static int getLinkHighlightingStyle(final Context context) {
return getLinkHighlightingStyleInt(getLinkHighlightingStyleName(context));
}
@HighlightStyle
public static int getLinkHighlightingStyleInt(final String option) {
if (option == null) return VALUE_LINK_HIGHLIGHT_OPTION_CODE_NONE;
@ -1381,10 +1162,6 @@ public final class Utils implements Constants {
return result;
}
public static String getReasonablySmallTwitterProfileImage(final String url) {
return getTwitterProfileImageOfSize(url, "reasonably_small");
}
public static int getResId(final Context context, final String string) {
if (context == null || string == null) return 0;
Matcher m = PATTERN_RESOURCE_IDENTIFIER.matcher(string);
@ -1396,13 +1173,6 @@ public final class Utils implements Constants {
}
public static String getSenderUserName(final Context context, final ParcelableDirectMessage user) {
if (context == null || user == null) return null;
final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
final boolean display_name = prefs.getBoolean(KEY_NAME_FIRST, true);
return display_name ? user.sender_name : "@" + user.sender_screen_name;
}
public static String getShareStatus(final Context context, final CharSequence title, final CharSequence text) {
if (context == null) return null;
String share_format = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE).getString(
@ -1433,11 +1203,6 @@ public final class Utils implements Constants {
return VALUE_TAB_DISPLAY_OPTION_CODE_BOTH;
}
public static long getTimestampFromDate(final Date date) {
if (date == null) return -1;
return date.getTime();
}
public static boolean hasNavBar(@NonNull Context context) {
final Resources resources = context.getResources();
if (resources == null) return false;
@ -1518,43 +1283,11 @@ public final class Utils implements Constants {
return 0;
}
public static boolean hasAccountSignedWithOfficialKeys(final Context context) {
if (context == null) return false;
final Cursor cur = context.getContentResolver().query(Accounts.CONTENT_URI, Accounts.COLUMNS, null, null, null);
if (cur == null) return false;
final String[] keySecrets = context.getResources().getStringArray(R.array.values_official_consumer_secret_crc32);
final ParcelableCredentialsCursorIndices indices = new ParcelableCredentialsCursorIndices(cur);
cur.moveToFirst();
final CRC32 crc32 = new CRC32();
try {
while (!cur.isAfterLast()) {
final String consumerSecret = cur.getString(indices.consumer_secret);
if (consumerSecret != null) {
final byte[] consumerSecretBytes = consumerSecret.getBytes(Charset.forName("UTF-8"));
crc32.update(consumerSecretBytes, 0, consumerSecretBytes.length);
final long value = crc32.getValue();
crc32.reset();
for (final String keySecret : keySecrets) {
if (Long.parseLong(keySecret, 16) == value) return true;
}
}
cur.moveToNext();
}
} finally {
cur.close();
}
return false;
}
public static boolean hasAutoRefreshAccounts(final Context context) {
final UserKey[] accountKeys = DataStoreUtils.getAccountKeys(context);
return !ArrayUtils.isEmpty(AccountPreferences.getAutoRefreshEnabledAccountIds(context, accountKeys));
}
public static boolean hasStaggeredTimeline() {
return false;
}
public static boolean isBatteryOkay(final Context context) {
if (context == null) return false;
final Context app = context.getApplicationContext();
@ -1567,18 +1300,6 @@ public final class Utils implements Constants {
return plugged || level / scale > 0.15f;
}
public static boolean isDatabaseReady(final Context context) {
final Cursor c = context.getContentResolver().query(TwidereDataStore.CONTENT_URI_DATABASE_READY, null, null, null,
null);
try {
return c != null;
} finally {
if (c != null) {
c.close();
}
}
}
public static boolean isMyAccount(final Context context, @Nullable final UserKey accountKey) {
if (context == null || accountKey == null) return false;
final String[] projection = new String[]{SQLFunctions.COUNT()};
@ -1626,16 +1347,6 @@ public final class Utils implements Constants {
}
}
@Deprecated
public static boolean isUserLoggedIn(final Context context, final String accountId) {
if (context == null) return false;
final UserKey[] ids = DataStoreUtils.getAccountKeys(context);
for (final UserKey id : ids) {
if (TextUtils.equals(id.getId(), accountId)) return true;
}
return false;
}
public static int matchLinkId(@Nullable final Uri uri) {
if (uri == null) return UriMatcher.NO_MATCH;
return LINK_HANDLER_URI_MATCHER.match(uri);
@ -1705,13 +1416,6 @@ public final class Utils implements Constants {
return top - actionBarHeight;
}
public static int getInsetsTopWithoutActionBarHeight(Context context, int top, int actionBarHeight) {
if (actionBarHeight > top) {
return top;
}
return top - actionBarHeight;
}
public static void restartActivity(final Activity activity) {
if (activity == null) return;
final int enterAnim = android.R.anim.fade_in;
@ -1817,16 +1521,6 @@ public final class Utils implements Constants {
showInfoMessage(context, context.getText(resId), long_message);
}
public static void showMenuItemToast(final View v, final CharSequence text) {
final int[] screenPos = new int[2];
final Rect displayFrame = new Rect();
v.getLocationOnScreen(screenPos);
v.getWindowVisibleDisplayFrame(displayFrame);
final int height = v.getHeight();
final int midy = screenPos[1] + height / 2;
showMenuItemToast(v, text, midy >= displayFrame.height());
}
public static void showMenuItemToast(final View v, final CharSequence text, final boolean isBottomBar) {
final int[] screenPos = new int[2];
final Rect displayFrame = new Rect();
@ -1903,17 +1597,6 @@ public final class Utils implements Constants {
showErrorMessage(context, message, long_message);
}
public static void showWarnMessage(final Context context, final CharSequence message, final boolean longMessage) {
if (context == null || TextUtils.isEmpty(message)) return;
final Toast toast = Toast.makeText(context, message, longMessage ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT);
toast.show();
}
public static void showWarnMessage(final Context context, final int resId, final boolean long_message) {
if (context == null) return;
showWarnMessage(context, context.getText(resId), long_message);
}
public static void startRefreshServiceIfNeeded(@NonNull final Context context) {
final Context appContext = context.getApplicationContext();
if (appContext == null) return;
@ -1975,10 +1658,6 @@ public final class Utils implements Constants {
resolver.insert(CachedRelationships.CONTENT_URI, values);
}
public static boolean useShareScreenshot() {
return Boolean.parseBoolean("false");
}
private static Drawable getMetadataDrawable(final PackageManager pm, final ActivityInfo info, final String key) {
if (pm == null || info == null || info.metaData == null || key == null || !info.metaData.containsKey(key))
return null;
@ -2025,22 +1704,6 @@ public final class Utils implements Constants {
return 0;
}
public static void makeListFragmentFitsSystemWindows(ListFragment fragment) {
final FragmentActivity activity = fragment.getActivity();
if (!(activity instanceof SystemWindowsInsetsCallback)) return;
final SystemWindowsInsetsCallback callback = (SystemWindowsInsetsCallback) activity;
final Rect insets = new Rect();
if (callback.getSystemWindowsInsets(insets)) {
makeListFragmentFitsSystemWindows(fragment, insets);
}
}
public static void makeListFragmentFitsSystemWindows(ListFragment fragment, Rect insets) {
final ListView listView = fragment.getListView();
listView.setPadding(insets.left, insets.top, insets.right, insets.bottom);
listView.setClipToPadding(false);
}
@Nullable
public static ParcelableUser getUserForConversation(@NonNull final Context context,
@ -2061,13 +1724,6 @@ public final class Utils implements Constants {
return null;
}
@SafeVarargs
public static Bundle makeSceneTransitionOption(final Activity activity,
final Pair<View, String>... sharedElements) {
if (ThemeUtils.isTransparentBackground(activity)) return null;
return ActivityOptionsCompat.makeSceneTransitionAnimation(activity, sharedElements).toBundle();
}
public static void setSharedElementTransition(Context context, Window window, int transitionRes) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return;
@ -2110,14 +1766,6 @@ public final class Utils implements Constants {
return UtilsL.getErrorNo(t);
}
public static boolean isOutOfMemory(Throwable ex) {
if (ex == null) return false;
final Throwable cause = ex.getCause();
if (cause == null || cause == ex) return false;
if (cause instanceof OutOfMemoryError) return true;
return isOutOfMemory(cause);
}
public static void logOpenNotificationFromUri(Context context, Uri uri) {
if (!uri.getBooleanQueryParameter(QUERY_PARAM_FROM_NOTIFICATION, false)) return;
final String type = uri.getQueryParameter(QUERY_PARAM_NOTIFICATION_TYPE);
@ -2133,19 +1781,6 @@ public final class Utils implements Constants {
HotMobiLogger.getInstance(context).log(accountKey, event);
}
public static boolean hasOfficialAPIAccess(@NonNull Context context, @NonNull ParcelableCredentials account) {
if (ParcelableAccount.Type.TWITTER.equals(account.account_type)) {
final TwitterAccountExtra extra = JsonSerializer.parse(account.account_extras,
TwitterAccountExtra.class);
if (extra != null) {
return extra.isOfficialCredentials();
}
}
final boolean isOAuth = ParcelableCredentialsUtils.isOAuth(account.auth_type);
final String consumerKey = account.consumer_key, consumerSecret = account.consumer_secret;
return isOAuth && TwitterContentUtils.isOfficialKey(context, consumerKey, consumerSecret);
}
public static int getNotificationId(int baseId, @Nullable UserKey accountId) {
int result = baseId;
result = 31 * result + (accountId != null ? accountId.hashCode() : 0);
@ -2195,23 +1830,13 @@ public final class Utils implements Constants {
}
/**
* Send Notifications to Pebble smartwatches
*
* @param context Context
* @param message String
*/
public static void sendPebbleNotification(final Context context, final String message) {
sendPebbleNotification(context, null, message);
}
/**
* Send Notifications to Pebble smartwatches
* Send Notifications to Pebble smart watches
*
* @param context Context
* @param title String
* @param message String
*/
public static void sendPebbleNotification(final Context context, final String title, final String message) {
public static void sendPebbleNotification(@NonNull final Context context, @Nullable final String title, @NonNull final String message) {
String appName;
if (title == null) {
@ -2220,7 +1845,7 @@ public final class Utils implements Constants {
appName = context.getString(R.string.app_name) + " - " + title;
}
if (context == null || TextUtils.isEmpty(message)) return;
if (TextUtils.isEmpty(message)) return;
final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
if (prefs.getBoolean(KEY_PEBBLE_NOTIFICATIONS, false)) {

View File

@ -1,38 +0,0 @@
/*
* Twidere - Twitter client for Android
*
* Copyright (C) 2012-2015 Mariotaku Lee <mariotaku.lee@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mariotaku.twidere.util;
import java.io.File;
/**
* Created by mariotaku on 15/12/31.
*/
public interface VideoLoadingListener {
void onVideoLoadingCancelled(String uri, VideoLoadingListener listener);
void onVideoLoadingComplete(String uri, VideoLoadingListener listener, File file);
void onVideoLoadingFailed(String uri, VideoLoadingListener listener, Exception e);
void onVideoLoadingProgressUpdate(String uri, VideoLoadingListener listener, int current, int total);
void onVideoLoadingStarted(String uri, VideoLoadingListener listener);
}

View File

@ -55,10 +55,7 @@ public class TwitterMediaProvider implements Provider {
}
final String path = UriUtils.getPath(link);
if (path == null) return false;
if (path.startsWith("/media/")) {
return true;
}
return false;
return path.startsWith("/media/");
}
}

View File

@ -1175,7 +1175,7 @@ class ComposeActivity : BaseActivity(), OnMenuItemClickListener, OnClickListener
if (locationText!!.tag == null || location != recentLocation) {
val task = DisplayPlaceNameTask(this)
task.params = location
task.setCallback(locationText)
task.callback = locationText
TaskStarter.execute(task)
}
}

View File

@ -405,7 +405,7 @@ class LinkHandlerActivity : BaseActivity(), SystemWindowsInsetsCallback, IContro
val actionBar = supportActionBar
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true)
actionBar.setSubtitle(mSubtitle)
actionBar.subtitle = mSubtitle
}
}

View File

@ -728,48 +728,48 @@ class SignInActivity : BaseActivity(), OnClickListener, TextWatcher {
when (authType) {
ParcelableCredentials.AuthType.BASIC -> {
values = ContentValues()
values.put(TwidereDataStore.Accounts.BASIC_AUTH_USERNAME, basicUsername)
values.put(TwidereDataStore.Accounts.BASIC_AUTH_PASSWORD, basicPassword)
values.put(TwidereDataStore.Accounts.AUTH_TYPE, ParcelableCredentials.AuthType.BASIC)
values.put(Accounts.BASIC_AUTH_USERNAME, basicUsername)
values.put(Accounts.BASIC_AUTH_PASSWORD, basicPassword)
values.put(Accounts.AUTH_TYPE, ParcelableCredentials.AuthType.BASIC)
}
ParcelableCredentials.AuthType.TWIP_O_MODE -> {
values = ContentValues()
values.put(TwidereDataStore.Accounts.AUTH_TYPE, ParcelableCredentials.AuthType.TWIP_O_MODE)
values.put(Accounts.AUTH_TYPE, ParcelableCredentials.AuthType.TWIP_O_MODE)
}
ParcelableCredentials.AuthType.OAUTH, ParcelableCredentials.AuthType.XAUTH -> {
values = ContentValues()
val accessToken = oauth!!.oauthToken
values.put(TwidereDataStore.Accounts.OAUTH_TOKEN, accessToken.oauthToken)
values.put(TwidereDataStore.Accounts.OAUTH_TOKEN_SECRET, accessToken.oauthTokenSecret)
values.put(TwidereDataStore.Accounts.CONSUMER_KEY, oauth.getConsumerKey())
values.put(TwidereDataStore.Accounts.CONSUMER_SECRET, oauth.getConsumerSecret())
values.put(TwidereDataStore.Accounts.AUTH_TYPE, authType)
values.put(Accounts.OAUTH_TOKEN, accessToken.oauthToken)
values.put(Accounts.OAUTH_TOKEN_SECRET, accessToken.oauthTokenSecret)
values.put(Accounts.CONSUMER_KEY, oauth.consumerKey)
values.put(Accounts.CONSUMER_SECRET, oauth.consumerSecret)
values.put(Accounts.AUTH_TYPE, authType)
}
else -> {
return null
}
}
values.put(TwidereDataStore.Accounts.ACCOUNT_KEY, UserKeyUtils.fromUser(user).toString())
values.put(TwidereDataStore.Accounts.SCREEN_NAME, user.screenName)
values.put(TwidereDataStore.Accounts.NAME, user.name)
values.put(TwidereDataStore.Accounts.PROFILE_IMAGE_URL, TwitterContentUtils.getProfileImageUrl(user))
values.put(TwidereDataStore.Accounts.PROFILE_BANNER_URL, user.profileBannerImageUrl)
values.put(Accounts.ACCOUNT_KEY, UserKeyUtils.fromUser(user).toString())
values.put(Accounts.SCREEN_NAME, user.screenName)
values.put(Accounts.NAME, user.name)
values.put(Accounts.PROFILE_IMAGE_URL, TwitterContentUtils.getProfileImageUrl(user))
values.put(Accounts.PROFILE_BANNER_URL, user.profileBannerImageUrl)
values.put(TwidereDataStore.Accounts.COLOR, color)
values.put(TwidereDataStore.Accounts.IS_ACTIVATED, 1)
values.put(Accounts.COLOR, color)
values.put(Accounts.IS_ACTIVATED, 1)
values.put(TwidereDataStore.Accounts.API_URL_FORMAT, apiUrlFormat)
values.put(TwidereDataStore.Accounts.SAME_OAUTH_SIGNING_URL, sameOAuthSigningUrl)
values.put(TwidereDataStore.Accounts.NO_VERSION_SUFFIX, noVersionSuffix)
values.put(Accounts.API_URL_FORMAT, apiUrlFormat)
values.put(Accounts.SAME_OAUTH_SIGNING_URL, sameOAuthSigningUrl)
values.put(Accounts.NO_VERSION_SUFFIX, noVersionSuffix)
if (accountType != null) {
values.put(TwidereDataStore.Accounts.ACCOUNT_TYPE, accountType.first)
values.put(TwidereDataStore.Accounts.ACCOUNT_EXTRAS, accountType.second)
values.put(Accounts.ACCOUNT_TYPE, accountType.first)
values.put(Accounts.ACCOUNT_EXTRAS, accountType.second)
val accountKey = UserKeyUtils.fromUser(user)
val parcelableUser = ParcelableUserUtils.fromUser(user, accountKey)
values.put(TwidereDataStore.Accounts.ACCOUNT_USER, JsonSerializer.serialize(parcelableUser, ParcelableUser::class.java))
values.put(Accounts.ACCOUNT_USER, JsonSerializer.serialize(parcelableUser, ParcelableUser::class.java))
}
return values
}

View File

@ -390,7 +390,7 @@ abstract class AbsActivitiesFragment protected constructor() : AbsContentListRec
}
}
}
task.setCallback(recyclerView)
task.callback = recyclerView
TaskStarter.execute(task)
bus.register(statusesBusCallback)
}

View File

@ -314,8 +314,8 @@ class AccountsDashboardFragment : BaseSupportFragment(), LoaderCallbacks<Account
profileContainer.setOnClickListener(this)
accountProfileBanner.setInAnimation(getContext(), android.R.anim.fade_in)
accountProfileBanner.setOutAnimation(getContext(), android.R.anim.fade_out)
accountProfileBanner.setInAnimation(context, android.R.anim.fade_in)
accountProfileBanner.setOutAnimation(context, android.R.anim.fade_out)
accountProfileBanner.setFactory {
inflater.inflate(R.layout.layout_account_dashboard_profile_image,
accountProfileBanner, false)
@ -352,7 +352,7 @@ class AccountsDashboardFragment : BaseSupportFragment(), LoaderCallbacks<Account
}
internal fun updateAccountActions() {
val activity = activity as HomeActivity ?: return
val activity = activity as HomeActivity
val tabs = activity.tabs
val account = mAccountsAdapter!!.selectedAccount ?: return
var hasDmTab = false

View File

@ -130,7 +130,7 @@ abstract class CursorActivitiesFragment : AbsActivitiesFragment() {
reloadActivities()
}
}
cr!!.registerContentObserver(Accounts.CONTENT_URI, true, mContentObserver!!)
cr.registerContentObserver(Accounts.CONTENT_URI, true, mContentObserver!!)
cr.registerContentObserver(Filters.CONTENT_URI, true, mContentObserver!!)
updateRefreshState()
reloadActivities()
@ -149,7 +149,7 @@ abstract class CursorActivitiesFragment : AbsActivitiesFragment() {
override fun onStop() {
val cr = contentResolver
cr!!.unregisterContentObserver(mContentObserver!!)
cr.unregisterContentObserver(mContentObserver!!)
super.onStop()
}

View File

@ -227,7 +227,7 @@ class HostMappingsListFragment : BaseListFragment(), MultiChoiceModeListener, On
}
private fun updateButton() {
val dialog = dialog as AlertDialog ?: return
val dialog = dialog as AlertDialog
val hostValid = !isEmpty(mEditHost!!.text)
val addressValid = !isEmpty(mEditAddress!!.text) || mCheckExclude!!.isChecked
val positiveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE)

View File

@ -568,7 +568,7 @@ class MessagesConversationFragment : BaseSupportFragment(), LoaderCallbacks<Curs
val activity = activity
if (activity !is BaseActivity) return false
if (activity.keyMetaState != 0) return false
val account = actionBarCustomView.accountSpinner.selectedItem as ParcelableCredentials ?: return false
val account = actionBarCustomView.accountSpinner.selectedItem as ParcelableCredentials
editText.setAccountKey(account.account_key)
searchUsers(account.account_key, ParseUtils.parseString(actionBarCustomView.editUserQuery.text), false)
return true

View File

@ -1915,7 +1915,7 @@ class StatusFragment : BaseSupportFragment(), LoaderCallbacks<SingleResponse<Par
if (heightBeforeSpace != 0) {
val spaceHeight = recyclerView.measuredHeight - heightBeforeSpace
this.spaceHeight = Math.max(0, spaceHeight)
return this.spaceHeight;
return this.spaceHeight
}
}
return super.getDecoratedMeasuredHeight(child)
@ -2022,7 +2022,7 @@ class StatusFragment : BaseSupportFragment(), LoaderCallbacks<SingleResponse<Par
if (adapter.isRepliesLoading) {
count += adapter.getTypeCount(StatusAdapter.ITEM_IDX_REPLY_LOAD_MORE)
}
val spaceHeight = calculateSpaceHeight();
val spaceHeight = calculateSpaceHeight()
if (spaceHeight > 0) {
count += adapter.getTypeCount(StatusAdapter.ITEM_IDX_SPACE)
}

View File

@ -335,7 +335,7 @@ class UserFragment : BaseSupportFragment(), OnClickListener, OnLinkClickListener
}
private fun updateSubtitle() {
val activity = activity as AppCompatActivity ?: return
val activity = activity as AppCompatActivity
val actionBar = activity.supportActionBar ?: return
val user = this.user
if (user == null) {
@ -1150,7 +1150,7 @@ class UserFragment : BaseSupportFragment(), OnClickListener, OnLinkClickListener
return true
}
TwidereLinkify.LINK_TYPE_LIST -> {
val mentionList = link.split("/".toRegex()).dropLastWhile { it.isEmpty() }
val mentionList = link.split("/").dropLastWhile(String::isEmpty)
if (mentionList.size != 2) {
return false
}

View File

@ -159,7 +159,7 @@ class ParcelableUserLoader(
return response
} catch (e: MicroBlogException) {
Log.w(LOGTAG, e)
return SingleResponse(exception = e);
return SingleResponse(exception = e)
}
}

View File

@ -27,7 +27,7 @@ import android.support.v4.app.Fragment
*/
abstract class MapFragmentFactory {
abstract fun createMapFragment(context: Context): Fragment?
abstract fun createMapFragment(context: Context): Fragment
companion object {

View File

@ -69,11 +69,11 @@ object MenuUtils {
}
fun setItemChecked(menu: Menu?, id: Int, checked: Boolean) {
menu?.setItemChecked(id, checked);
menu?.setItemChecked(id, checked)
}
fun setMenuItemIcon(menu: Menu?, id: Int, @DrawableRes icon: Int) {
menu?.setMenuItemIcon(id, icon);
menu?.setMenuItemIcon(id, icon)
}
fun setMenuItemTitle(menu: Menu?, id: Int, @StringRes icon: Int) {