Improve cache

pull/254/head
Thomas 2 years ago
parent e425528648
commit 154cc63f69

@ -184,6 +184,11 @@
android:theme="@style/AppThemeBarDark" android:theme="@style/AppThemeBarDark"
android:windowSoftInputMode="stateVisible" /> android:windowSoftInputMode="stateVisible" />
<activity
android:name=".activities.CacheActivity"
android:label="@string/action_cache"
android:theme="@style/AppThemeBarDark" />
<provider <provider
android:name="androidx.core.content.FileProvider" android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileProvider" android:authorities="${applicationId}.fileProvider"

@ -16,8 +16,8 @@ package app.fedilab.android;
import static app.fedilab.android.BaseMainActivity.status.DISCONNECTED; import static app.fedilab.android.BaseMainActivity.status.DISCONNECTED;
import static app.fedilab.android.BaseMainActivity.status.UNKNOWN; import static app.fedilab.android.BaseMainActivity.status.UNKNOWN;
import static app.fedilab.android.helper.CacheHelper.deleteDir;
import static app.fedilab.android.helper.Helper.PREF_USER_TOKEN; import static app.fedilab.android.helper.Helper.PREF_USER_TOKEN;
import static app.fedilab.android.helper.Helper.deleteDir;
import static app.fedilab.android.helper.Helper.getCurrentAccount; import static app.fedilab.android.helper.Helper.getCurrentAccount;
import android.annotation.SuppressLint; import android.annotation.SuppressLint;
@ -44,8 +44,6 @@ import android.view.View;
import android.view.inputmethod.InputMethodManager; import android.view.inputmethod.InputMethodManager;
import android.widget.EditText; import android.widget.EditText;
import android.widget.LinearLayout; import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
@ -83,6 +81,7 @@ import app.fedilab.android.activities.ActionActivity;
import app.fedilab.android.activities.AdminActionActivity; import app.fedilab.android.activities.AdminActionActivity;
import app.fedilab.android.activities.AnnouncementActivity; import app.fedilab.android.activities.AnnouncementActivity;
import app.fedilab.android.activities.BaseActivity; import app.fedilab.android.activities.BaseActivity;
import app.fedilab.android.activities.CacheActivity;
import app.fedilab.android.activities.ComposeActivity; import app.fedilab.android.activities.ComposeActivity;
import app.fedilab.android.activities.ContextActivity; import app.fedilab.android.activities.ContextActivity;
import app.fedilab.android.activities.DraftActivity; import app.fedilab.android.activities.DraftActivity;
@ -525,55 +524,13 @@ public abstract class BaseMainActivity extends BaseActivity implements NetworkSt
startActivity(intent); startActivity(intent);
return true; return true;
} else if (itemId == R.id.action_cache) { } else if (itemId == R.id.action_cache) {
new Helper.CacheTask(BaseMainActivity.this); Intent intent = new Intent(BaseMainActivity.this, CacheActivity.class);
startActivity(intent);
return true; return true;
} else if (itemId == R.id.action_proxy) { } else if (itemId == R.id.action_proxy) {
Intent intent = new Intent(BaseMainActivity.this, ProxyActivity.class); Intent intent = new Intent(BaseMainActivity.this, ProxyActivity.class);
startActivity(intent); startActivity(intent);
return true; return true;
} else if (itemId == R.id.action_size) {
float scale = sharedpreferences.getFloat(getString(R.string.SET_FONT_SCALE), 1.0f);
AlertDialog.Builder builder = new AlertDialog.Builder(BaseMainActivity.this, Helper.dialogStyle());
builder.setTitle(R.string.text_size);
View popup_quick_settings = getLayoutInflater().inflate(R.layout.popup_text_size, new LinearLayout(BaseMainActivity.this), false);
builder.setView(popup_quick_settings);
SeekBar set_text_size = popup_quick_settings.findViewById(R.id.set_text_size);
final TextView set_text_size_value = popup_quick_settings.findViewById(R.id.set_text_size_value);
set_text_size_value.setText(String.format("%s%%", scale * 100));
set_text_size.setMax(20);
set_text_size.setProgress((((int) (scale * 100) - 80) / 5));
set_text_size.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
int value = 80 + progress * 5;
float scale = (float) (value) / 100.0f;
set_text_size_value.setText(String.format("%s%%", value));
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putFloat(getString(R.string.SET_FONT_SCALE), scale);
editor.apply();
}
});
builder.setPositiveButton(R.string.validate, (dialog, which) -> {
BaseMainActivity.this.recreate();
recreate();
dialog.dismiss();
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
return true;
} }
return true; return true;
}); });

@ -0,0 +1,85 @@
package app.fedilab.android.activities;
/* Copyright 2022 Thomas Schneider
*
* This file is a part of Fedilab
*
* 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.
*
* Fedilab 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 Fedilab; if not,
* see <http://www.gnu.org/licenses>. */
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.MenuItem;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import java.util.List;
import java.util.Locale;
import app.fedilab.android.R;
import app.fedilab.android.client.entities.app.Account;
import app.fedilab.android.client.entities.app.BaseAccount;
import app.fedilab.android.databinding.ActivityCacheBinding;
import app.fedilab.android.helper.CacheHelper;
import app.fedilab.android.helper.ThemeHelper;
import app.fedilab.android.ui.drawer.CacheAdapter;
public class CacheActivity extends BaseActivity {
private ActivityCacheBinding binding;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ThemeHelper.applyThemeBar(this);
binding = ActivityCacheBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(ContextCompat.getColor(this, R.color.cyanea_primary)));
}
CacheHelper.getCacheValues(CacheActivity.this, size -> {
if (size > 0) {
size = size / 1000000.0f;
}
binding.fileCacheSize.setText(String.format("%s %s", String.format(Locale.getDefault(), "%.2f", size), getString(R.string.cache_units)));
});
new Thread(() -> {
List<BaseAccount> accounts = new Account(CacheActivity.this).getPushNotificationAccounts();
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> {
CacheAdapter cacheAdapter = new CacheAdapter(accounts);
LinearLayoutManager mLayoutManager = new LinearLayoutManager(CacheActivity.this);
binding.cacheRecyclerview.setLayoutManager(mLayoutManager);
binding.cacheRecyclerview.setAdapter(cacheAdapter);
};
mainHandler.post(myRunnable);
}).start();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}

@ -22,6 +22,7 @@ import android.database.sqlite.SQLiteDatabase;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import app.fedilab.android.client.entities.api.Notification; import app.fedilab.android.client.entities.api.Notification;
@ -147,6 +148,30 @@ public class QuickLoad {
return (count > 0); return (count > 0);
} }
/**
* Count statuses in cache for an account
*
* @param account Account {@link Account}
* @return int - Number of statuses
* @throws DBException Exception
*/
public int count(BaseAccount account) throws DBException {
if (db == null) {
throw new DBException("db is null. Wrong initialization.");
}
int count = 0;
Cursor c = db.query(Sqlite.TABLE_QUICK_LOAD, null, Sqlite.COL_USER_ID + " = ? AND " + Sqlite.COL_INSTANCE + " =?",
new String[]{account.user_id, account.instance}, null, null, null, null);
List<QuickLoad> quickLoadList = cursorToQuickLoadList(c);
if (quickLoadList != null) {
for (QuickLoad quickLoad : quickLoadList) {
count += quickLoad.statuses.size();
}
}
return count;
}
/** /**
* @param position - current position in timeline * @param position - current position in timeline
* @param timeLineType - Timeline.TimeLineEnum * @param timeLineType - Timeline.TimeLineEnum
@ -510,20 +535,36 @@ public class QuickLoad {
quickLoad.statuses = statuses.subList(startAt, endAt); quickLoad.statuses = statuses.subList(startAt, endAt);
} }
/** /**
* Convert a cursor to QuickLoad * Restore statusDraft list from db
* *
* @param c Cursor * @param c Cursor
* @return QuickLoad * @return List<Emoji>
*/ */
private QuickLoad cursorToQuickLoad(Cursor c) { private List<QuickLoad> cursorToQuickLoadList(Cursor c) {
//No element found //No element found
if (c.getCount() == 0) { if (c.getCount() == 0) {
c.close(); c.close();
return null; return null;
} }
//Take the first element List<QuickLoad> quickLoads = new ArrayList<>();
c.moveToFirst(); while (c.moveToNext()) {
QuickLoad quickLoad = convertCursorToQuickLoad(c);
quickLoads.add(quickLoad);
}
//Close the cursor
c.close();
return quickLoads;
}
/**
* Convert a cursor to QuickLoad
*
* @param c Cursor
* @return QuickLoad
*/
private QuickLoad convertCursorToQuickLoad(Cursor c) {
QuickLoad quickLoad = new QuickLoad(); QuickLoad quickLoad = new QuickLoad();
quickLoad.id = c.getInt(c.getColumnIndexOrThrow(Sqlite.COL_ID)); quickLoad.id = c.getInt(c.getColumnIndexOrThrow(Sqlite.COL_ID));
quickLoad.instance = c.getString(c.getColumnIndexOrThrow(Sqlite.COL_INSTANCE)); quickLoad.instance = c.getString(c.getColumnIndexOrThrow(Sqlite.COL_INSTANCE));
@ -535,9 +576,26 @@ public class QuickLoad {
quickLoad.notifications = Notification.restoreNotificationsFromString(c.getString(c.getColumnIndexOrThrow(Sqlite.COL_STATUSES))); quickLoad.notifications = Notification.restoreNotificationsFromString(c.getString(c.getColumnIndexOrThrow(Sqlite.COL_STATUSES)));
} }
quickLoad.position = c.getInt(c.getColumnIndexOrThrow(Sqlite.COL_POSITION)); quickLoad.position = c.getInt(c.getColumnIndexOrThrow(Sqlite.COL_POSITION));
//TimelineHelper.filterStatus(_mContext, quickLoad.statuses, TimelineHelper.FilterTimeLineType.PUBLIC); //TimelineHelper.filterStatus(_mContext, quickLoad.statuses, TimelineHelper.FilterTimeLineType.PUBLIC);
quickLoad.statuses = SpannableHelper.convertStatus(_mContext, quickLoad.statuses); quickLoad.statuses = SpannableHelper.convertStatus(_mContext, quickLoad.statuses);
return quickLoad;
}
/**
* Convert a cursor to QuickLoad
*
* @param c Cursor
* @return QuickLoad
*/
private QuickLoad cursorToQuickLoad(Cursor c) {
//No element found
if (c.getCount() == 0) {
c.close();
return null;
}
//Take the first element
c.moveToFirst();
QuickLoad quickLoad = convertCursorToQuickLoad(c);
//Close the cursor //Close the cursor
c.close(); c.close();
return quickLoad; return quickLoad;

@ -343,6 +343,19 @@ public class StatusCache {
return reply; return reply;
} }
public int count(BaseAccount account) throws DBException {
if (db == null) {
throw new DBException("db is null. Wrong initialization.");
}
Cursor mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_STATUS_CACHE
+ " where " + Sqlite.COL_INSTANCE + " = '" + account.instance + "' AND " + Sqlite.COL_USER_ID + " = '" + account.user_id + "'", null);
mCount.moveToFirst();
int count = mCount.getInt(0);
mCount.close();
return count;
}
/** /**
* Convert a cursor to list of statuses * Convert a cursor to list of statuses
* *

@ -73,6 +73,7 @@ public class StatusDraft implements Serializable {
this.db = Sqlite.getInstance(context.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open(); this.db = Sqlite.getInstance(context.getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
} }
/** /**
* Serialized a list of Status class * Serialized a list of Status class
* *
@ -190,6 +191,19 @@ public class StatusDraft implements Serializable {
return db.delete(Sqlite.TABLE_STATUS_DRAFT, Sqlite.COL_USER_ID + " = '" + BaseMainActivity.currentUserID + "' AND " + Sqlite.COL_INSTANCE + " = '" + BaseMainActivity.currentInstance + "'", null); return db.delete(Sqlite.TABLE_STATUS_DRAFT, Sqlite.COL_USER_ID + " = '" + BaseMainActivity.currentUserID + "' AND " + Sqlite.COL_INSTANCE + " = '" + BaseMainActivity.currentInstance + "'", null);
} }
public int count(BaseAccount account) throws DBException {
if (db == null) {
throw new DBException("db is null. Wrong initialization.");
}
Cursor mCount = db.rawQuery("select count(*) from " + Sqlite.TABLE_STATUS_DRAFT
+ " where " + Sqlite.COL_INSTANCE + " = '" + account.instance + "' AND " + Sqlite.COL_USER_ID + " = '" + account.user_id + "'", null);
mCount.moveToFirst();
int count = mCount.getInt(0);
mCount.close();
return count;
}
/** /**
* update statusDraft in db * update statusDraft in db
* *

@ -0,0 +1,197 @@
package app.fedilab.android.helper;
/* Copyright 2022 Thomas Schneider
*
* This file is a part of Fedilab
*
* 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.
*
* Fedilab 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 Fedilab; if not,
* see <http://www.gnu.org/licenses>. */
import static app.fedilab.android.helper.Helper.getCurrentAccount;
import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.SwitchCompat;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import app.fedilab.android.BaseMainActivity;
import app.fedilab.android.R;
import app.fedilab.android.client.entities.app.BaseAccount;
import app.fedilab.android.client.entities.app.QuickLoad;
import app.fedilab.android.client.entities.app.StatusCache;
import app.fedilab.android.client.entities.app.StatusDraft;
import app.fedilab.android.exception.DBException;
import es.dmoral.toasty.Toasty;
public class CacheHelper {
public static void getCacheValues(Context context, Callback callback) {
new Thread(() -> {
long sizeCache = cacheSize(context.getCacheDir().getParentFile());
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> callback.getCacheSize(sizeCache);
mainHandler.post(myRunnable);
}).start();
}
public static void getTimelineValues(Context context, BaseAccount account, CallbackAccount callbackAccount) {
new Thread(() -> {
List<Integer> count = new ArrayList<>();
try {
count.add(new StatusCache(context).count(account));
} catch (DBException e) {
e.printStackTrace();
}
try {
count.add(new QuickLoad(context).count(account));
} catch (DBException e) {
e.printStackTrace();
}
try {
count.add(new StatusDraft(context).count(account));
} catch (DBException e) {
e.printStackTrace();
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> callbackAccount.getcount(count);
mainHandler.post(myRunnable);
}).start();
}
/**
* Retrieves the cache size
*
* @param directory File
* @return long value in Mo
*/
public static long cacheSize(File directory) {
long length = 0;
if (directory == null || directory.length() == 0)
return -1;
for (File file : Objects.requireNonNull(directory.listFiles())) {
if (file.isFile()) {
try {
length += file.length();
} catch (NullPointerException e) {
return -1;
}
} else {
if (!file.getName().equals("databases") && !file.getName().equals("shared_prefs")) {
length += cacheSize(file);
}
}
}
return length;
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
assert children != null;
for (String aChildren : children) {
if (!aChildren.equals("databases") && !aChildren.equals("shared_prefs")) {
boolean success = deleteDir(new File(dir, aChildren));
if (!success) {
return false;
}
}
}
return dir.delete();
} else {
return dir != null && dir.isFile() && dir.delete();
}
}
public interface Callback {
void getCacheSize(float size);
}
public interface CallbackAccount {
void getcount(List<Integer> countStatuses);
}
public static class CacheTask {
private final WeakReference<Context> contextReference;
private float cacheSize;
public CacheTask(Context context) {
contextReference = new WeakReference<>(context);
doInBackground();
}
protected void doInBackground() {
new Thread(() -> {
long sizeCache = cacheSize(contextReference.get().getCacheDir().getParentFile());
cacheSize = 0;
if (sizeCache > 0) {
cacheSize = (float) sizeCache / 1000000.0f;
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> {
AlertDialog.Builder builder = new AlertDialog.Builder(contextReference.get(), Helper.dialogStyle());
LayoutInflater inflater = ((BaseMainActivity) contextReference.get()).getLayoutInflater();
View dialogView = inflater.inflate(R.layout.popup_cache, new LinearLayout(contextReference.get()), false);
TextView message = dialogView.findViewById(R.id.message);
message.setText(contextReference.get().getString(R.string.cache_message, String.format("%s %s", String.format(Locale.getDefault(), "%.2f", cacheSize), contextReference.get().getString(R.string.cache_units))));
builder.setView(dialogView);
builder.setTitle(R.string.cache_title);
final SwitchCompat clean_all = dialogView.findViewById(R.id.clean_all);
final float finalCacheSize = cacheSize;
builder
.setPositiveButton(R.string.clear, (dialog, which) -> new Thread(() -> {
try {
String path = Objects.requireNonNull(contextReference.get().getCacheDir().getParentFile()).getPath();
File dir = new File(path);
if (dir.isDirectory()) {
deleteDir(dir);
}
if (clean_all.isChecked()) {
new QuickLoad(contextReference.get()).deleteForAllAccount();
new StatusCache(contextReference.get()).deleteForAllAccount();
} else {
new QuickLoad(contextReference.get()).deleteForAccount(getCurrentAccount(contextReference.get()));
new StatusCache(contextReference.get()).deleteForAccount(getCurrentAccount(contextReference.get()));
}
Handler mainHandler2 = new Handler(Looper.getMainLooper());
Runnable myRunnable2 = () -> {
Toasty.success(contextReference.get(), contextReference.get().getString(R.string.toast_cache_clear, String.format("%s %s", String.format(Locale.getDefault(), "%.2f", finalCacheSize), contextReference.get().getString(R.string.cache_units))), Toast.LENGTH_LONG).show();
dialog.dismiss();
};
mainHandler2.post(myRunnable2);
} catch (Exception ignored) {
}
}).start())
.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss())
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
};
mainHandler.post(myRunnable);
}).start();
}
}
}

@ -55,7 +55,6 @@ import android.provider.OpenableColumns;
import android.text.TextUtils; import android.text.TextUtils;
import android.util.DisplayMetrics; import android.util.DisplayMetrics;
import android.util.TypedValue; import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu; import android.view.Menu;
import android.view.MenuItem; import android.view.MenuItem;
import android.view.View; import android.view.View;
@ -67,7 +66,6 @@ import android.webkit.URLUtil;
import android.webkit.WebChromeClient; import android.webkit.WebChromeClient;
import android.webkit.WebSettings; import android.webkit.WebSettings;
import android.widget.ImageView; import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
@ -75,7 +73,6 @@ import androidx.annotation.IdRes;
import androidx.annotation.NonNull; import androidx.annotation.NonNull;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat; import androidx.core.app.NotificationManagerCompat;
import androidx.core.content.ContextCompat; import androidx.core.content.ContextCompat;
@ -102,7 +99,6 @@ import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.net.Authenticator; import java.net.Authenticator;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.InetSocketAddress; import java.net.InetSocketAddress;
@ -133,8 +129,6 @@ import app.fedilab.android.broadcastreceiver.ToastMessage;
import app.fedilab.android.client.entities.api.Attachment; import app.fedilab.android.client.entities.api.Attachment;
import app.fedilab.android.client.entities.app.Account; import app.fedilab.android.client.entities.app.Account;
import app.fedilab.android.client.entities.app.BaseAccount; import app.fedilab.android.client.entities.app.BaseAccount;
import app.fedilab.android.client.entities.app.QuickLoad;
import app.fedilab.android.client.entities.app.StatusCache;
import app.fedilab.android.exception.DBException; import app.fedilab.android.exception.DBException;
import app.fedilab.android.sqlite.Sqlite; import app.fedilab.android.sqlite.Sqlite;
import app.fedilab.android.viewmodel.mastodon.OauthVM; import app.fedilab.android.viewmodel.mastodon.OauthVM;
@ -1047,49 +1041,6 @@ public class Helper {
} }
} }
/**
* Retrieves the cache size
*
* @param directory File
* @return long value in Mo
*/
public static long cacheSize(File directory) {
long length = 0;
if (directory == null || directory.length() == 0)
return -1;
for (File file : Objects.requireNonNull(directory.listFiles())) {
if (file.isFile()) {
try {
length += file.length();
} catch (NullPointerException e) {
return -1;
}
} else {
if (!file.getName().equals("databases") && !file.getName().equals("shared_prefs")) {
length += cacheSize(file);
}
}
}
return length;
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
assert children != null;
for (String aChildren : children) {
if (!aChildren.equals("databases") && !aChildren.equals("shared_prefs")) {
boolean success = deleteDir(new File(dir, aChildren));
if (!success) {
return false;
}
}
}
return dir.delete();
} else {
return dir != null && dir.isFile() && dir.delete();
}
}
public static Proxy getProxy(Context context) { public static Proxy getProxy(Context context) {
SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(context);
@ -1626,64 +1577,5 @@ public class Helper {
return currentAccount; return currentAccount;
} }
public static class CacheTask {
private final WeakReference<Context> contextReference;
private float cacheSize;
public CacheTask(Context context) {
contextReference = new WeakReference<>(context);
doInBackground();
}
protected void doInBackground() {
new Thread(() -> {
long sizeCache = cacheSize(contextReference.get().getCacheDir().getParentFile());
cacheSize = 0;
if (sizeCache > 0) {
cacheSize = (float) sizeCache / 1000000.0f;
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = () -> {
AlertDialog.Builder builder = new AlertDialog.Builder(contextReference.get(), Helper.dialogStyle());
LayoutInflater inflater = ((BaseMainActivity) contextReference.get()).getLayoutInflater();
View dialogView = inflater.inflate(R.layout.popup_cache, new LinearLayout(contextReference.get()), false);
TextView message = dialogView.findViewById(R.id.message);
message.setText(contextReference.get().getString(R.string.cache_message, String.format("%s %s", String.format(Locale.getDefault(), "%.2f", cacheSize), contextReference.get().getString(R.string.cache_units))));
builder.setView(dialogView);
builder.setTitle(R.string.cache_title);
final SwitchCompat clean_all = dialogView.findViewById(R.id.clean_all);
final float finalCacheSize = cacheSize;
builder
.setPositiveButton(R.string.clear, (dialog, which) -> new Thread(() -> {
try {
String path = Objects.requireNonNull(contextReference.get().getCacheDir().getParentFile()).getPath();
File dir = new File(path);
if (dir.isDirectory()) {
deleteDir(dir);
}
if (clean_all.isChecked()) {
new QuickLoad(contextReference.get()).deleteForAllAccount();
new StatusCache(contextReference.get()).deleteForAllAccount();
} else {
new QuickLoad(contextReference.get()).deleteForAccount(getCurrentAccount(contextReference.get()));
new StatusCache(contextReference.get()).deleteForAccount(getCurrentAccount(contextReference.get()));
}
Handler mainHandler2 = new Handler(Looper.getMainLooper());
Runnable myRunnable2 = () -> {
Toasty.success(contextReference.get(), contextReference.get().getString(R.string.toast_cache_clear, String.format("%s %s", String.format(Locale.getDefault(), "%.2f", finalCacheSize), contextReference.get().getString(R.string.cache_units))), Toast.LENGTH_LONG).show();
dialog.dismiss();
};
mainHandler2.post(myRunnable2);
} catch (Exception ignored) {
}
}).start())
.setNegativeButton(R.string.cancel, (dialog, which) -> dialog.dismiss())
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
};
mainHandler.post(myRunnable);
}).start();
}
}
} }

@ -0,0 +1,96 @@
package app.fedilab.android.ui.drawer;
/* Copyright 2022 Thomas Schneider
*
* This file is a part of Fedilab
*
* 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.
*
* Fedilab 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 Fedilab; if not,
* see <http://www.gnu.org/licenses>. */
import android.content.Context;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import app.fedilab.android.activities.ProfileActivity;
import app.fedilab.android.client.entities.app.BaseAccount;
import app.fedilab.android.databinding.DrawerCacheBinding;
import app.fedilab.android.helper.CacheHelper;
import app.fedilab.android.helper.MastodonHelper;
public class CacheAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static ProfileActivity.action doAction;
private final List<BaseAccount> accountList;
private Context context;
public CacheAdapter(List<BaseAccount> accountList) {
this.accountList = accountList;
}
public int getCount() {
return accountList.size();
}
public BaseAccount getItem(int position) {
return accountList.get(position);
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
this.context = parent.getContext();
DrawerCacheBinding itemBinding = DrawerCacheBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
return new AccountCacheViewHolder(itemBinding);
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
BaseAccount account = accountList.get(position);
AccountCacheViewHolder holder = (AccountCacheViewHolder) viewHolder;
MastodonHelper.loadPPMastodon(holder.binding.pp, account.mastodon_account);
holder.binding.acct.setText(String.format("@%s@%s", account.mastodon_account.username, account.instance));
holder.binding.displayName.setText(account.mastodon_account.display_name);
CacheHelper.getTimelineValues(context, account, countStatuses -> {
if (countStatuses != null && countStatuses.size() == 3) {
holder.binding.homeCount.setText(String.valueOf(countStatuses.get(0)));
holder.binding.otherCount.setText(String.valueOf(countStatuses.get(1)));
holder.binding.draftCount.setText(String.valueOf(countStatuses.get(2)));
}
});
}
public long getItemId(int position) {
return position;
}
@Override
public int getItemCount() {
return accountList.size();
}
public static class AccountCacheViewHolder extends RecyclerView.ViewHolder {
DrawerCacheBinding binding;
AccountCacheViewHolder(DrawerCacheBinding itemView) {
super(itemView.getRoot());
binding = itemView;
}
}
}

@ -19,8 +19,12 @@ import android.os.Bundle;
import androidx.preference.PreferenceFragmentCompat; import androidx.preference.PreferenceFragmentCompat;
import androidx.preference.PreferenceManager; import androidx.preference.PreferenceManager;
import androidx.preference.PreferenceScreen;
import androidx.preference.SeekBarPreference;
import app.fedilab.android.R; import app.fedilab.android.R;
import app.fedilab.android.helper.Helper;
import es.dmoral.toasty.Toasty;
public class FragmentInterfaceSettings extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener { public class FragmentInterfaceSettings extends PreferenceFragmentCompat implements SharedPreferences.OnSharedPreferenceChangeListener {
@ -30,8 +34,21 @@ public class FragmentInterfaceSettings extends PreferenceFragmentCompat implemen
createPref(); createPref();
} }
boolean recreate;
private void createPref() { private void createPref() {
getPreferenceScreen().removeAll();
addPreferencesFromResource(R.xml.pref_interface);
PreferenceScreen preferenceScreen = getPreferenceScreen();
if (preferenceScreen == null) {
Toasty.error(requireActivity(), getString(R.string.toast_error), Toasty.LENGTH_SHORT).show();
return;
}
SeekBarPreference SET_FONT_SCALE = findPreference(getString(R.string.SET_FONT_SCALE_INT));
if (SET_FONT_SCALE != null) {
SET_FONT_SCALE.setMax(180);
SET_FONT_SCALE.setMin(80);
}
recreate = false;
} }
@Override @Override
@ -39,7 +56,12 @@ public class FragmentInterfaceSettings extends PreferenceFragmentCompat implemen
if (getActivity() != null) { if (getActivity() != null) {
SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(requireActivity()); SharedPreferences sharedpreferences = PreferenceManager.getDefaultSharedPreferences(requireActivity());
SharedPreferences.Editor editor = sharedpreferences.edit(); SharedPreferences.Editor editor = sharedpreferences.edit();
if (key.compareToIgnoreCase(getString(R.string.SET_FONT_SCALE_INT)) == 0) {
int progress = sharedPreferences.getInt(getString(R.string.SET_FONT_SCALE_INT), 110);
float scale = (float) (progress) / 100.0f;
editor.putFloat(getString(R.string.SET_FONT_SCALE), scale);
recreate = true;
}
editor.apply(); editor.apply();
} }
} }
@ -57,6 +79,11 @@ public class FragmentInterfaceSettings extends PreferenceFragmentCompat implemen
super.onPause(); super.onPause();
getPreferenceScreen().getSharedPreferences() getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this); .unregisterOnSharedPreferenceChangeListener(this);
if (recreate) {
recreate = false;
requireActivity().recreate();
Helper.recreateMainActivity(requireActivity());
}
} }

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="@dimen/fab_margin">
<com.google.android.material.checkbox.MaterialCheckBox
android:id="@+id/label_file_cache"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:checked="true"
android:text="@string/files_cache_size"
app:buttonTint="@color/cyanea_accent_dark_reference"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/file_cache_size"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="@+id/label_file_cache"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="@+id/label_file_cache"
tools:text="105 Mb" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/cache_recyclerview"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/label_file_cache" />
</androidx.constraintlayout.widget.ConstraintLayout>

@ -0,0 +1,108 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.appcompat.widget.AppCompatImageView
android:id="@+id/pp"
android:layout_width="50dp"
android:layout_height="50dp"
android:scaleType="centerCrop"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:src="@tools:sample/avatars" />
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/display_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:maxLines="1"
android:textSize="18sp"
app:layout_constraintStart_toEndOf="@+id/pp"
app:layout_constraintTop_toTopOf="@+id/pp"
tools:text="@tools:sample/full_names" />
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/acct"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:layout_marginTop="5dp"
android:maxLines="1"
android:textSize="16sp"
app:layout_constraintStart_toEndOf="@+id/pp"
app:layout_constraintTop_toBottomOf="@+id/display_name"
tools:text="@tools:sample/last_names" />
<com.google.android.material.checkbox.MaterialCheckBox
android:id="@+id/label_home_timeline_cache_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:checked="true"
android:text="@string/messages_in_cache_for_home"
app:buttonTint="@color/cyanea_accent_dark_reference"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/pp" />
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/home_count"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="@+id/label_home_timeline_cache_count"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="@+id/label_home_timeline_cache_count"
tools:text="50" />
<com.google.android.material.checkbox.MaterialCheckBox
android:id="@+id/label_timelines_cache_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:checked="true"
android:text="@string/messages_in_cache_for_other_timelines"
app:buttonTint="@color/cyanea_accent_dark_reference"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/label_home_timeline_cache_count" />
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/other_count"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="@+id/label_timelines_cache_count"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="@+id/label_timelines_cache_count"
tools:text="150" />
<com.google.android.material.checkbox.MaterialCheckBox
android:id="@+id/label_drafts_count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:checked="false"
android:text="@string/messages_stored_in_drafts"
app:buttonTint="@color/cyanea_accent_dark_reference"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/label_timelines_cache_count" />
<androidx.appcompat.widget.AppCompatTextView
android:id="@+id/draft_count"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="@+id/label_drafts_count"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="@+id/label_drafts_count"
tools:text="49" />
</androidx.constraintlayout.widget.ConstraintLayout>

@ -13,10 +13,6 @@
android:id="@+id/action_proxy" android:id="@+id/action_proxy"
android:title="@string/proxy_set" android:title="@string/proxy_set"
app:showAsAction="never" /> app:showAsAction="never" />
<item
android:id="@+id/action_size"
android:title="@string/text_size"
app:showAsAction="never" />
<item <item
android:id="@+id/action_logout_account" android:id="@+id/action_logout_account"
android:title="@string/action_logout_account" android:title="@string/action_logout_account"

@ -1501,6 +1501,7 @@
<string name="SET_NOTIF_MEDIA" translatable="false">SET_NOTIF_MEDIA</string> <string name="SET_NOTIF_MEDIA" translatable="false">SET_NOTIF_MEDIA</string>
<string name="SET_NOTIF_STATUS" translatable="false">SET_NOTIF_STATUS</string> <string name="SET_NOTIF_STATUS" translatable="false">SET_NOTIF_STATUS</string>
<string name="SET_FONT_SCALE" translatable="false">SET_FONT_SCALE</string> <string name="SET_FONT_SCALE" translatable="false">SET_FONT_SCALE</string>
<string name="SET_FONT_SCALE_INT" translatable="false">SET_FONT_SCALE_INT</string>
<string name="SET_NOTIF_FOLLOW_FILTER" translatable="false">SET_NOTIF_FOLLOW_FILTER</string> <string name="SET_NOTIF_FOLLOW_FILTER" translatable="false">SET_NOTIF_FOLLOW_FILTER</string>
<string name="SET_NOTIF_ADD_FILTER" translatable="false">SET_NOTIF_ADD_FILTER</string> <string name="SET_NOTIF_ADD_FILTER" translatable="false">SET_NOTIF_ADD_FILTER</string>
<string name="SET_NOTIF_MENTION_FILTER" translatable="false">SET_NOTIF_MENTION_FILTER</string> <string name="SET_NOTIF_MENTION_FILTER" translatable="false">SET_NOTIF_MENTION_FILTER</string>
@ -1627,6 +1628,13 @@
<string name="msg_share_image">Share Image</string> <string name="msg_share_image">Share Image</string>
<string name="tap_here_to_refresh_poll">Tap here to refresh poll</string> <string name="tap_here_to_refresh_poll">Tap here to refresh poll</string>
<string name="action_announcement_from_to">Announcement · %1$s - %2$s</string> <string name="action_announcement_from_to">Announcement · %1$s - %2$s</string>
<string name="delete_cache">Delete cache</string>
<string name="messages_in_cache_for_home">Messages in cache for Home</string>
<string name="messages_in_cache_for_other_timelines">Messages in cache for other timelines</string>
<string name="messages_stored_in_drafts">Messages stored in drafts</string>
<string name="built_in_browser_cache">Built-in browser cache</string>
<string name="files_cache">Fiiles cache</string>
<string name="files_cache_size">File cache size</string>
<string-array name="photo_editor_emoji" translatable="false"> <string-array name="photo_editor_emoji" translatable="false">
<!-- Smiles --> <!-- Smiles -->

@ -34,6 +34,14 @@
app:summary="@string/set_enable_crash_report_indication" app:summary="@string/set_enable_crash_report_indication"
app:title="@string/set_enable_crash_report" /> app:title="@string/set_enable_crash_report" />
<androidx.preference.SeekBarPreference
android:defaultValue="110"
android:max="180"
app:iconSpaceReserved="false"
app:key="@string/SET_FONT_SCALE_INT"
app:showSeekBarValue="true"
app:title="@string/text_size" />
<androidx.preference.SeekBarPreference <androidx.preference.SeekBarPreference
android:defaultValue="100" android:defaultValue="100"
android:max="1000" android:max="1000"

Loading…
Cancel
Save