Reduce visibility of members and methods where possible, and more (see description)

* reduce visibility
* remove unused methods and members
* Suppress unused warnings we can ignore
* fixed or ignored deprecation warnings
* Changed HistoryItem to have better hashcode and equals implementations
and removed id member from it as it was unnecessary
* Fix performance problem with loading bookmarksettingsfragment and
properly annotate bookmarklocalsync
This commit is contained in:
Anthony Restaino 2015-09-27 22:19:59 -04:00
parent 3bd08d00f3
commit c67a1108cd
27 changed files with 210 additions and 288 deletions

View File

@ -374,6 +374,7 @@ public abstract class BrowserActivity extends ThemableBrowserActivity implements
mDrawerLayout.setDrawerShadow(R.drawable.drawer_left_shadow, GravityCompat.START); mDrawerLayout.setDrawerShadow(R.drawable.drawer_left_shadow, GravityCompat.START);
if (API <= Build.VERSION_CODES.JELLY_BEAN_MR2) { if (API <= Build.VERSION_CODES.JELLY_BEAN_MR2) {
//noinspection deprecation
WebIconDatabase.getInstance().open(getDir("icons", MODE_PRIVATE).getPath()); WebIconDatabase.getInstance().open(getDir("icons", MODE_PRIVATE).getPath());
} }
@ -1294,7 +1295,7 @@ public abstract class BrowserActivity extends ThemableBrowserActivity implements
} }
} }
public class LightningViewAdapter extends RecyclerView.Adapter<LightningViewAdapter.LightningViewHolder> { private class LightningViewAdapter extends RecyclerView.Adapter<LightningViewAdapter.LightningViewHolder> {
private final Context context; private final Context context;
private final int layoutResourceId; private final int layoutResourceId;
@ -1359,6 +1360,7 @@ public abstract class BrowserActivity extends ThemableBrowserActivity implements
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.txtTitle.setTextAppearance(R.style.boldText); holder.txtTitle.setTextAppearance(R.style.boldText);
} else { } else {
//noinspection deprecation
holder.txtTitle.setTextAppearance(context, R.style.boldText); holder.txtTitle.setTextAppearance(context, R.style.boldText);
} }
Drawable foregroundDrawable; Drawable foregroundDrawable;
@ -1373,6 +1375,7 @@ public abstract class BrowserActivity extends ThemableBrowserActivity implements
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
holder.layout.setBackground(foregroundDrawable); holder.layout.setBackground(foregroundDrawable);
} else { } else {
//noinspection deprecation
holder.layout.setBackgroundDrawable(foregroundDrawable); holder.layout.setBackgroundDrawable(foregroundDrawable);
} }
if (!isIncognito() && mColorMode) { if (!isIncognito() && mColorMode) {
@ -1383,11 +1386,13 @@ public abstract class BrowserActivity extends ThemableBrowserActivity implements
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.txtTitle.setTextAppearance(R.style.normalText); holder.txtTitle.setTextAppearance(R.style.normalText);
} else { } else {
//noinspection deprecation
holder.txtTitle.setTextAppearance(context, R.style.normalText); holder.txtTitle.setTextAppearance(context, R.style.normalText);
} }
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
holder.layout.setBackground(mBackgroundTabDrawable); holder.layout.setBackground(mBackgroundTabDrawable);
} else { } else {
//noinspection deprecation
holder.layout.setBackgroundDrawable(mBackgroundTabDrawable); holder.layout.setBackgroundDrawable(mBackgroundTabDrawable);
} }
@ -1455,12 +1460,7 @@ public abstract class BrowserActivity extends ThemableBrowserActivity implements
* @param tabBackground the optional LinearLayout to color * @param tabBackground the optional LinearLayout to color
*/ */
private void changeToolbarBackground(@NonNull Bitmap favicon, @Nullable final Drawable tabBackground) { private void changeToolbarBackground(@NonNull Bitmap favicon, @Nullable final Drawable tabBackground) {
final int defaultColor; final int defaultColor = ContextCompat.getColor(this, R.color.primary_color);
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
defaultColor = getResources().getColor(R.color.primary_color);
} else {
defaultColor = getColor(R.color.primary_color);
}
if (mCurrentUiColor == Color.BLACK) { if (mCurrentUiColor == Color.BLACK) {
mCurrentUiColor = defaultColor; mCurrentUiColor = defaultColor;
} }

View File

@ -26,7 +26,7 @@ public class BrowserApp extends Application {
return appComponent; return appComponent;
} }
public void buildDepencyGraph() { private void buildDepencyGraph() {
appComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).build(); appComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).build();
} }

View File

@ -3,8 +3,6 @@
*/ */
package acr.browser.lightning.constant; package acr.browser.lightning.constant;
import android.os.Environment;
import acr.browser.lightning.BuildConfig; import acr.browser.lightning.BuildConfig;
public final class Constants { public final class Constants {
@ -27,8 +25,6 @@ public final class Constants {
public static final String HOMEPAGE = "about:home"; public static final String HOMEPAGE = "about:home";
public static final String BAIDU_SEARCH = "https://www.baidu.com/s?wd="; public static final String BAIDU_SEARCH = "https://www.baidu.com/s?wd=";
public static final String YANDEX_SEARCH = "https://yandex.ru/yandsearch?lr=21411&text="; public static final String YANDEX_SEARCH = "https://yandex.ru/yandsearch?lr=21411&text=";
public static final String EXTERNAL_STORAGE = Environment.getExternalStorageDirectory()
.toString();
public static final String JAVASCRIPT_INVERT_PAGE = "javascript:(function(){var e='img {-webkit-filter: invert(100%);'+'-moz-filter: invert(100%);'+'-o-filter: invert(100%);'+'-ms-filter: invert(100%); }',t=document.getElementsByTagName('head')[0],n=document.createElement('style');if(!window.counter){window.counter=1}else{window.counter++;if(window.counter%2==0){var e='html {-webkit-filter: invert(0%); -moz-filter: invert(0%); -o-filter: invert(0%); -ms-filter: invert(0%); }'}}n.type='text/css';if(n.styleSheet){n.styleSheet.cssText=e}else{n.appendChild(document.createTextNode(e))}t.appendChild(n)})();"; public static final String JAVASCRIPT_INVERT_PAGE = "javascript:(function(){var e='img {-webkit-filter: invert(100%);'+'-moz-filter: invert(100%);'+'-o-filter: invert(100%);'+'-ms-filter: invert(100%); }',t=document.getElementsByTagName('head')[0],n=document.createElement('style');if(!window.counter){window.counter=1}else{window.counter++;if(window.counter%2==0){var e='html {-webkit-filter: invert(0%); -moz-filter: invert(0%); -o-filter: invert(0%); -ms-filter: invert(0%); }'}}n.type='text/css';if(n.styleSheet){n.styleSheet.cssText=e}else{n.appendChild(document.createTextNode(e))}t.appendChild(n)})();";
public static final String JAVASCRIPT_TEXT_REFLOW = "javascript:document.getElementsByTagName('body')[0].style.width=window.innerWidth+'px';"; public static final String JAVASCRIPT_TEXT_REFLOW = "javascript:document.getElementsByTagName('body')[0].style.width=window.innerWidth+'px';";

View File

@ -3,7 +3,6 @@
*/ */
package acr.browser.lightning.controller; package acr.browser.lightning.controller;
import android.app.Activity;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.net.Uri; import android.net.Uri;
import android.os.Message; import android.os.Message;

View File

@ -100,12 +100,14 @@ public class BookmarkLocalSync {
return list; return list;
} }
@WorkerThread
public boolean isStockSupported() { public boolean isStockSupported() {
Cursor cursor = getStockCursor(); Cursor cursor = getStockCursor();
Utils.close(cursor); Utils.close(cursor);
return cursor != null; return cursor != null;
} }
@WorkerThread
public boolean isChromeSupported() { public boolean isChromeSupported() {
Cursor cursor = getChromeCursor(); Cursor cursor = getChromeCursor();
Utils.close(cursor); Utils.close(cursor);
@ -113,6 +115,7 @@ public class BookmarkLocalSync {
} }
@Nullable @Nullable
@WorkerThread
private Cursor getChromeCursor() { private Cursor getChromeCursor() {
Cursor cursor; Cursor cursor;
Uri uri = Uri.parse(CHROME_BOOKMARKS_CONTENT); Uri uri = Uri.parse(CHROME_BOOKMARKS_CONTENT);
@ -126,6 +129,7 @@ public class BookmarkLocalSync {
} }
@Nullable @Nullable
@WorkerThread
private Cursor getStockCursor() { private Cursor getStockCursor() {
Cursor cursor; Cursor cursor;
Uri uri = Uri.parse(STOCK_BOOKMARKS_CONTENT); Uri uri = Uri.parse(STOCK_BOOKMARKS_CONTENT);

View File

@ -433,7 +433,7 @@ public class BookmarkManager {
* *
* @return a list of all folders * @return a list of all folders
*/ */
public synchronized List<HistoryItem> getFolders(boolean sort) { private synchronized List<HistoryItem> getFolders(boolean sort) {
final HashMap<String, HistoryItem> folders = new HashMap<>(); final HashMap<String, HistoryItem> folders = new HashMap<>();
for (HistoryItem item : mBookmarksMap.values()) { for (HistoryItem item : mBookmarksMap.values()) {
final String folderName = item.getFolder(); final String folderName = item.getFolder();

View File

@ -22,7 +22,7 @@ public class HistoryDatabase extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 2; private static final int DATABASE_VERSION = 2;
// Database Name // Database Name
public static final String DATABASE_NAME = "historyManager"; private static final String DATABASE_NAME = "historyManager";
// HistoryItems table name // HistoryItems table name
private static final String TABLE_HISTORY = "history"; private static final String TABLE_HISTORY = "history";
@ -160,7 +160,6 @@ public class HistoryDatabase extends SQLiteOpenHelper {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
do { do {
HistoryItem item = new HistoryItem(); HistoryItem item = new HistoryItem();
item.setID(Integer.parseInt(cursor.getString(0)));
item.setUrl(cursor.getString(1)); item.setUrl(cursor.getString(1));
item.setTitle(cursor.getString(2)); item.setTitle(cursor.getString(2));
item.setImageId(R.drawable.ic_history); item.setImageId(R.drawable.ic_history);
@ -185,7 +184,6 @@ public class HistoryDatabase extends SQLiteOpenHelper {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
do { do {
HistoryItem item = new HistoryItem(); HistoryItem item = new HistoryItem();
item.setID(Integer.parseInt(cursor.getString(0)));
item.setUrl(cursor.getString(1)); item.setUrl(cursor.getString(1));
item.setTitle(cursor.getString(2)); item.setTitle(cursor.getString(2));
item.setImageId(R.drawable.ic_history); item.setImageId(R.drawable.ic_history);
@ -210,7 +208,6 @@ public class HistoryDatabase extends SQLiteOpenHelper {
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
do { do {
HistoryItem item = new HistoryItem(); HistoryItem item = new HistoryItem();
item.setID(Integer.parseInt(cursor.getString(0)));
item.setUrl(cursor.getString(1)); item.setUrl(cursor.getString(1));
item.setTitle(cursor.getString(2)); item.setTitle(cursor.getString(2));
item.setImageId(R.drawable.ic_history); item.setImageId(R.drawable.ic_history);
@ -222,19 +219,6 @@ public class HistoryDatabase extends SQLiteOpenHelper {
return itemList; return itemList;
} }
public synchronized int updateHistoryItem(HistoryItem item) {
mLock = true;
openIfNecessary();
ContentValues values = new ContentValues();
values.put(KEY_URL, item.getUrl());
values.put(KEY_TITLE, item.getTitle());
values.put(KEY_TIME_VISITED, System.currentTimeMillis());
int update = mDatabase.update(TABLE_HISTORY, values, KEY_ID + " = ?",
new String[]{String.valueOf(item.getId())});
mLock = false;
return update;
}
public int getHistoryItemsCount() { public int getHistoryItemsCount() {
mLock = true; mLock = true;
openIfNecessary(); openIfNecessary();

View File

@ -5,23 +5,29 @@ package acr.browser.lightning.database;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
public class HistoryItem implements Comparable<HistoryItem> { public class HistoryItem implements Comparable<HistoryItem> {
// private variables // private variables
private int mId = 0; @NonNull
private String mUrl = ""; private String mUrl = "";
@NonNull
private String mTitle = ""; private String mTitle = "";
@NonNull
private String mFolder = ""; private String mFolder = "";
@Nullable
private Bitmap mBitmap = null; private Bitmap mBitmap = null;
private int mImageId = 0; private int mImageId = 0;
private int mOrder = 0; private int mOrder = 0;
private boolean mIsFolder = false; private boolean mIsFolder = false;
// Empty constructor // Empty constructor
public HistoryItem() { public HistoryItem() {}
}
public HistoryItem(HistoryItem item) { public HistoryItem(HistoryItem item) {
this.mUrl = item.mUrl; this.mUrl = item.mUrl;
@ -32,42 +38,24 @@ public class HistoryItem implements Comparable<HistoryItem> {
} }
// constructor // constructor
public HistoryItem(int id, String url, String title) { public HistoryItem(@NonNull String url, @NonNull String title) {
this.mId = id;
this.mUrl = url; this.mUrl = url;
this.mTitle = title; this.mTitle = title;
this.mBitmap = null; this.mBitmap = null;
} }
// constructor // constructor
public HistoryItem(String url, String title) { public HistoryItem(@NonNull String url, @NonNull String title, int imageId) {
this.mUrl = url;
this.mTitle = title;
this.mBitmap = null;
}
// constructor
public HistoryItem(String url, String title, int imageId) {
this.mUrl = url; this.mUrl = url;
this.mTitle = title; this.mTitle = title;
this.mBitmap = null; this.mBitmap = null;
this.mImageId = imageId; this.mImageId = imageId;
} }
// getting ID
public int getId() {
return this.mId;
}
public int getImageId() { public int getImageId() {
return this.mImageId; return this.mImageId;
} }
// setting id
public void setID(int id) {
this.mId = id;
}
public void setImageId(int id) { public void setImageId(int id) {
this.mImageId = id; this.mImageId = id;
} }
@ -131,40 +119,34 @@ public class HistoryItem implements Comparable<HistoryItem> {
@Override @Override
public int compareTo(@NonNull HistoryItem another) { public int compareTo(@NonNull HistoryItem another) {
return mTitle.compareTo(another.mTitle); int compare = this.mTitle.compareTo(another.mTitle);
if (compare == 0) {
return this.mUrl.compareTo(another.mUrl);
}
return compare;
} }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object object) {
if (this == o) { if (this == object) return true;
return true; if (object == null) return false;
} if (!(object instanceof HistoryItem)) return false;
if (o == null || ((Object) this).getClass() != o.getClass()) {
return false;
}
HistoryItem that = (HistoryItem) o; HistoryItem that = (HistoryItem) object;
if (mId != that.mId) { return mImageId == that.mImageId &&
return false; this.mTitle.equals(that.mTitle) && this.mUrl.equals(that.mUrl) &&
} this.mFolder.equals(that.mFolder);
if (mImageId != that.mImageId) {
return false;
}
if (mBitmap != null ? !mBitmap.equals(that.mBitmap) : that.mBitmap != null) {
return false;
}
return mTitle.equals(that.mTitle) && mUrl.equals(that.mUrl);
} }
@Override @Override
public int hashCode() { public int hashCode() {
int result = mId; int result = mUrl.hashCode();
result = 31 * result + mUrl.hashCode(); result = 31 * result + mImageId;
result = 31 * result + mTitle.hashCode(); result = 31 * result + mTitle.hashCode();
result = 31 * result + (mBitmap != null ? mBitmap.hashCode() : 0); result = 32 * result + mFolder.hashCode();
result = 31 * result + mImageId; result = 31 * result + mImageId;
return result; return result;

View File

@ -101,7 +101,7 @@ public class BookmarksDialogBuilder {
.show(); .show();
} }
public void showEditBookmarkDialog(final Context context, final HistoryItem item) { private void showEditBookmarkDialog(final Context context, final HistoryItem item) {
final AlertDialog.Builder editBookmarkDialog = new AlertDialog.Builder(context); final AlertDialog.Builder editBookmarkDialog = new AlertDialog.Builder(context);
editBookmarkDialog.setTitle(R.string.title_edit_bookmark); editBookmarkDialog.setTitle(R.string.title_edit_bookmark);
final View dialogLayout = View.inflate(context, R.layout.dialog_edit_bookmark, null); final View dialogLayout = View.inflate(context, R.layout.dialog_edit_bookmark, null);
@ -165,7 +165,7 @@ public class BookmarksDialogBuilder {
.show(); .show();
} }
public void showRenameFolderDialog(final Context context, final HistoryItem item) { private void showRenameFolderDialog(final Context context, final HistoryItem item) {
// assert item.isFolder(); // assert item.isFolder();
final AlertDialog.Builder editFolderDialog = new AlertDialog.Builder(context); final AlertDialog.Builder editFolderDialog = new AlertDialog.Builder(context);
editFolderDialog.setTitle(R.string.title_rename_folder); editFolderDialog.setTitle(R.string.title_rename_folder);

View File

@ -25,7 +25,7 @@ import acr.browser.lightning.utils.Utils;
* just clicks on the link, we will do the same steps of correcting the mimetype * just clicks on the link, we will do the same steps of correcting the mimetype
* down in android.os.webkit.LoadListener rather than handling it here. * down in android.os.webkit.LoadListener rather than handling it here.
*/ */
public class FetchUrlMimeType extends Thread { class FetchUrlMimeType extends Thread {
private final Activity mActivity; private final Activity mActivity;

View File

@ -22,19 +22,19 @@ import static android.util.Patterns.GOOD_IRI_CHAR;
* <p/> * <p/>
* If given an https scheme but no port, fills in port * If given an https scheme but no port, fills in port
*/ */
public class WebAddress { class WebAddress {
private String mScheme; private String mScheme;
private String mHost; private String mHost;
private int mPort; private int mPort;
private String mPath; private String mPath;
private String mAuthInfo; private String mAuthInfo;
static final int MATCH_GROUP_SCHEME = 1; private static final int MATCH_GROUP_SCHEME = 1;
static final int MATCH_GROUP_AUTHORITY = 2; private static final int MATCH_GROUP_AUTHORITY = 2;
static final int MATCH_GROUP_HOST = 3; private static final int MATCH_GROUP_HOST = 3;
static final int MATCH_GROUP_PORT = 4; private static final int MATCH_GROUP_PORT = 4;
static final int MATCH_GROUP_PATH = 5; private static final int MATCH_GROUP_PATH = 5;
static final Pattern sAddressPattern = Pattern.compile( private static final Pattern sAddressPattern = Pattern.compile(
/* scheme */"(?:(http|https|file)\\:\\/\\/)?" + /* scheme */"(?:(http|https|file)\\:\\/\\/)?" +
/* authority */"(?:([-A-Za-z0-9$_.+!*'(),;?&=]+(?:\\:[-A-Za-z0-9$_.+!*'(),;?&=]+)?)@)?" + /* authority */"(?:([-A-Za-z0-9$_.+!*'(),;?&=]+(?:\\:[-A-Za-z0-9$_.+!*'(),;?&=]+)?)@)?" +
/* host */"([" + GOOD_IRI_CHAR + "%_-][" + GOOD_IRI_CHAR + "%_\\.-]*|\\[[0-9a-fA-F:\\.]+\\])?" + /* host */"([" + GOOD_IRI_CHAR + "%_-][" + GOOD_IRI_CHAR + "%_\\.-]*|\\[[0-9a-fA-F:\\.]+\\])?" +

View File

@ -102,17 +102,24 @@ public class BookmarkSettingsFragment extends PreferenceFragment implements Pref
Preference exportpref = findPreference(SETTINGS_EXPORT); Preference exportpref = findPreference(SETTINGS_EXPORT);
Preference importpref = findPreference(SETTINGS_IMPORT); Preference importpref = findPreference(SETTINGS_IMPORT);
Preference importStock = findPreference(SETTINGS_IMPORT_BROWSER);
mSync = new BookmarkLocalSync(mActivity); mSync = new BookmarkLocalSync(mActivity);
importStock.setEnabled(mSync.isStockSupported() || mSync.isChromeSupported());
exportpref.setOnPreferenceClickListener(this); exportpref.setOnPreferenceClickListener(this);
importpref.setOnPreferenceClickListener(this); importpref.setOnPreferenceClickListener(this);
importStock.setOnPreferenceClickListener(this);
new Thread(mInitializeImportPreference).start();
} }
private final Runnable mInitializeImportPreference = new Runnable() {
@Override
public void run() {
Preference importStock = findPreference(SETTINGS_IMPORT_BROWSER);
importStock.setEnabled(mSync.isStockSupported() || mSync.isChromeSupported());
importStock.setOnPreferenceClickListener(BookmarkSettingsFragment.this);
}
};
@Override @Override
public boolean onPreferenceClick(Preference preference) { public boolean onPreferenceClick(Preference preference) {
switch (preference.getKey()) { switch (preference.getKey()) {

View File

@ -139,22 +139,7 @@ public class DisplaySettingsFragment extends PreferenceFragment implements Prefe
sample.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT)); sample.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT));
sample.setGravity(Gravity.CENTER_HORIZONTAL); sample.setGravity(Gravity.CENTER_HORIZONTAL);
view.addView(sample); view.addView(sample);
bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { bar.setOnSeekBarChangeListener(new TextSeekBarListener(sample));
@Override
public void onProgressChanged(SeekBar view, int size, boolean user) {
sample.setTextSize(getTextSize(size));
}
@Override
public void onStartTrackingTouch(SeekBar arg0) {
}
@Override
public void onStopTrackingTouch(SeekBar arg0) {
}
});
final int MAX = 5; final int MAX = 5;
bar.setMax(MAX); bar.setMax(MAX);
bar.setProgress(MAX - mPreferences.getTextSize()); bar.setProgress(MAX - mPreferences.getTextSize());
@ -225,4 +210,25 @@ public class DisplaySettingsFragment extends PreferenceFragment implements Prefe
}); });
picker.show(); picker.show();
} }
private static class TextSeekBarListener implements SeekBar.OnSeekBarChangeListener {
private final TextView sample;
public TextSeekBarListener(TextView sample) {this.sample = sample;}
@Override
public void onProgressChanged(SeekBar view, int size, boolean user) {
this.sample.setTextSize(getTextSize(size));
}
@Override
public void onStartTrackingTouch(SeekBar arg0) {
}
@Override
public void onStopTrackingTouch(SeekBar arg0) {
}
}
} }

View File

@ -15,7 +15,6 @@ import android.support.v7.app.AlertDialog;
import android.text.Editable; import android.text.Editable;
import android.text.InputFilter; import android.text.InputFilter;
import android.text.TextWatcher; import android.text.TextWatcher;
import android.util.Log;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.EditText; import android.widget.EditText;
@ -219,12 +218,7 @@ public class GeneralSettingsFragment extends PreferenceFragment implements Prefe
setProxyChoice(which); setProxyChoice(which);
} }
}); });
picker.setNeutralButton(getResources().getString(R.string.action_ok), picker.setNeutralButton(getResources().getString(R.string.action_ok), null);
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
picker.show(); picker.show();
} }
@ -302,12 +296,7 @@ public class GeneralSettingsFragment extends PreferenceFragment implements Prefe
setSearchEngineSummary(which); setSearchEngineSummary(which);
} }
}); });
picker.setNeutralButton(getResources().getString(R.string.action_ok), picker.setNeutralButton(getResources().getString(R.string.action_ok), null);
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
picker.show(); picker.show();
} }
@ -349,12 +338,7 @@ public class GeneralSettingsFragment extends PreferenceFragment implements Prefe
} }
} }
}); });
picker.setNeutralButton(getResources().getString(R.string.action_ok), picker.setNeutralButton(getResources().getString(R.string.action_ok), null);
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
picker.show(); picker.show();
} }
@ -407,12 +391,7 @@ public class GeneralSettingsFragment extends PreferenceFragment implements Prefe
} }
} }
}); });
picker.setNeutralButton(getResources().getString(R.string.action_ok), picker.setNeutralButton(getResources().getString(R.string.action_ok), null);
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
picker.show(); picker.show();
} }
@ -442,18 +421,7 @@ public class GeneralSettingsFragment extends PreferenceFragment implements Prefe
} }
} }
}); });
agentPicker.setNeutralButton(getResources().getString(R.string.action_ok), agentPicker.setNeutralButton(getResources().getString(R.string.action_ok), null);
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
agentPicker.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
Log.i("Cancelled", "");
}
});
agentPicker.show(); agentPicker.show();
} }
@ -485,24 +453,7 @@ public class GeneralSettingsFragment extends PreferenceFragment implements Prefe
final int errorColor = ContextCompat.getColor(getActivity(), R.color.error_red); final int errorColor = ContextCompat.getColor(getActivity(), R.color.error_red);
final int regularColor = ThemeUtils.getTextColor(getActivity()); final int regularColor = ThemeUtils.getTextColor(getActivity());
getDownload.setTextColor(regularColor); getDownload.setTextColor(regularColor);
getDownload.addTextChangedListener(new TextWatcher() { getDownload.addTextChangedListener(new DownloadLocationTextWatcher(getDownload, errorColor, regularColor));
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
if (!DownloadHandler.isWriteAccessAvailable(s.toString())) {
getDownload.setTextColor(errorColor);
} else {
getDownload.setTextColor(regularColor);
}
}
});
getDownload.setText(mPreferences.getDownloadDirectory()); getDownload.setText(mPreferences.getDownloadDirectory());
layout.addView(getDownload); layout.addView(getDownload);
@ -624,4 +575,31 @@ public class GeneralSettingsFragment extends PreferenceFragment implements Prefe
return false; return false;
} }
} }
private static class DownloadLocationTextWatcher implements TextWatcher {
private final EditText getDownload;
private final int errorColor;
private final int regularColor;
public DownloadLocationTextWatcher(EditText getDownload, int errorColor, int regularColor) {
this.getDownload = getDownload;
this.errorColor = errorColor;
this.regularColor = regularColor;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {}
@Override
public void afterTextChanged(Editable s) {
if (!DownloadHandler.isWriteAccessAvailable(s.toString())) {
this.getDownload.setTextColor(this.errorColor);
} else {
this.getDownload.setTextColor(this.regularColor);
}
}
}
} }

View File

@ -153,12 +153,7 @@ public class PrivacySettingsFragment extends PreferenceFragment implements Prefe
clear.start(); clear.start();
} }
}) })
.setNegativeButton(getResources().getString(R.string.action_no), .setNegativeButton(getResources().getString(R.string.action_no), null).show();
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
}).show();
} }
private void clearCookiesDialog() { private void clearCookiesDialog() {
@ -178,12 +173,7 @@ public class PrivacySettingsFragment extends PreferenceFragment implements Prefe
clear.start(); clear.start();
} }
}) })
.setNegativeButton(getResources().getString(R.string.action_no), .setNegativeButton(getResources().getString(R.string.action_no), null).show();
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface arg0, int arg1) {
}
}).show();
} }
private void clearCache() { private void clearCache() {

View File

@ -385,16 +385,16 @@ public class ArticleTextExtractor {
// System.out.println("date modified element " + elem.toString()); // System.out.println("date modified element " + elem.toString());
} }
if (dateStr != null && dateStr.isEmpty()) { if (dateStr.isEmpty()) {
dateStr = SHelper.innerTrim(doc.select("meta[name=utime]").attr("content")); dateStr = SHelper.innerTrim(doc.select("meta[name=utime]").attr("content"));
} }
if (dateStr != null && dateStr.isEmpty()) { if (dateStr.isEmpty()) {
dateStr = SHelper.innerTrim(doc.select("meta[name=pdate]").attr("content")); dateStr = SHelper.innerTrim(doc.select("meta[name=pdate]").attr("content"));
} }
if (dateStr != null && dateStr.isEmpty()) { if (dateStr.isEmpty()) {
dateStr = SHelper.innerTrim(doc.select("meta[property=article:published]").attr("content")); dateStr = SHelper.innerTrim(doc.select("meta[property=article:published]").attr("content"));
} }
if (dateStr != null && dateStr.isEmpty()) { if (dateStr.isEmpty()) {
return parseDate(dateStr); return parseDate(dateStr);
} }
@ -492,9 +492,7 @@ public class ArticleTextExtractor {
if (el.hasAttr("content")) { if (el.hasAttr("content")) {
dateStr = el.attr("content"); dateStr = el.attr("content");
Date parsedDate = parseDate(dateStr); Date parsedDate = parseDate(dateStr);
if (parsedDate != null) { return parsedDate;
return parsedDate;
}
} }
} }
@ -686,14 +684,12 @@ public class ArticleTextExtractor {
private static Collection<String> extractKeywords(Document doc) { private static Collection<String> extractKeywords(Document doc) {
String content = SHelper.innerTrim(doc.select("head meta[name=keywords]").attr("content")); String content = SHelper.innerTrim(doc.select("head meta[name=keywords]").attr("content"));
if (content != null) { if (content.startsWith("[") && content.endsWith("]"))
if (content.startsWith("[") && content.endsWith("]")) content = content.substring(1, content.length() - 1);
content = content.substring(1, content.length() - 1);
String[] split = content.split("\\s*,\\s*"); String[] split = content.split("\\s*,\\s*");
if (split.length > 1 || (split.length > 0 && split[0] != null && !split[0].isEmpty())) if (split.length > 1 || (split.length > 0 && split[0] != null && !split[0].isEmpty()))
return Arrays.asList(split); return Arrays.asList(split);
}
return Collections.emptyList(); return Collections.emptyList();
} }
@ -1190,7 +1186,7 @@ public class ArticleTextExtractor {
charlen = 4; charlen = 4;
} else if (c <= 0xdfff) { } else if (c <= 0xdfff) {
charlen = 0; charlen = 0;
} else if (c <= 0xffff) { } else {
charlen = 3; charlen = 3;
} }
if (resultlen + charlen > length) { if (resultlen + charlen > length) {

View File

@ -35,9 +35,9 @@ import acr.browser.lightning.constant.Constants;
*/ */
public class Converter { public class Converter {
public final static String UTF8 = "UTF-8"; private final static String UTF8 = "UTF-8";
public final static String ISO = "ISO-8859-1"; private final static String ISO = "ISO-8859-1";
public final static int K2 = 2048; private final static int K2 = 2048;
private int maxBytes = 1000000 / 2; private int maxBytes = 1000000 / 2;
private String encoding; private String encoding;
private String url; private String url;
@ -99,7 +99,7 @@ public class Converter {
* The max bytes that we want to read from the input stream * The max bytes that we want to read from the input stream
* @return String * @return String
*/ */
public String streamToString(InputStream is, int maxBytes, String enc) { private String streamToString(InputStream is, int maxBytes, String enc) {
encoding = enc; encoding = enc;
// Http 1.1. standard is iso-8859-1 not utf8 :( // Http 1.1. standard is iso-8859-1 not utf8 :(
// but we force utf-8 as youtube assumes it ;) // but we force utf-8 as youtube assumes it ;)
@ -181,8 +181,8 @@ public class Converter {
* *
* @throws IOException * @throws IOException
*/ */
protected static String detectCharset(String key, ByteArrayOutputStream bos, BufferedInputStream in, private static String detectCharset(String key, ByteArrayOutputStream bos, BufferedInputStream in,
String enc) throws IOException { String enc) throws IOException {
// Grab better encoding from stream // Grab better encoding from stream
byte[] arr = new byte[K2]; byte[] arr = new byte[K2];

View File

@ -207,8 +207,8 @@ public class HtmlFetcher {
// main workhorse to call externally // main workhorse to call externally
@SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter") @SuppressWarnings("SynchronizationOnLocalVariableOrMethodParameter")
public JResult fetchAndExtract(String url, int timeout, boolean resolve, private JResult fetchAndExtract(String url, int timeout, boolean resolve,
int maxContentSize, boolean forceReload) throws Exception { int maxContentSize, boolean forceReload) throws Exception {
String originalUrl = url; String originalUrl = url;
url = SHelper.removeHashbang(url); url = SHelper.removeHashbang(url);
String gUrl = SHelper.getUrlFromUglyGoogleRedirect(url); String gUrl = SHelper.getUrlFromUglyGoogleRedirect(url);
@ -301,7 +301,7 @@ public class HtmlFetcher {
} }
// Ugly hack to break free from any cached versions, a few URLs required this. // Ugly hack to break free from any cached versions, a few URLs required this.
public static String getURLtoBreakCache(String url) { private static String getURLtoBreakCache(String url) {
try { try {
URL aURL = new URL(url); URL aURL = new URL(url);
if (aURL.getQuery() != null && aURL.getQuery().isEmpty()) { if (aURL.getQuery() != null && aURL.getQuery().isEmpty()) {
@ -314,7 +314,7 @@ public class HtmlFetcher {
} }
} }
public String lessText(String text) { private String lessText(String text) {
if (text == null) if (text == null)
return ""; return "";
@ -328,13 +328,13 @@ public class HtmlFetcher {
return SHelper.useDomainOfFirstArg4Second(url, urlOrPath); return SHelper.useDomainOfFirstArg4Second(url, urlOrPath);
} }
public String fetchAsString(String urlAsString, int timeout) private String fetchAsString(String urlAsString, int timeout)
throws IOException { throws IOException {
return fetchAsString(urlAsString, timeout, true); return fetchAsString(urlAsString, timeout, true);
} }
// main routine to get raw webpage content // main routine to get raw webpage content
public String fetchAsString(String urlAsString, int timeout, boolean includeSomeGooseOptions) private String fetchAsString(String urlAsString, int timeout, boolean includeSomeGooseOptions)
throws IOException { throws IOException {
HttpURLConnection hConn = createUrlConnection(urlAsString, timeout, includeSomeGooseOptions); HttpURLConnection hConn = createUrlConnection(urlAsString, timeout, includeSomeGooseOptions);
hConn.setInstanceFollowRedirects(true); hConn.setInstanceFollowRedirects(true);
@ -352,7 +352,7 @@ public class HtmlFetcher {
return createConverter(urlAsString).streamToString(is, enc); return createConverter(urlAsString).streamToString(is, enc);
} }
public static Converter createConverter(String url) { private static Converter createConverter(String url) {
return new Converter(url); return new Converter(url);
} }
@ -364,8 +364,8 @@ public class HtmlFetcher {
* @return the resolved url if any. Or null if it couldn't resolve the url * @return the resolved url if any. Or null if it couldn't resolve the url
* (within the specified time) or the same url if response code is OK * (within the specified time) or the same url if response code is OK
*/ */
public String getResolvedUrl(String urlAsString, int timeout, private String getResolvedUrl(String urlAsString, int timeout,
int num_redirects) { int num_redirects) {
String newUrl = null; String newUrl = null;
int responseCode = -1; int responseCode = -1;
try { try {
@ -416,7 +416,7 @@ public class HtmlFetcher {
* to non-ASCII characters. Workaround for broken origin servers that send * to non-ASCII characters. Workaround for broken origin servers that send
* UTF-8 in the Location: header. * UTF-8 in the Location: header.
*/ */
static String encodeUriFromHeader(String badLocation) { private static String encodeUriFromHeader(String badLocation) {
StringBuilder sb = new StringBuilder(badLocation.length()); StringBuilder sb = new StringBuilder(badLocation.length());
for (char ch : badLocation.toCharArray()) { for (char ch : badLocation.toCharArray()) {
@ -431,8 +431,8 @@ public class HtmlFetcher {
return sb.toString(); return sb.toString();
} }
protected HttpURLConnection createUrlConnection(String urlAsStr, int timeout, private HttpURLConnection createUrlConnection(String urlAsStr, int timeout,
boolean includeSomeGooseOptions) throws IOException { boolean includeSomeGooseOptions) throws IOException {
URL url = new URL(urlAsStr); URL url = new URL(urlAsStr);
//using proxy may increase latency //using proxy may increase latency
HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY); HttpURLConnection hConn = (HttpURLConnection) url.openConnection(Proxy.NO_PROXY);

View File

@ -7,15 +7,15 @@ import org.jsoup.nodes.Element;
* *
* @author Chris Alexander, chris@chris-alexander.co.uk * @author Chris Alexander, chris@chris-alexander.co.uk
*/ */
public class ImageResult { class ImageResult {
public final String src; private final String src;
public final Integer weight; public final Integer weight;
public final String title; private final String title;
public final int height; private final int height;
public final int width; private final int width;
public final String alt; private final String alt;
public final boolean noFollow; private final boolean noFollow;
public Element element; public Element element;
public ImageResult(String src, Integer weight, String title, int height, int width, String alt, public ImageResult(String src, Integer weight, String title, int height, int width, String alt,

View File

@ -41,8 +41,8 @@ public class OutputFormatter {
this(minFirstParagraphText, minParagraphText, NODES_TO_REPLACE); this(minFirstParagraphText, minParagraphText, NODES_TO_REPLACE);
} }
public OutputFormatter(int minFirstParagraphText, int minParagraphText, private OutputFormatter(int minFirstParagraphText, int minParagraphText,
List<String> nodesToReplace) { List<String> nodesToReplace) {
this.minFirstParagraphText = minFirstParagraphText; this.minFirstParagraphText = minFirstParagraphText;
this.minParagraphText = minParagraphText; this.minParagraphText = minParagraphText;
this.nodesToReplace = nodesToReplace; this.nodesToReplace = nodesToReplace;
@ -91,7 +91,7 @@ public class OutputFormatter {
* If there are elements inside our top node that have a negative gravity * If there are elements inside our top node that have a negative gravity
* score remove them * score remove them
*/ */
protected void removeNodesWithNegativeScores(Element topNode) { private void removeNodesWithNegativeScores(Element topNode) {
Elements gravityItems = topNode.select("*[gravityScore]"); Elements gravityItems = topNode.select("*[gravityScore]");
for (Element item : gravityItems) { for (Element item : gravityItems) {
int score = getScore(item); int score = getScore(item);
@ -102,7 +102,7 @@ public class OutputFormatter {
} }
} }
protected int append(Element node, StringBuilder sb, String tagName) { private int append(Element node, StringBuilder sb, String tagName) {
int countOfP = 0; // Number of P elements in the article int countOfP = 0; // Number of P elements in the article
int paragraphWithTextIndex = 0; int paragraphWithTextIndex = 0;
// is select more costly then getElementsByTag? // is select more costly then getElementsByTag?
@ -134,14 +134,14 @@ public class OutputFormatter {
return countOfP; return countOfP;
} }
protected static void setParagraphIndex(Element node, String tagName) { private static void setParagraphIndex(Element node, String tagName) {
int paragraphIndex = 0; int paragraphIndex = 0;
for (Element e : node.select(tagName)) { for (Element e : node.select(tagName)) {
e.attr("paragraphIndex", Integer.toString(paragraphIndex++)); e.attr("paragraphIndex", Integer.toString(paragraphIndex++));
} }
} }
protected int getMinParagraph(int paragraphIndex) { private int getMinParagraph(int paragraphIndex) {
if (paragraphIndex < 1) { if (paragraphIndex < 1) {
return minFirstParagraphText; return minFirstParagraphText;
} else { } else {
@ -149,7 +149,7 @@ public class OutputFormatter {
} }
} }
protected static int getParagraphIndex(Element el) { private static int getParagraphIndex(Element el) {
try { try {
return Integer.parseInt(el.attr("paragraphIndex")); return Integer.parseInt(el.attr("paragraphIndex"));
} catch (NumberFormatException ex) { } catch (NumberFormatException ex) {
@ -157,7 +157,7 @@ public class OutputFormatter {
} }
} }
protected static int getScore(Element el) { private static int getScore(Element el) {
try { try {
return Integer.parseInt(el.attr("gravityScore")); return Integer.parseInt(el.attr("gravityScore"));
} catch (Exception ex) { } catch (Exception ex) {
@ -165,7 +165,7 @@ public class OutputFormatter {
} }
} }
boolean unlikely(Node e) { private boolean unlikely(Node e) {
if (e.attr("class") != null && e.attr("class").toLowerCase().contains("caption")) if (e.attr("class") != null && e.attr("class").toLowerCase().contains("caption"))
return true; return true;
@ -174,7 +174,7 @@ public class OutputFormatter {
return unlikelyPattern.matcher(style).find() || unlikelyPattern.matcher(clazz).find(); return unlikelyPattern.matcher(style).find() || unlikelyPattern.matcher(clazz).find();
} }
void appendTextSkipHidden(Element e, StringBuilder accum, int indent) { private void appendTextSkipHidden(Element e, StringBuilder accum, int indent) {
for (Node child : e.childNodes()) { for (Node child : e.childNodes()) {
if (unlikely(child)) { if (unlikely(child)) {
continue; continue;
@ -195,17 +195,17 @@ public class OutputFormatter {
} }
} }
static boolean lastCharIsWhitespace(StringBuilder accum) { private static boolean lastCharIsWhitespace(StringBuilder accum) {
return accum.length() != 0 && Character.isWhitespace(accum.charAt(accum.length() - 1)); return accum.length() != 0 && Character.isWhitespace(accum.charAt(accum.length() - 1));
} }
protected String node2Text(Element el) { private String node2Text(Element el) {
StringBuilder sb = new StringBuilder(200); StringBuilder sb = new StringBuilder(200);
appendTextSkipHidden(el, sb, 0); appendTextSkipHidden(el, sb, 0);
return sb.toString(); return sb.toString();
} }
public OutputFormatter setUnlikelyPattern(String unlikelyPattern) { private OutputFormatter setUnlikelyPattern(String unlikelyPattern) {
this.unlikelyPattern = Pattern.compile(unlikelyPattern); this.unlikelyPattern = Pattern.compile(unlikelyPattern);
return this; return this;
} }

View File

@ -39,9 +39,9 @@ import javax.net.ssl.X509TrustManager;
/** /**
* @author Peter Karich * @author Peter Karich
*/ */
public class SHelper { class SHelper {
public static final String UTF8 = "UTF-8"; private static final String UTF8 = "UTF-8";
private static final Pattern SPACE = Pattern.compile(" "); private static final Pattern SPACE = Pattern.compile(" ");
public static String replaceSpaces(String url) { public static String replaceSpaces(String url) {
@ -122,7 +122,7 @@ public class SHelper {
return str1.substring(res[0], res[1]); return str1.substring(res[0], res[1]);
} }
public static int[] longestSubstring(String str1, String str2) { private static int[] longestSubstring(String str1, String str2) {
if (str1 == null || str1.isEmpty() || str2 == null || str2.isEmpty()) if (str1 == null || str1.isEmpty() || str2 == null || str2.isEmpty())
return null; return null;
@ -280,7 +280,7 @@ public class SHelper {
} }
} }
public static String urlDecode(String str) { private static String urlDecode(String str) {
try { try {
return URLDecoder.decode(str, UTF8); return URLDecoder.decode(str, UTF8);
} catch (UnsupportedEncodingException ex) { } catch (UnsupportedEncodingException ex) {
@ -300,7 +300,7 @@ public class SHelper {
return printNode(root, 0); return printNode(root, 0);
} }
public static String printNode(Element root, int indentation) { private static String printNode(Element root, int indentation) {
StringBuilder sb = new StringBuilder(indentation); StringBuilder sb = new StringBuilder(indentation);
for (int i = 0; i < indentation; i++) { for (int i = 0; i < indentation; i++) {
sb.append(' '); sb.append(' ');

View File

@ -15,8 +15,6 @@ import java.util.List;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import acr.browser.lightning.controller.BrowserController;
public class IntentUtils { public class IntentUtils {
private final Activity mActivity; private final Activity mActivity;

View File

@ -1,7 +1,6 @@
package acr.browser.lightning.utils; package acr.browser.lightning.utils;
import android.content.Context; import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray; import android.content.res.TypedArray;
import android.graphics.Bitmap; import android.graphics.Bitmap;
import android.graphics.BitmapFactory; import android.graphics.BitmapFactory;
@ -12,11 +11,11 @@ import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter; import android.graphics.PorterDuffColorFilter;
import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable; import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.AttrRes; import android.support.annotation.AttrRes;
import android.support.annotation.DrawableRes; import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.annotation.Nullable; import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.TypedValue; import android.util.TypedValue;
import android.widget.ImageView; import android.widget.ImageView;
@ -46,17 +45,11 @@ public class ThemeUtils {
} }
public static int getIconLightThemeColor(@NonNull Context context) { public static int getIconLightThemeColor(@NonNull Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return ContextCompat.getColor(context, R.color.icon_light_theme);
return context.getResources().getColor(R.color.icon_light_theme, context.getTheme());
}
return context.getResources().getColor(R.color.icon_light_theme);
} }
public static int getIconDarkThemeColor(@NonNull Context context) { public static int getIconDarkThemeColor(@NonNull Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return ContextCompat.getColor(context, R.color.icon_dark_theme);
return context.getResources().getColor(R.color.icon_dark_theme, context.getTheme());
}
return context.getResources().getColor(R.color.icon_dark_theme);
} }
public static void themeImageView(ImageView icon, Context context, boolean dark) { public static void themeImageView(ImageView icon, Context context, boolean dark) {
@ -80,12 +73,7 @@ public class ThemeUtils {
@Nullable @Nullable
public static Drawable getThemedDrawable(@NonNull Context context, @DrawableRes int res, boolean dark) { public static Drawable getThemedDrawable(@NonNull Context context, @DrawableRes int res, boolean dark) {
int color = dark ? getIconDarkThemeColor(context) : getIconLightThemeColor(context); int color = dark ? getIconDarkThemeColor(context) : getIconLightThemeColor(context);
final Drawable drawable; final Drawable drawable = ContextCompat.getDrawable(context, res);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
drawable = context.getResources().getDrawable(res);
} else {
drawable = context.getDrawable(res);
}
if (drawable == null) if (drawable == null)
return null; return null;
drawable.mutate(); drawable.mutate();
@ -95,12 +83,7 @@ public class ThemeUtils {
@Nullable @Nullable
public static Drawable getLightThemedDrawable(@NonNull Context context, @DrawableRes int res) { public static Drawable getLightThemedDrawable(@NonNull Context context, @DrawableRes int res) {
final Drawable drawable; final Drawable drawable = ContextCompat.getDrawable(context, res);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
drawable = context.getResources().getDrawable(res);
} else {
drawable = context.getDrawable(res);
}
if (drawable == null) if (drawable == null)
return null; return null;
drawable.mutate(); drawable.mutate();
@ -109,19 +92,12 @@ public class ThemeUtils {
} }
public static ColorDrawable getSelectedBackground(@NonNull Context context, boolean dark) { public static ColorDrawable getSelectedBackground(@NonNull Context context, boolean dark) {
Resources res = context.getResources(); final int color = (dark) ? ContextCompat.getColor(context, R.color.selected_dark) :
int color; ContextCompat.getColor(context, R.color.selected_light);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
color = (dark) ? res.getColor(R.color.selected_dark, context.getTheme()) :
res.getColor(R.color.selected_light, context.getTheme());
} else {
color = (dark) ? res.getColor(R.color.selected_dark) :
res.getColor(R.color.selected_light);
}
return new ColorDrawable(color); return new ColorDrawable(color);
} }
public static int getTextColor(Context context){ public static int getTextColor(Context context) {
return getColor(context, android.R.attr.editTextColor); return getColor(context, android.R.attr.editTextColor);
} }
} }

View File

@ -18,10 +18,7 @@ import android.graphics.LinearGradient;
import android.graphics.Paint; import android.graphics.Paint;
import android.graphics.Path; import android.graphics.Path;
import android.graphics.Shader; import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Environment; import android.os.Environment;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull; import android.support.annotation.NonNull;
import android.support.annotation.StringRes; import android.support.annotation.StringRes;
import android.support.design.widget.Snackbar; import android.support.design.widget.Snackbar;
@ -151,7 +148,7 @@ public final class Utils {
} }
} }
public static boolean deleteDir(File dir) { private static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) { if (dir != null && dir.isDirectory()) {
String[] children = dir.list(); String[] children = dir.list();
for (String aChildren : children) { for (String aChildren : children) {
@ -262,14 +259,6 @@ public final class Utils {
} }
} }
public static Drawable getDrawable(Context context, @DrawableRes int res) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return context.getDrawable(res);
} else {
return context.getResources().getDrawable(res);
}
}
/** /**
* Draws the trapezoid background for the horizontal tabs on a canvas object using * Draws the trapezoid background for the horizontal tabs on a canvas object using
* the specified color. * the specified color.

View File

@ -22,7 +22,9 @@ public class WebUtils {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
c.removeAllCookies(null); c.removeAllCookies(null);
} else { } else {
//noinspection deprecation
CookieSyncManager.createInstance(context); CookieSyncManager.createInstance(context);
//noinspection deprecation
c.removeAllCookie(); c.removeAllCookie();
} }
} }
@ -37,7 +39,9 @@ public class WebUtils {
m.clearFormData(); m.clearFormData();
m.clearHttpAuthUsernamePassword(); m.clearHttpAuthUsernamePassword();
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
//noinspection deprecation
m.clearUsernamePassword(); m.clearUsernamePassword();
//noinspection deprecation
WebIconDatabase.getInstance().removeAllIcons(); WebIconDatabase.getInstance().removeAllIcons();
} }
Utils.trimCache(context); Utils.trimCache(context);

View File

@ -123,7 +123,9 @@ public class LightningView {
mWebView.setDrawingCacheEnabled(false); mWebView.setDrawingCacheEnabled(false);
mWebView.setWillNotCacheDrawing(true); mWebView.setWillNotCacheDrawing(true);
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) { if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
//noinspection deprecation
mWebView.setAnimationCacheEnabled(false); mWebView.setAnimationCacheEnabled(false);
//noinspection deprecation
mWebView.setAlwaysDrawnWithCacheEnabled(false); mWebView.setAlwaysDrawnWithCacheEnabled(false);
} }
mWebView.setBackgroundColor(Color.WHITE); mWebView.setBackgroundColor(Color.WHITE);
@ -197,12 +199,15 @@ public class LightningView {
if (API < Build.VERSION_CODES.KITKAT) { if (API < Build.VERSION_CODES.KITKAT) {
switch (mPreferences.getFlashSupport()) { switch (mPreferences.getFlashSupport()) {
case 0: case 0:
//noinspection deprecation
settings.setPluginState(PluginState.OFF); settings.setPluginState(PluginState.OFF);
break; break;
case 1: case 1:
//noinspection deprecation
settings.setPluginState(PluginState.ON_DEMAND); settings.setPluginState(PluginState.ON_DEMAND);
break; break;
case 2: case 2:
//noinspection deprecation
settings.setPluginState(PluginState.ON); settings.setPluginState(PluginState.ON);
break; break;
default: default:
@ -213,12 +218,14 @@ public class LightningView {
setUserAgent(context, mPreferences.getUserAgentChoice()); setUserAgent(context, mPreferences.getUserAgentChoice());
if (mPreferences.getSavePasswordsEnabled() && !mIsIncognitoTab) { if (mPreferences.getSavePasswordsEnabled() && !mIsIncognitoTab) {
if (API < 18) { if (API < Build.VERSION_CODES.JELLY_BEAN_MR2) {
//noinspection deprecation
settings.setSavePassword(true); settings.setSavePassword(true);
} }
settings.setSaveFormData(true); settings.setSaveFormData(true);
} else { } else {
if (API < 18) { if (API < Build.VERSION_CODES.JELLY_BEAN_MR2) {
//noinspection deprecation
settings.setSavePassword(false); settings.setSavePassword(false);
} }
settings.setSaveFormData(false); settings.setSaveFormData(false);
@ -293,9 +300,11 @@ public class LightningView {
@SuppressLint("NewApi") @SuppressLint("NewApi")
private void initializeSettings(WebSettings settings, Context context) { private void initializeSettings(WebSettings settings, Context context) {
if (API < Build.VERSION_CODES.JELLY_BEAN_MR2) { if (API < Build.VERSION_CODES.JELLY_BEAN_MR2) {
//noinspection deprecation
settings.setAppCacheMaxSize(Long.MAX_VALUE); settings.setAppCacheMaxSize(Long.MAX_VALUE);
} }
if (API < Build.VERSION_CODES.JELLY_BEAN_MR1) { if (API < Build.VERSION_CODES.JELLY_BEAN_MR1) {
//noinspection deprecation
settings.setEnableSmoothTransition(true); settings.setEnableSmoothTransition(true);
} }
if (API > Build.VERSION_CODES.JELLY_BEAN) { if (API > Build.VERSION_CODES.JELLY_BEAN) {
@ -331,6 +340,7 @@ public class LightningView {
settings.setAppCachePath(context.getDir("appcache", 0).getPath()); settings.setAppCachePath(context.getDir("appcache", 0).getPath());
settings.setGeolocationDatabasePath(context.getDir("geolocation", 0).getPath()); settings.setGeolocationDatabasePath(context.getDir("geolocation", 0).getPath());
if (API < Build.VERSION_CODES.KITKAT) { if (API < Build.VERSION_CODES.KITKAT) {
//noinspection deprecation
settings.setDatabasePath(context.getDir("databases", 0).getPath()); settings.setDatabasePath(context.getDir("databases", 0).getPath());
} }
} }
@ -346,7 +356,7 @@ public class LightningView {
} }
@SuppressLint("NewApi") @SuppressLint("NewApi")
public void setUserAgent(Context context, int choice) { private void setUserAgent(Context context, int choice) {
if (mWebView == null) return; if (mWebView == null) return;
WebSettings settings = mWebView.getSettings(); WebSettings settings = mWebView.getSettings();
switch (choice) { switch (choice) {
@ -388,8 +398,10 @@ public class LightningView {
} }
public synchronized void freeMemory() { public synchronized void freeMemory() {
if (mWebView != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) if (mWebView != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
//noinspection deprecation
mWebView.freeMemory(); mWebView.freeMemory();
}
} }
public void setForegroundTab(boolean isForeground) { public void setForegroundTab(boolean isForeground) {
@ -526,6 +538,7 @@ public class LightningView {
if (API >= Build.VERSION_CODES.JELLY_BEAN_MR1) { if (API >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
mWebView.findAllAsync(text); mWebView.findAllAsync(text);
} else { } else {
//noinspection deprecation
mWebView.findAll(text); mWebView.findAll(text);
} }
} }
@ -593,12 +606,6 @@ public class LightningView {
} }
} }
public synchronized void invalidate() {
if (mWebView != null) {
mWebView.invalidate();
}
}
public String getTitle() { public String getTitle() {
return mTitle.getTitle(); return mTitle.getTitle();
} }
@ -658,6 +665,7 @@ public class LightningView {
return super.shouldInterceptRequest(view, request); return super.shouldInterceptRequest(view, request);
} }
@SuppressWarnings("deprecation")
@Override @Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) { public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
if (mAdBlock.isAd(url)) { if (mAdBlock.isAd(url)) {
@ -944,14 +952,17 @@ public class LightningView {
mBrowserController.onCloseWindow(LightningView.this); mBrowserController.onCloseWindow(LightningView.this);
} }
@SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg) { public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mBrowserController.openFileChooser(uploadMsg); mBrowserController.openFileChooser(uploadMsg);
} }
@SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) { public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
mBrowserController.openFileChooser(uploadMsg); mBrowserController.openFileChooser(uploadMsg);
} }
@SuppressWarnings("unused")
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) { public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
mBrowserController.openFileChooser(uploadMsg); mBrowserController.openFileChooser(uploadMsg);
} }
@ -999,6 +1010,7 @@ public class LightningView {
super.onShowCustomView(view, callback); super.onShowCustomView(view, callback);
} }
@SuppressWarnings("deprecation")
@Override @Override
@Deprecated @Deprecated
public void onShowCustomView(View view, int requestedOrientation, public void onShowCustomView(View view, int requestedOrientation,

View File

@ -1,4 +1,5 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<!--suppress AndroidElementNotAllowed -->
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="@string/settings_about"> <PreferenceCategory android:title="@string/settings_about">