diff --git a/app/build.gradle.kts b/app/build.gradle.kts index a45e26a132ffeb79b9d1387680cf8bba8d7fe5e5..72ab2c3da3d20c814b71975282fc9179eb487248 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -43,7 +43,7 @@ android { testInstrumentationRunner = "android.support.test.runner.AndroidJUnitRunner" renderscriptTargetApi = 28 renderscriptSupportModeEnabled = true - setProperty("archivesBaseName", "BlissLauncher-v$versionName") + setProperty("archivesBaseName", "BlissLauncher-$versionName") } buildTypes { diff --git a/app/src/androidTest/java/foundation/e/blisslauncher/ExampleInstrumentedTest.java b/app/src/androidTest/java/foundation/e/blisslauncher/ExampleInstrumentedTest.java index f0223b542855e3e0a8796aa661923aa7d72ac19b..fd263cef330d90e2afe34ea46ffce3dca7e23cf7 100755 --- a/app/src/androidTest/java/foundation/e/blisslauncher/ExampleInstrumentedTest.java +++ b/app/src/androidTest/java/foundation/e/blisslauncher/ExampleInstrumentedTest.java @@ -17,12 +17,11 @@ package foundation.e.blisslauncher; import static org.junit.Assert.*; -import org.junit.Test; -import org.junit.runner.RunWith; - import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; +import org.junit.Test; +import org.junit.runner.RunWith; /** * Instrumentation test, which will execute on an Android device. diff --git a/app/src/apiNougat/java/foundation/e/blisslauncher/core/Preferences.java b/app/src/apiNougat/java/foundation/e/blisslauncher/core/Preferences.java index 9bd5deab9df7e135452c732aee700f2225e2bf47..135a06c995ee41c44552423508b431a718a6b5a4 100644 --- a/app/src/apiNougat/java/foundation/e/blisslauncher/core/Preferences.java +++ b/app/src/apiNougat/java/foundation/e/blisslauncher/core/Preferences.java @@ -3,24 +3,20 @@ package foundation.e.blisslauncher.core; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Color; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import java.util.ArrayList; -import java.util.Locale; - import cyanogenmod.weather.WeatherInfo; import cyanogenmod.weather.WeatherLocation; import foundation.e.blisslauncher.core.utils.Constants; +import java.util.ArrayList; +import java.util.Locale; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; public class Preferences { - /** - * Weather related keys and constants. - */ + /** Weather related keys and constants. */ private static final String WEATHER_LOCATION_CITY_ID = "city_id"; + private static final String WEATHER_LOCATION_CITY_NAME = "city_name"; private static final String WEATHER_LOCATION_STATE = "state"; private static final String WEATHER_LOCATION_POSTAL_CODE = "postal_code"; @@ -64,8 +60,8 @@ public class Preferences { } public static int weatherFontColor(Context context) { - int color = Color.parseColor(getPrefs(context).getString(Constants.WEATHER_FONT_COLOR, - Constants.DEFAULT_LIGHT_COLOR)); + int color = Color + .parseColor(getPrefs(context).getString(Constants.WEATHER_FONT_COLOR, Constants.DEFAULT_LIGHT_COLOR)); return color; } @@ -75,8 +71,7 @@ public class Preferences { public static boolean useMetricUnits(Context context) { Locale locale = context.getResources().getConfiguration().locale; - boolean defValue = !(locale.equals(Locale.US) - || locale.toString().equals("ms_MY") // Malaysia + boolean defValue = !(locale.equals(Locale.US) || locale.toString().equals("ms_MY") // Malaysia || locale.toString().equals("si_LK") // Sri Lanka ); return getPrefs(context).getBoolean(Constants.WEATHER_USE_METRIC, defValue); @@ -107,17 +102,14 @@ public class Preferences { getPrefs(context).edit().putString(Constants.WEATHER_CUSTOM_LOCATION_CITY, city).apply(); } - public static boolean setCustomWeatherLocation(Context context, - WeatherLocation weatherLocation) { + public static boolean setCustomWeatherLocation(Context context, WeatherLocation weatherLocation) { if (weatherLocation == null) { - getPrefs(context).edit() - .remove(Constants.WEATHER_CUSTOM_LOCATION).apply(); + getPrefs(context).edit().remove(Constants.WEATHER_CUSTOM_LOCATION).apply(); return true; } try { JSONObject jsonObject = weatherLocationToJSON(weatherLocation); - getPrefs(context).edit() - .putString(Constants.WEATHER_CUSTOM_LOCATION, jsonObject.toString()).apply(); + getPrefs(context).edit().putString(Constants.WEATHER_CUSTOM_LOCATION, jsonObject.toString()).apply(); return true; } catch (JSONException e) { // We're here because weatherLocationToJSON() or jsonObject.toString() failed. @@ -127,8 +119,7 @@ public class Preferences { } public static WeatherLocation getCustomWeatherLocation(Context context) { - String weatherLocation = getPrefs(context) - .getString(Constants.WEATHER_CUSTOM_LOCATION, null); + String weatherLocation = getPrefs(context).getString(Constants.WEATHER_CUSTOM_LOCATION, null); if (weatherLocation == null) { return null; @@ -142,8 +133,7 @@ public class Preferences { } } - private static WeatherLocation JSONToWeatherLocation(JSONObject jsonObject) - throws JSONException { + private static WeatherLocation JSONToWeatherLocation(JSONObject jsonObject) throws JSONException { String cityId; String cityName; String state; @@ -158,25 +148,27 @@ public class Preferences { countryId = jsonObject.getString(WEATHER_LOCATION_COUNTRY_ID); countryName = jsonObject.getString(WEATHER_LOCATION_COUNTRY_NAME); - //We need at least city id and city name to build a WeatherLocation + // We need at least city id and city name to build a WeatherLocation if (cityId == null && cityName == null) { return null; } WeatherLocation.Builder location = new WeatherLocation.Builder(cityId, cityName); - if (countryId != null) location.setCountryId(countryId); - if (countryName != null) location.setCountry(countryName); - if (state != null) location.setState(state); - if (postalCode != null) location.setPostalCode(postalCode); + if (countryId != null) + location.setCountryId(countryId); + if (countryName != null) + location.setCountry(countryName); + if (state != null) + location.setState(state); + if (postalCode != null) + location.setPostalCode(postalCode); return location.build(); } private static JSONObject weatherLocationToJSON(WeatherLocation location) throws JSONException { - return new JSONObject() - .put(WEATHER_LOCATION_CITY_ID, location.getCityId()) - .put(WEATHER_LOCATION_CITY_NAME, location.getCity()) - .put(WEATHER_LOCATION_STATE, location.getState()) + return new JSONObject().put(WEATHER_LOCATION_CITY_ID, location.getCityId()) + .put(WEATHER_LOCATION_CITY_NAME, location.getCity()).put(WEATHER_LOCATION_STATE, location.getState()) .put(WEATHER_LOCATION_POSTAL_CODE, location.getPostalCode()) .put(WEATHER_LOCATION_COUNTRY_ID, location.getCountryId()) .put(WEATHER_LOCATION_COUNTRY_NAME, location.getCountry()); @@ -190,9 +182,8 @@ public class Preferences { JSONObject jsonObject = new JSONObject(); boolean serialized = false; try { - //These members always return a value that can be parsed - jsonObject - .put(WEATHER_INFO_CITY, info.getCity()) + // These members always return a value that can be parsed + jsonObject.put(WEATHER_INFO_CITY, info.getCity()) .put(WEATHER_INFO_CONDITION_CODE, info.getConditionCode()) .put(WEATHER_INFO_TEMPERATURE, info.getTemperature()) .put(WEATHER_INFO_TEMPERATURE_UNIT, info.getTemperatureUnit()) @@ -205,24 +196,21 @@ public class Preferences { jsonObject.put(WEATHER_INFO_HUMIDITY, Double.isNaN(humidity) ? "NaN" : humidity); double todaysHigh = info.getTodaysHigh(); - jsonObject.put(WEATHER_INFO_TODAYS_HIGH, Double.isNaN(todaysHigh) - ? "NaN" : todaysHigh); + jsonObject.put(WEATHER_INFO_TODAYS_HIGH, Double.isNaN(todaysHigh) ? "NaN" : todaysHigh); double todaysLow = info.getTodaysLow(); - jsonObject.put(WEATHER_INFO_TODAYS_LOW, Double.isNaN(todaysLow) - ? "NaN" : todaysLow); + jsonObject.put(WEATHER_INFO_TODAYS_LOW, Double.isNaN(todaysLow) ? "NaN" : todaysLow); double windSpeed = info.getWindSpeed(); double windDirection = info.getWindDirection(); jsonObject.put(WEATHER_INFO_WIND_SPEED, Double.isNaN(windSpeed) ? "NaN" : windSpeed) .put(WEATHER_INFO_WIND_SPEED_UNIT, info.getWindSpeedUnit()) - .put(WEATHER_INFO_WIND_SPEED_DIRECTION, Double.isNaN(windDirection) - ? "NaN" : windDirection); + .put(WEATHER_INFO_WIND_SPEED_DIRECTION, Double.isNaN(windDirection) ? "NaN" : windDirection); JSONArray forecastArray = new JSONArray(); for (WeatherInfo.DayForecast forecast : info.getForecasts()) { - JSONObject jsonForecast = new JSONObject() - .put(DAY_FORECAST_CONDITION_CODE, forecast.getConditionCode()); + JSONObject jsonForecast = new JSONObject().put(DAY_FORECAST_CONDITION_CODE, + forecast.getConditionCode()); double low = forecast.getLow(); jsonForecast.put(DAY_FORECAST_LOW, Double.isNaN(low) ? "NaN" : low); @@ -257,7 +245,8 @@ public class Preferences { public static WeatherInfo getCachedWeatherInfo(Context context) { final String cachedInfo = getPrefs(context).getString(Constants.WEATHER_DATA, null); - if (cachedInfo == null) return null; + if (cachedInfo == null) + return null; String city; int conditionCode; @@ -295,21 +284,26 @@ public class Preferences { high = forecast.getDouble(DAY_FORECAST_HIGH); code = forecast.getInt(DAY_FORECAST_CONDITION_CODE); WeatherInfo.DayForecast.Builder f = new WeatherInfo.DayForecast.Builder(code); - if (!Double.isNaN(low)) f.setLow(low); - if (!Double.isNaN(high)) f.setHigh(high); + if (!Double.isNaN(low)) + f.setLow(low); + if (!Double.isNaN(high)) + f.setHigh(high); forecastList.add(f.build()); } WeatherInfo.Builder weatherInfo = new WeatherInfo.Builder(city, temperature, tempUnit) - .setWeatherCondition(conditionCode) - .setTimestamp(timestamp); + .setWeatherCondition(conditionCode).setTimestamp(timestamp); - if (!Double.isNaN(humidity)) weatherInfo.setHumidity(humidity); + if (!Double.isNaN(humidity)) + weatherInfo.setHumidity(humidity); if (!Double.isNaN(windSpeed) && !Double.isNaN(windDirection)) { weatherInfo.setWind(windSpeed, windDirection, windSpeedUnit); } - if (forecastList.size() > 0) weatherInfo.setForecast(forecastList); - if (!Double.isNaN(todaysHigh)) weatherInfo.setTodaysHigh(todaysHigh); - if (!Double.isNaN(todaysLow)) weatherInfo.setTodaysLow(todaysLow); + if (forecastList.size() > 0) + weatherInfo.setForecast(forecastList); + if (!Double.isNaN(todaysHigh)) + weatherInfo.setTodaysHigh(todaysHigh); + if (!Double.isNaN(todaysLow)) + weatherInfo.setTodaysLow(todaysLow); return weatherInfo.build(); } catch (JSONException e) { } @@ -344,11 +338,11 @@ public class Preferences { getPrefs(context).edit().putBoolean(NOTIFICATION_ACCESS, false).apply(); } - public static int getCurrentMigrationVersion(Context context){ + public static int getCurrentMigrationVersion(Context context) { return getPrefs(context).getInt(CURRENT_MIGRATION_VERSION, 0); } - public static void setCurrentMigrationVersion(Context context, int version){ + public static void setCurrentMigrationVersion(Context context, int version) { getPrefs(context).edit().putInt(CURRENT_MIGRATION_VERSION, version).apply(); } @@ -360,8 +354,7 @@ public class Preferences { getPrefs(context).edit().putBoolean(ENABLE_LOCATION, true).apply(); } - public static boolean getEnableLocation( - Context context) { + public static boolean getEnableLocation(Context context) { return getPrefs(context).getBoolean(ENABLE_LOCATION, false); } diff --git a/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/CustomLocationPreference.java b/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/CustomLocationPreference.java index a84a6455655587849a82b4827783c0feb16cabcb..d4f4a43cfb3dbba932daf6b194081c15b35828fc 100644 --- a/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/CustomLocationPreference.java +++ b/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/CustomLocationPreference.java @@ -12,17 +12,14 @@ import android.util.AttributeSet; import android.view.View; import android.widget.Button; import android.widget.Toast; - -import java.util.HashSet; -import java.util.List; - import cyanogenmod.weather.CMWeatherManager; import cyanogenmod.weather.WeatherLocation; import foundation.e.blisslauncher.R; import foundation.e.blisslauncher.core.Preferences; +import java.util.HashSet; +import java.util.List; -public class CustomLocationPreference extends EditTextPreference - implements CMWeatherManager.LookupCityRequestListener { +public class CustomLocationPreference extends EditTextPreference implements CMWeatherManager.LookupCityRequestListener { public CustomLocationPreference(Context context) { super(context); } @@ -49,15 +46,14 @@ public class CustomLocationPreference extends EditTextPreference okButton.setOnClickListener(v -> { CustomLocationPreference.this.onClick(d, DialogInterface.BUTTON_POSITIVE); final String customLocationToLookUp = getEditText().getText().toString(); - if (TextUtils.equals(customLocationToLookUp, "")) return; + if (TextUtils.equals(customLocationToLookUp, "")) + return; final CMWeatherManager weatherManager = CMWeatherManager.getInstance(getContext()); mProgressDialog = new ProgressDialog(getContext()); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mProgressDialog.setMessage(getContext().getString(R.string.weather_progress_title)); - mProgressDialog.setOnCancelListener( - dialog -> weatherManager.cancelRequest(mCustomLocationRequestId)); - mCustomLocationRequestId = weatherManager.lookupCity(customLocationToLookUp, - CustomLocationPreference.this); + mProgressDialog.setOnCancelListener(dialog -> weatherManager.cancelRequest(mCustomLocationRequestId)); + mCustomLocationRequestId = weatherManager.lookupCity(customLocationToLookUp, CustomLocationPreference.this); mProgressDialog.show(); }); } @@ -83,14 +79,10 @@ public class CustomLocationPreference extends EditTextPreference private void handleResultDisambiguation(final List results) { CharSequence[] items = buildItemList(results); - new AlertDialog.Builder(getContext()) - .setSingleChoiceItems(items, -1, (dialog, which) -> { - applyLocation(results.get(which)); - dialog.dismiss(); - }) - .setNegativeButton(android.R.string.cancel, null) - .setTitle(R.string.weather_select_location) - .show(); + new AlertDialog.Builder(getContext()).setSingleChoiceItems(items, -1, (dialog, which) -> { + applyLocation(results.get(which)); + dialog.dismiss(); + }).setNegativeButton(android.R.string.cancel, null).setTitle(R.string.weather_select_location).show(); } private CharSequence[] buildItemList(List results) { @@ -122,8 +114,7 @@ public class CustomLocationPreference extends EditTextPreference } builder.append(result.getCity()); if (needCountry) { - String country = result.getCountry() != null - ? result.getCountry() : result.getCountryId(); + String country = result.getCountry() != null ? result.getCountry() : result.getCountryId(); builder.append(" (").append(country).append(")"); } items[i] = builder.toString(); @@ -147,10 +138,8 @@ public class CustomLocationPreference extends EditTextPreference mHandler.post(() -> { final Context context = getContext(); if (locations == null || locations.isEmpty()) { - Toast.makeText(context, - context.getString(R.string.weather_retrieve_location_dialog_title), - Toast.LENGTH_SHORT) - .show(); + Toast.makeText(context, context.getString(R.string.weather_retrieve_location_dialog_title), + Toast.LENGTH_SHORT).show(); } else if (locations.size() > 1) { handleResultDisambiguation(locations); } else { diff --git a/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/DeviceStatusService.java b/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/DeviceStatusService.java index 43635b91989ef95793f646a5511038f385ebfddc..66dd96d45e467b0325a823411857b85d9116518d 100644 --- a/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/DeviceStatusService.java +++ b/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/DeviceStatusService.java @@ -8,7 +8,6 @@ import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.IBinder; import android.util.Log; - import foundation.e.blisslauncher.core.utils.Constants; public class DeviceStatusService extends Service { @@ -21,12 +20,13 @@ public class DeviceStatusService extends Service { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); - // Network connection has changed, make sure the weather update service knows about it + // Network connection has changed, make sure the weather update service knows + // about it if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) { - boolean hasConnection = !intent.getBooleanExtra( - ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); + boolean hasConnection = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); - if (D) Log.d(TAG, "Got connectivity change, has connection: " + hasConnection); + if (D) + Log.d(TAG, "Got connectivity change, has connection: " + hasConnection); Intent i = new Intent(context, WeatherUpdateService.class); if (hasConnection) { @@ -35,10 +35,12 @@ public class DeviceStatusService extends Service { context.stopService(i); } } else if (Intent.ACTION_SCREEN_OFF.equals(action)) { - if (D) Log.d(TAG, "onDisplayOff: Cancel pending update"); + if (D) + Log.d(TAG, "onDisplayOff: Cancel pending update"); WeatherUpdateService.cancelUpdates(context); } else if (Intent.ACTION_SCREEN_ON.equals(action)) { - if (D) Log.d(TAG, "onDisplayOn: Reschedule update"); + if (D) + Log.d(TAG, "onDisplayOn: Reschedule update"); WeatherUpdateService.scheduleNextUpdate(context, false); } } @@ -55,13 +57,15 @@ public class DeviceStatusService extends Service { @Override public void onDestroy() { - if (D) Log.d(TAG, "Stopping service"); + if (D) + Log.d(TAG, "Stopping service"); unregisterReceiver(mDeviceStatusListenerReceiver); } @Override public int onStartCommand(Intent intent, int flags, int startId) { - if (D) Log.d(TAG, "Starting service"); + if (D) + Log.d(TAG, "Starting service"); return START_STICKY; } diff --git a/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/ForecastBuilder.java b/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/ForecastBuilder.java index e38de4c14117a3024765300141af6e88af0de292..42e98814b9638e53125a7b6cc1ff810fe61a908a 100644 --- a/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/ForecastBuilder.java +++ b/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/ForecastBuilder.java @@ -14,18 +14,16 @@ import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; - +import cyanogenmod.weather.WeatherInfo; +import cyanogenmod.weather.util.WeatherUtils; +import foundation.e.blisslauncher.R; +import foundation.e.blisslauncher.core.Preferences; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import java.util.TimeZone; -import cyanogenmod.weather.WeatherInfo; -import cyanogenmod.weather.util.WeatherUtils; -import foundation.e.blisslauncher.R; -import foundation.e.blisslauncher.core.Preferences; - public class ForecastBuilder { private static final String TAG = "ForecastBuilder"; @@ -33,9 +31,12 @@ public class ForecastBuilder { /** * This method is used to build the forecast panel * - * @param context Context to be used - * @param weatherPanel a view that will contain the forecast - * @param w the Weather info object that contains the forecast data + * @param context + * Context to be used + * @param weatherPanel + * a view that will contain the forecast + * @param w + * the Weather info object that contains the forecast data */ @SuppressLint("InflateParams") public static void buildLargePanel(Context context, View weatherPanel, WeatherInfo w) { @@ -67,9 +68,8 @@ public class ForecastBuilder { // Weather Image ImageView weatherImage = weatherPanel.findViewById(R.id.weather_image); String iconsSet = Preferences.getWeatherIconSet(context); - weatherImage.setImageBitmap( - WeatherIconUtils.getWeatherIconBitmap(context, iconsSet, color, - w.getConditionCode(), WeatherIconUtils.getNextHigherDensity(context))); + weatherImage.setImageBitmap(WeatherIconUtils.getWeatherIconBitmap(context, iconsSet, color, + w.getConditionCode(), WeatherIconUtils.getNextHigherDensity(context))); // City TextView city = weatherPanel.findViewById(R.id.weather_city); @@ -77,14 +77,11 @@ public class ForecastBuilder { // Weather Condition TextView weatherCondition = weatherPanel.findViewById(R.id.weather_condition); - weatherCondition.setText( - foundation.e.blisslauncher.features.weather.WeatherUtils.resolveWeatherCondition( - context, - w.getConditionCode())); + weatherCondition.setText(foundation.e.blisslauncher.features.weather.WeatherUtils + .resolveWeatherCondition(context, w.getConditionCode())); // Weather Temps - TextView weatherTemp = weatherPanel.findViewById( - R.id.weather_current_temperature); + TextView weatherTemp = weatherPanel.findViewById(R.id.weather_current_temperature); weatherTemp.setText(WeatherUtils.formatTemperature(temp, tempUnit)); // Weather Temps Panel additional networkItems @@ -97,26 +94,20 @@ public class ForecastBuilder { int windSpeedUnit = w.getWindSpeedUnit(); if (windSpeedUnit == MPH && useMetric) { windSpeedUnit = KPH; - windSpeed = foundation.e.blisslauncher.features.weather.WeatherUtils.milesToKilometers( - windSpeed); + windSpeed = foundation.e.blisslauncher.features.weather.WeatherUtils.milesToKilometers(windSpeed); } else if (windSpeedUnit == KPH && !useMetric) { windSpeedUnit = MPH; - windSpeed = foundation.e.blisslauncher.features.weather.WeatherUtils.kilometersToMiles( - windSpeed); + windSpeed = foundation.e.blisslauncher.features.weather.WeatherUtils.kilometersToMiles(windSpeed); } - // Humidity and Wind TextView weatherHumWind = weatherPanel.findViewById(R.id.weather_chance_rain); - weatherHumWind.setText( - String.format("%s, %s %s", - foundation.e.blisslauncher.features.weather.WeatherUtils.formatHumidity( - w.getHumidity()), - foundation.e.blisslauncher.features.weather.WeatherUtils.formatWindSpeed( - context, windSpeed, windSpeedUnit), - foundation.e.blisslauncher.features.weather.WeatherUtils - .resolveWindDirection( - context, w.getWindDirection()))); + weatherHumWind.setText(String.format("%s, %s %s", + foundation.e.blisslauncher.features.weather.WeatherUtils.formatHumidity(w.getHumidity()), + foundation.e.blisslauncher.features.weather.WeatherUtils.formatWindSpeed(context, windSpeed, + windSpeedUnit), + foundation.e.blisslauncher.features.weather.WeatherUtils.resolveWindDirection(context, + w.getWindDirection()))); LinearLayout forecastView = weatherPanel.findViewById(R.id.forecast_view); buildSmallPanel(context, forecastView, w); } @@ -124,9 +115,12 @@ public class ForecastBuilder { /** * This method is used to build the small, horizontal forecasts panel * - * @param context Context to be used - * @param smallPanel a horizontal {@link LinearLayout} that will contain the forecasts - * @param w the Weather info object that contains the forecast data + * @param context + * Context to be used + * @param smallPanel + * a horizontal {@link LinearLayout} that will contain the forecasts + * @param w + * the Weather info object that contains the forecast data */ @SuppressLint("InflateParams") private static void buildSmallPanel(Context context, LinearLayout smallPanel, WeatherInfo w) { @@ -136,8 +130,7 @@ public class ForecastBuilder { } // Get things ready - LayoutInflater inflater - = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); int color = Preferences.weatherFontColor(context); final boolean useMetric = Preferences.useMetricUnits(context); @@ -152,8 +145,7 @@ public class ForecastBuilder { Calendar calendar = new GregorianCalendar(MyTimezone); int weatherTempUnit = w.getTemperatureUnit(); int numForecasts = forecasts.size(); - int itemSidePadding = context.getResources().getDimensionPixelSize( - R.dimen.forecast_item_padding_side); + int itemSidePadding = context.getResources().getDimensionPixelSize(R.dimen.forecast_item_padding_side); // Iterate through the Forecasts for (int count = 0; count < numForecasts; count++) { @@ -165,20 +157,18 @@ public class ForecastBuilder { // The day of the week TextView day = forecastItem.findViewById(R.id.forecast_day); - day.setText(calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, - Locale.getDefault())); + day.setText(calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault())); calendar.roll(Calendar.DAY_OF_WEEK, true); // Weather Image ImageView image = forecastItem.findViewById(R.id.weather_image); String iconsSet = Preferences.getWeatherIconSet(context); - final int resId = WeatherIconUtils.getWeatherIconResource(context, iconsSet, - d.getConditionCode()); + final int resId = WeatherIconUtils.getWeatherIconResource(context, iconsSet, d.getConditionCode()); if (resId != 0) { image.setImageResource(resId); } else { - image.setImageBitmap(WeatherIconUtils.getWeatherIconBitmap(context, iconsSet, - color, d.getConditionCode())); + image.setImageBitmap( + WeatherIconUtils.getWeatherIconBitmap(context, iconsSet, color, d.getConditionCode())); } // Temperatures @@ -194,8 +184,7 @@ public class ForecastBuilder { highTemp = cyanogenmod.weather.util.WeatherUtils.celsiusToFahrenheit(highTemp); tempUnit = FAHRENHEIT; } - String dayLow = cyanogenmod.weather.util.WeatherUtils.formatTemperature(lowTemp, - tempUnit); + String dayLow = cyanogenmod.weather.util.WeatherUtils.formatTemperature(lowTemp, tempUnit); String dayHigh = WeatherUtils.formatTemperature(highTemp, tempUnit); TextView temps = forecastItem.findViewById(R.id.weather_temps); temps.setText(String.format("%s\n%s", dayLow, dayHigh)); @@ -207,14 +196,14 @@ public class ForecastBuilder { // Add a divider to the right for all but the last view if (count < numForecasts - 1) { View divider = new View(context); - smallPanel.addView(divider, new LinearLayout.LayoutParams( - itemSidePadding, LinearLayout.LayoutParams.MATCH_PARENT)); + smallPanel.addView(divider, + new LinearLayout.LayoutParams(itemSidePadding, LinearLayout.LayoutParams.MATCH_PARENT)); } } smallPanel.setOnClickListener(v -> { Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage("foundation.e.weather"); - if(launchIntent != null){ + if (launchIntent != null) { launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(launchIntent); } diff --git a/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/IconSelectionPreference.java b/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/IconSelectionPreference.java index 57b4e882da15b8cacc64c9557aa4bab3d5362f13..18752a5d682d650aba7d64697700fe277c529bf9 100644 --- a/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/IconSelectionPreference.java +++ b/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/IconSelectionPreference.java @@ -25,17 +25,13 @@ import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; - import androidx.annotation.NonNull; - +import foundation.e.blisslauncher.R; import java.util.ArrayList; import java.util.Arrays; import java.util.Locale; -import foundation.e.blisslauncher.R; - -public class IconSelectionPreference extends DialogPreference implements - AdapterView.OnItemClickListener { +public class IconSelectionPreference extends DialogPreference implements AdapterView.OnItemClickListener { private static final String INTENT_CATEGORY_ICONPACK = "com.dvtonder.chronus.ICON_PACK"; private static final String SEARCH_URI = "https://market.android.com/search?q=%s&c=apps"; @@ -46,24 +42,26 @@ public class IconSelectionPreference extends DialogPreference implements int descriptionResId; Drawable previewDrawable; int previewResId; - IconSetDescriptor(String name, int descriptionResId, - int previewResId) { + + IconSetDescriptor(String name, int descriptionResId, int previewResId) { this.name = name; this.descriptionResId = descriptionResId; this.previewResId = previewResId; } - IconSetDescriptor(String packageName, CharSequence description, - Drawable preview) { + + IconSetDescriptor(String packageName, CharSequence description, Drawable preview) { this.name = "ext:" + packageName; this.description = description; this.previewDrawable = preview; } + public CharSequence getDescription(Context context) { if (description != null) { return description; } return context.getString(descriptionResId); } + @Override public boolean equals(Object other) { if (other instanceof IconSetDescriptor) { @@ -74,16 +72,13 @@ public class IconSelectionPreference extends DialogPreference implements } } - private static final IconSetDescriptor ICON_SETS[] = new IconSetDescriptor[] { - new IconSetDescriptor("color", R.string.weather_icons_standard, - R.drawable.weather_color_28), - new IconSetDescriptor("mono", R.string.weather_icons_monochrome, - R.drawable.weather_28), - new IconSetDescriptor("vclouds", R.string.weather_icons_vclouds, - R.drawable.weather_vclouds_28) - }; + private static final IconSetDescriptor ICON_SETS[] = new IconSetDescriptor[]{ + new IconSetDescriptor("color", R.string.weather_icons_standard, R.drawable.weather_color_28), + new IconSetDescriptor("mono", R.string.weather_icons_monochrome, R.drawable.weather_28), + new IconSetDescriptor("vclouds", R.string.weather_icons_vclouds, R.drawable.weather_vclouds_28)}; private static final IntentFilter PACKAGE_CHANGE_FILTER = new IntentFilter(); + static { PACKAGE_CHANGE_FILTER.addAction(Intent.ACTION_PACKAGE_ADDED); PACKAGE_CHANGE_FILTER.addAction(Intent.ACTION_PACKAGE_REMOVED); @@ -134,8 +129,7 @@ public class IconSelectionPreference extends DialogPreference implements AlertDialog d = (AlertDialog) getDialog(); d.getButton(DialogInterface.BUTTON_NEUTRAL).setOnClickListener(view -> { - String uri = String.format(Locale.US, SEARCH_URI, - getContext().getString(R.string.icon_set_store_filter)); + String uri = String.format(Locale.US, SEARCH_URI, getContext().getString(R.string.icon_set_store_filter)); viewUri(getContext(), uri); }); } @@ -219,7 +213,7 @@ public class IconSelectionPreference extends DialogPreference implements public IconSetAdapter(Context context) { super(context, R.layout.icon_item, 0, populateIconSets(context)); - mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void reenumerateIconSets() { @@ -246,8 +240,7 @@ public class IconSelectionPreference extends DialogPreference implements } private static ArrayList populateIconSets(Context context) { - ArrayList result = new ArrayList<>( - Arrays.asList(ICON_SETS)); + ArrayList result = new ArrayList<>(Arrays.asList(ICON_SETS)); PackageManager pm = context.getPackageManager(); Intent i = new Intent(Intent.ACTION_MAIN); @@ -259,8 +252,7 @@ public class IconSelectionPreference extends DialogPreference implements Resources res = pm.getResourcesForApplication(appInfo); int previewResId = res.getIdentifier("weather_28", "drawable", appInfo.packageName); Drawable preview = previewResId != 0 ? res.getDrawable(previewResId) : null; - result.add(new IconSetDescriptor(appInfo.packageName, - appInfo.loadLabel(pm), preview)); + result.add(new IconSetDescriptor(appInfo.packageName, appInfo.loadLabel(pm), preview)); } catch (PackageManager.NameNotFoundException e) { // shouldn't happen, ignore package } diff --git a/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/PermissionRequestActivity.java b/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/PermissionRequestActivity.java index 9b4637a9a7e222dd4de16d7b3c9ec75e8da4fced..45fe3335d75d8ed6c5a2f1a239669735f33db0f7 100644 --- a/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/PermissionRequestActivity.java +++ b/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/PermissionRequestActivity.java @@ -6,7 +6,6 @@ import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.os.ResultReceiver; - import androidx.annotation.NonNull; public class PermissionRequestActivity extends Activity { @@ -38,16 +37,14 @@ public class PermissionRequestActivity extends Activity { } public boolean hasLocationPermission() { - return checkSelfPermission( - Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED; + return checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) { - if (grantResults.length > 0 - && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { mResult = RESULT_OK; } } diff --git a/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/WeatherIconUtils.java b/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/WeatherIconUtils.java index 7804e09ee81d9eec6aea37e02abdb7e18ed11ee5..dbcc2525bb23ff1830efbb10b80c2b374ed02435 100644 --- a/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/WeatherIconUtils.java +++ b/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/WeatherIconUtils.java @@ -13,7 +13,6 @@ import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.DisplayMetrics; import android.util.Log; - import foundation.e.blisslauncher.R; import foundation.e.blisslauncher.core.utils.Constants; @@ -27,9 +26,9 @@ public class WeatherIconUtils { } final Resources res = context.getResources(); - final int resId = res.getIdentifier("weather_" + iconSet + "_" - + WeatherUtils.addOffsetToConditionCodeFromWeatherContract(conditionCode), "drawable", - context.getPackageName()); + final int resId = res.getIdentifier( + "weather_" + iconSet + "_" + WeatherUtils.addOffsetToConditionCodeFromWeatherContract(conditionCode), + "drawable", context.getPackageName()); if (resId != 0) { return resId; @@ -39,13 +38,12 @@ public class WeatherIconUtils { return R.drawable.weather_color_na; } - public static Bitmap getWeatherIconBitmap(Context context, String iconSet, - int color, int conditionCode) { + public static Bitmap getWeatherIconBitmap(Context context, String iconSet, int color, int conditionCode) { return getWeatherIconBitmap(context, iconSet, color, conditionCode, 0); } - public static Bitmap getWeatherIconBitmap(Context context, String iconSet, - int color, int conditionCode, int density) { + public static Bitmap getWeatherIconBitmap(Context context, String iconSet, int color, int conditionCode, + int density) { boolean isMonoSet = Constants.MONOCHROME.equals(iconSet); Resources res = null; int resId = 0; @@ -63,8 +61,8 @@ public class WeatherIconUtils { } if (resId == 0) { String identifier = isMonoSet - ? "weather_" + fixedConditionCode : "weather_" - + iconSet + "_" + fixedConditionCode; + ? "weather_" + fixedConditionCode + : "weather_" + iconSet + "_" + fixedConditionCode; res = context.getResources(); resId = res.getIdentifier(identifier, "drawable", context.getPackageName()); } @@ -86,8 +84,7 @@ public class WeatherIconUtils { return src; } - final Bitmap dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(), - Bitmap.Config.ARGB_8888); + final Bitmap dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888); Canvas c = new Canvas(dest); final Paint paint = new Paint(); @@ -99,19 +96,20 @@ public class WeatherIconUtils { public static Bitmap getBitmapFromResource(Resources res, int resId, int density) { if (density == 0) { - if (D) Log.d(TAG, "Decoding resource id = " + resId + " for default density"); + if (D) + Log.d(TAG, "Decoding resource id = " + resId + " for default density"); return BitmapFactory.decodeResource(res, resId); } - if (D) Log.d(TAG, "Decoding resource id = " + resId + " for density = " + density); + if (D) + Log.d(TAG, "Decoding resource id = " + resId + " for density = " + density); Drawable d = res.getDrawableForDensity(resId, density); if (d instanceof BitmapDrawable) { BitmapDrawable bd = (BitmapDrawable) d; return bd.getBitmap(); } - Bitmap result = Bitmap.createBitmap(d.getIntrinsicWidth(), - d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); + Bitmap result = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(result); d.setBounds(0, 0, result.getWidth(), result.getHeight()); d.draw(canvas); diff --git a/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/WeatherPreferences.java b/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/WeatherPreferences.java index 460e32a5838e70b32775a10996dfca3d5d9b9c87..e47826ffd8733f396ffcdc1995f2b3550bc10d57 100644 --- a/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/WeatherPreferences.java +++ b/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/WeatherPreferences.java @@ -19,18 +19,16 @@ import android.provider.Settings; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; - import androidx.annotation.NonNull; - import cyanogenmod.weather.CMWeatherManager; import foundation.e.blisslauncher.R; import foundation.e.blisslauncher.core.Preferences; import foundation.e.blisslauncher.core.utils.Constants; - -public class WeatherPreferences extends PreferenceActivity implements - SharedPreferences.OnSharedPreferenceChangeListener, - CMWeatherManager.WeatherServiceProviderChangeListener { +public class WeatherPreferences extends PreferenceActivity + implements + SharedPreferences.OnSharedPreferenceChangeListener, + CMWeatherManager.WeatherServiceProviderChangeListener { private static final String TAG = "WeatherPreferences"; public static final int LOCATION_PERMISSION_REQUEST_CODE = 1; @@ -52,12 +50,10 @@ public class WeatherPreferences extends PreferenceActivity implements // Load networkItems that need custom summaries etc. mUseCustomLoc = (SwitchPreference) findPreference(Constants.WEATHER_USE_CUSTOM_LOCATION); - mCustomWeatherLoc = (EditTextPreference) findPreference( - Constants.WEATHER_CUSTOM_LOCATION_CITY); + mCustomWeatherLoc = (EditTextPreference) findPreference(Constants.WEATHER_CUSTOM_LOCATION_CITY); mIconSet = (IconSelectionPreference) findPreference(Constants.WEATHER_ICONS); mUseMetric = (SwitchPreference) findPreference(Constants.WEATHER_USE_METRIC); - mUseCustomlocation = (SwitchPreference) findPreference( - Constants.WEATHER_USE_CUSTOM_LOCATION); + mUseCustomlocation = (SwitchPreference) findPreference(Constants.WEATHER_USE_CUSTOM_LOCATION); mWeatherSource = (PreferenceScreen) findPreference(Constants.WEATHER_SOURCE); mWeatherSource.setOnPreferenceChangeListener((preference, o) -> { if (Preferences.getWeatherSource(mContext) != null) { @@ -74,11 +70,11 @@ public class WeatherPreferences extends PreferenceActivity implements Preferences.setUseMetricUnits(mContext, defValue); mUseMetric.setChecked(defValue); - if(!mUseCustomLoc.isChecked()){ + if (!mUseCustomLoc.isChecked()) { if (!hasLocationPermission(this)) { String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION}; requestPermissions(permissions, LOCATION_PERMISSION_REQUEST_CODE); - }else{ + } else { LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { showDialog(); @@ -91,8 +87,7 @@ public class WeatherPreferences extends PreferenceActivity implements public void onResume() { super.onResume(); - getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener( - this); + getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); if (mPostResumeRunnable != null) { mPostResumeRunnable.run(); @@ -112,8 +107,7 @@ public class WeatherPreferences extends PreferenceActivity implements @Override public void onPause() { super.onPause(); - getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener( - this); + getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); final CMWeatherManager weatherManager = CMWeatherManager.getInstance(mContext); weatherManager.unregisterWeatherServiceProviderChangeListener(this); } @@ -121,10 +115,10 @@ public class WeatherPreferences extends PreferenceActivity implements @Override public void onDestroy() { super.onDestroy(); - if (mUseCustomlocation.isChecked() - && Preferences.getCustomWeatherLocationCity(mContext) == null) { - //The user decided to toggle the custom location switch, but forgot to set a custom - //location, we need to go back to geo location + if (mUseCustomlocation.isChecked() && Preferences.getCustomWeatherLocationCity(mContext) == null) { + // The user decided to toggle the custom location switch, but forgot to set a + // custom + // location, we need to go back to geo location Preferences.setUseCustomWeatherLocation(mContext, false); } } @@ -155,8 +149,10 @@ public class WeatherPreferences extends PreferenceActivity implements } if (TextUtils.equals(key, Constants.WEATHER_SOURCE)) { - // The weather source changed, invalidate the custom location settings and change - // back to GeoLocation to force the user to specify a new custom location if needed + // The weather source changed, invalidate the custom location settings and + // change + // back to GeoLocation to force the user to specify a new custom location if + // needed Preferences.setCustomWeatherLocationCity(mContext, null); Preferences.setCustomWeatherLocation(mContext, null); Preferences.setUseCustomWeatherLocation(mContext, false); @@ -165,8 +161,8 @@ public class WeatherPreferences extends PreferenceActivity implements } if (key.equals(Constants.WEATHER_USE_CUSTOM_LOCATION)) { - if (!mUseCustomLoc.isChecked() || (mUseCustomLoc.isChecked() && - Preferences.getCustomWeatherLocation(mContext) != null)) { + if (!mUseCustomLoc.isChecked() + || (mUseCustomLoc.isChecked() && Preferences.getCustomWeatherLocation(mContext) != null)) { forceWeatherUpdate = true; } } @@ -187,8 +183,8 @@ public class WeatherPreferences extends PreferenceActivity implements } if (Constants.DEBUG) { - Log.v(TAG, "Preference " + key + " changed, need update " + - needWeatherUpdate + " force update " + forceWeatherUpdate); + Log.v(TAG, "Preference " + key + " changed, need update " + needWeatherUpdate + " force update " + + forceWeatherUpdate); } if ((needWeatherUpdate || forceWeatherUpdate)) { @@ -201,13 +197,13 @@ public class WeatherPreferences extends PreferenceActivity implements } public static boolean hasLocationPermission(Context context) { - return context.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) - == PackageManager.PERMISSION_GRANTED; + return context + .checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED; } - //=============================================================================================== + // =============================================================================================== // Utility classes and supporting methods - //=============================================================================================== + // =============================================================================================== private void updateLocationSummary() { if (mUseCustomLoc.isChecked()) { @@ -233,13 +229,11 @@ public class WeatherPreferences extends PreferenceActivity implements builder.setTitle(R.string.weather_retrieve_location_dialog_title); builder.setMessage(R.string.weather_retrieve_location_dialog_message); builder.setCancelable(false); - builder.setPositiveButton(R.string.weather_retrieve_location_dialog_enable_button, - (dialog1, whichButton) -> { - Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); - intent.setFlags( - Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); - startActivityForResult(intent, 203); - }); + builder.setPositiveButton(R.string.weather_retrieve_location_dialog_enable_button, (dialog1, whichButton) -> { + Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); + startActivityForResult(intent, 203); + }); builder.setNegativeButton(R.string.cancel, null); dialog = builder.create(); dialog.show(); @@ -250,8 +244,7 @@ public class WeatherPreferences extends PreferenceActivity implements if (requestCode == 203) { LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { - Toast.makeText(this, "Set custom location in weather wettings.", - Toast.LENGTH_SHORT).show(); + Toast.makeText(this, "Set custom location in weather wettings.", Toast.LENGTH_SHORT).show(); } else { startService(new Intent(this, WeatherUpdateService.class) .putExtra(WeatherUpdateService.ACTION_FORCE_UPDATE, true)); @@ -271,8 +264,7 @@ public class WeatherPreferences extends PreferenceActivity implements public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) { - if (grantResults.length > 0 - && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // We only get here if user tried to enable the preference, // hence safe to turn it on after permission is granted LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); diff --git a/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/WeatherSourceListenerService.java b/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/WeatherSourceListenerService.java index 11a142df0f6cdcba2fd4e71caaed41b298694056..8c86fe8a808759f2e8bc0f68dd2d60494d05771b 100644 --- a/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/WeatherSourceListenerService.java +++ b/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/WeatherSourceListenerService.java @@ -5,13 +5,13 @@ import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.util.Log; - import cyanogenmod.weather.CMWeatherManager; import foundation.e.blisslauncher.core.Preferences; import foundation.e.blisslauncher.core.utils.Constants; public class WeatherSourceListenerService extends Service - implements CMWeatherManager.WeatherServiceProviderChangeListener { + implements + CMWeatherManager.WeatherServiceProviderChangeListener { private static final String TAG = WeatherSourceListenerService.class.getSimpleName(); private static final boolean D = Constants.DEBUG; @@ -20,16 +20,20 @@ public class WeatherSourceListenerService extends Service @Override public void onWeatherServiceProviderChanged(String providerLabel) { - if (D) Log.d(TAG, "Weather Source changed " + providerLabel); + if (D) + Log.d(TAG, "Weather Source changed " + providerLabel); Preferences.setWeatherSource(mContext, providerLabel); Preferences.setCachedWeatherInfo(mContext, 0, null); - //The data contained in WeatherLocation is tightly coupled to the weather provider - //that generated that data, so we need to clear the cached weather location and let the new - //weather provider regenerate the data if the user decides to use custom location again + // The data contained in WeatherLocation is tightly coupled to the weather + // provider + // that generated that data, so we need to clear the cached weather location and + // let the new + // weather provider regenerate the data if the user decides to use custom + // location again Preferences.setCustomWeatherLocationCity(mContext, null); Preferences.setCustomWeatherLocation(mContext, null); Preferences.setUseCustomWeatherLocation(mContext, false); - + if (providerLabel != null) { mContext.startService(new Intent(mContext, WeatherUpdateService.class) .putExtra(WeatherUpdateService.ACTION_FORCE_UPDATE, true)); @@ -39,11 +43,11 @@ public class WeatherSourceListenerService extends Service @Override public void onCreate() { mContext = getApplicationContext(); - final CMWeatherManager weatherManager - = CMWeatherManager.getInstance(mContext); + final CMWeatherManager weatherManager = CMWeatherManager.getInstance(mContext); weatherManager.registerWeatherServiceProviderChangeListener(this); mRegistered = true; - if (D) Log.d(TAG, "Listener registered"); + if (D) + Log.d(TAG, "Listener registered"); } @Override diff --git a/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/WeatherUpdateService.java b/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/WeatherUpdateService.java index 92445be07d5ecb1f9e667fbbf64bdcb73e349352..28b453cfd58ec01a4905fd43c1a22a7cee09f2fc 100644 --- a/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/WeatherUpdateService.java +++ b/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/WeatherUpdateService.java @@ -25,12 +25,7 @@ import android.os.SystemClock; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; - import androidx.localbroadcastmanager.content.LocalBroadcastManager; - -import java.lang.ref.WeakReference; -import java.util.Date; - import cyanogenmod.weather.CMWeatherManager; import cyanogenmod.weather.WeatherInfo; import cyanogenmod.weather.WeatherLocation; @@ -38,23 +33,21 @@ import foundation.e.blisslauncher.R; import foundation.e.blisslauncher.core.Preferences; import foundation.e.blisslauncher.core.utils.Constants; import foundation.e.blisslauncher.core.utils.PackageManagerUtils; +import java.lang.ref.WeakReference; +import java.util.Date; public class WeatherUpdateService extends Service { private static final String TAG = "WeatherUpdateService"; private static final boolean D = Constants.DEBUG; - public static final String ACTION_FORCE_UPDATE = - "org.indin.blisslauncher.action.FORCE_WEATHER_UPDATE"; - private static final String ACTION_CANCEL_LOCATION_UPDATE = - "org.indin.blisslauncher.action.CANCEL_LOCATION_UPDATE"; + public static final String ACTION_FORCE_UPDATE = "org.indin.blisslauncher.action.FORCE_WEATHER_UPDATE"; + private static final String ACTION_CANCEL_LOCATION_UPDATE = "org.indin.blisslauncher.action.CANCEL_LOCATION_UPDATE"; - private static final String ACTION_CANCEL_UPDATE_WEATHER_REQUEST = - "org.indin.blisslauncher.action.CANCEL_UPDATE_WEATHER_REQUEST"; + private static final String ACTION_CANCEL_UPDATE_WEATHER_REQUEST = "org.indin.blisslauncher.action.CANCEL_UPDATE_WEATHER_REQUEST"; private static final long WEATHER_UPDATE_REQUEST_TIMEOUT_MS = 300L * 1000L; // Broadcast action for end of update - public static final String ACTION_UPDATE_FINISHED = - "org.indin.blisslauncher.action.WEATHER_UPDATE_FINISHED"; + public static final String ACTION_UPDATE_FINISHED = "org.indin.blisslauncher.action.WEATHER_UPDATE_FINISHED"; public static final String EXTRA_UPDATE_CANCELLED = "update_cancelled"; private static final long LOCATION_REQUEST_TIMEOUT = 5L * 60L * 1000L; @@ -85,7 +78,8 @@ public class WeatherUpdateService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { - if (D) Log.v(TAG, "Got intent " + intent); + if (D) + Log.v(TAG, "Got intent " + intent); if (ACTION_CANCEL_LOCATION_UPDATE.equals(intent.getAction())) { WeatherLocationListener.cancel(this); @@ -97,17 +91,12 @@ public class WeatherUpdateService extends Service { if (ACTION_CANCEL_UPDATE_WEATHER_REQUEST.equals(intent.getAction())) { if (mWorkerThread.isProcessing()) { - mWorkerThread.getHandler().obtainMessage( - WorkerThread.MSG_CANCEL_UPDATE_WEATHER_REQUEST).sendToTarget(); + mWorkerThread.getHandler().obtainMessage(WorkerThread.MSG_CANCEL_UPDATE_WEATHER_REQUEST).sendToTarget(); mHandler.post(() -> { final Context context = getApplicationContext(); - final CMWeatherManager weatherManager - = CMWeatherManager.getInstance(context); - final String activeProviderLabel - = weatherManager.getActiveWeatherServiceProviderLabel(); - final String noData - = getString(R.string.weather_cannot_reach_provider, - activeProviderLabel); + final CMWeatherManager weatherManager = CMWeatherManager.getInstance(context); + final String activeProviderLabel = weatherManager.getActiveWeatherServiceProviderLabel(); + final String noData = getString(R.string.weather_cannot_reach_provider, activeProviderLabel); Toast.makeText(context, noData, Toast.LENGTH_SHORT).show(); }); } @@ -123,65 +112,66 @@ public class WeatherUpdateService extends Service { return START_NOT_STICKY; } - mWorkerThread.getHandler().obtainMessage(WorkerThread.MSG_ON_NEW_WEATHER_REQUEST) - .sendToTarget(); + mWorkerThread.getHandler().obtainMessage(WorkerThread.MSG_ON_NEW_WEATHER_REQUEST).sendToTarget(); return START_REDELIVER_INTENT; } private boolean shouldUpdate(boolean force) { - final CMWeatherManager weatherManager - = CMWeatherManager.getInstance(getApplicationContext()); + final CMWeatherManager weatherManager = CMWeatherManager.getInstance(getApplicationContext()); if (weatherManager.getActiveWeatherServiceProviderLabel() == null) { - //Why bother if we don't even have an active provider - if (D) Log.d(TAG, "No active weather service provider found, skip"); + // Why bother if we don't even have an active provider + if (D) + Log.d(TAG, "No active weather service provider found, skip"); return false; } final long interval = Preferences.weatherRefreshIntervalInMs(this); if (interval == 0 && !force) { - if (D) Log.v(TAG, "Interval set to manual and update not forced, skip"); + if (D) + Log.v(TAG, "Interval set to manual and update not forced, skip"); return false; } if (!WeatherPreferences.hasLocationPermission(this)) { - if (D) Log.v(TAG, "Application does not have the location permission, skip"); + if (D) + Log.v(TAG, "Application does not have the location permission, skip"); return false; } - - ConnectivityManager cm = (ConnectivityManager) getSystemService( - Context.CONNECTIVITY_SERVICE); + ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); if (info == null || !info.isConnected() || !info.isAvailable()) { - if (D) Log.d(TAG, "Network is not available, skip"); + if (D) + Log.d(TAG, "Network is not available, skip"); return false; } else { if (force) { - if (D) Log.d(TAG, "Forcing weather update"); + if (D) + Log.d(TAG, "Forcing weather update"); return true; } else { final long now = SystemClock.elapsedRealtime(); final long lastUpdate = Preferences.lastWeatherUpdateTimestamp(this); final long due = lastUpdate + interval; if (D) { - Log.d(TAG, "Now " + now + " Last update " + lastUpdate - + " interval " + interval); + Log.d(TAG, "Now " + now + " Last update " + lastUpdate + " interval " + interval); } if (lastUpdate == 0 || due - now < 0) { - if (D) Log.d(TAG, "Should update"); + if (D) + Log.d(TAG, "Should update"); return true; } else { - if (D) Log.v(TAG, "Next weather update due in " + (due - now) + " ms, skip"); + if (D) + Log.v(TAG, "Next weather update due in " + (due - now) + " ms, skip"); return false; } } } } - private class WorkerThread extends HandlerThread - implements CMWeatherManager.WeatherUpdateRequestListener { + private class WorkerThread extends HandlerThread implements CMWeatherManager.WeatherUpdateRequestListener { public static final int MSG_ON_NEW_WEATHER_REQUEST = 1; public static final int MSG_ON_WEATHER_REQUEST_COMPLETED = 2; @@ -194,7 +184,7 @@ public class WeatherUpdateService extends Service { private PendingIntent mTimeoutPendingIntent; private int mRequestId; private final CMWeatherManager mWeatherManager; - final private Context mContext; + private final Context mContext; public WorkerThread(Context context) { super("weather-service-worker"); @@ -206,24 +196,25 @@ public class WeatherUpdateService extends Service { mHandler = new Handler(getLooper()) { @Override public void handleMessage(Message msg) { - if (D) Log.d(TAG, "Msg " + msg.what); + if (D) + Log.d(TAG, "Msg " + msg.what); switch (msg.what) { - case MSG_ON_NEW_WEATHER_REQUEST: + case MSG_ON_NEW_WEATHER_REQUEST : onNewWeatherRequest(); break; - case MSG_ON_WEATHER_REQUEST_COMPLETED: + case MSG_ON_WEATHER_REQUEST_COMPLETED : WeatherInfo info = (WeatherInfo) msg.obj; onWeatherRequestCompleted(info); break; - case MSG_WEATHER_REQUEST_FAILED: + case MSG_WEATHER_REQUEST_FAILED : int status = msg.arg1; onWeatherRequestFailed(status); break; - case MSG_CANCEL_UPDATE_WEATHER_REQUEST: + case MSG_CANCEL_UPDATE_WEATHER_REQUEST : onCancelUpdateWeatherRequest(); break; - default: - //Unknown message, pass it on... + default : + // Unknown message, pass it on... super.handleMessage(msg); } } @@ -240,7 +231,8 @@ public class WeatherUpdateService extends Service { AlarmManager am = (AlarmManager) mContext.getSystemService(ALARM_SERVICE); long elapseTime = SystemClock.elapsedRealtime() + WEATHER_UPDATE_REQUEST_TIMEOUT_MS; am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, elapseTime, mTimeoutPendingIntent); - if (D) Log.v(TAG, "Timeout alarm set to expire in " + elapseTime + " ms"); + if (D) + Log.v(TAG, "Timeout alarm set to expire in " + elapseTime + " ms"); } private void cancelTimeoutAlarm() { @@ -249,7 +241,8 @@ public class WeatherUpdateService extends Service { AlarmManager am = (AlarmManager) mContext.getSystemService(ALARM_SERVICE); am.cancel(mTimeoutPendingIntent); mTimeoutPendingIntent = null; - if (D) Log.v(TAG, "Timeout alarm cancelled"); + if (D) + Log.v(TAG, "Timeout alarm cancelled"); } } @@ -265,12 +258,11 @@ public class WeatherUpdateService extends Service { } mIsProcessingWeatherUpdate = true; - final PowerManager pm - = (PowerManager) mContext.getSystemService(POWER_SERVICE); - mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, - "blisslauncher:WeatherUpdateService"); + final PowerManager pm = (PowerManager) mContext.getSystemService(POWER_SERVICE); + mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "blisslauncher:WeatherUpdateService"); mWakeLock.setReferenceCounted(false); - if (D) Log.v(TAG, "ACQUIRING WAKELOCK"); + if (D) + Log.v(TAG, "ACQUIRING WAKELOCK"); mWakeLock.acquire(); WeatherLocation customWeatherLocation = null; @@ -279,34 +271,37 @@ public class WeatherUpdateService extends Service { } if (customWeatherLocation != null) { mRequestId = mWeatherManager.requestWeatherUpdate(customWeatherLocation, this); - if (D) Log.d(TAG, "Request submitted using WeatherLocation"); + if (D) + Log.d(TAG, "Request submitted using WeatherLocation"); startTimeoutAlarm(); } else { final Location location = getCurrentLocation(); if (location != null) { mRequestId = mWeatherManager.requestWeatherUpdate(location, this); - if (D) Log.d(TAG, "Request submitted using Location"); + if (D) + Log.d(TAG, "Request submitted using Location"); startTimeoutAlarm(); } else { // work with cached location from last request for now // a listener to update it is already scheduled if possible WeatherInfo cachedInfo = Preferences.getCachedWeatherInfo(mContext); if (cachedInfo != null) { - mHandler.obtainMessage(MSG_ON_WEATHER_REQUEST_COMPLETED, - cachedInfo).sendToTarget(); - if (D) Log.d(TAG, "Returning cached weather data [ " - + cachedInfo.toString() + " ]"); + mHandler.obtainMessage(MSG_ON_WEATHER_REQUEST_COMPLETED, cachedInfo).sendToTarget(); + if (D) + Log.d(TAG, "Returning cached weather data [ " + cachedInfo.toString() + " ]"); } else { - mHandler.obtainMessage(MSG_WEATHER_REQUEST_FAILED, - CMWeatherManager.RequestStatus.FAILED, 0).sendToTarget(); + mHandler.obtainMessage(MSG_WEATHER_REQUEST_FAILED, CMWeatherManager.RequestStatus.FAILED, 0) + .sendToTarget(); } } } } public void tearDown() { - if (D) Log.d(TAG, "Tearing down worker thread"); - if (isProcessing()) mWeatherManager.cancelRequest(mRequestId); + if (D) + Log.d(TAG, "Tearing down worker thread"); + if (isProcessing()) + mWeatherManager.cancelRequest(mRequestId); quit(); } @@ -315,31 +310,34 @@ public class WeatherUpdateService extends Service { } private Location getCurrentLocation() { - final LocationManager lm - = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); + final LocationManager lm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); Location location = null; - try{ + try { location = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); - }catch (SecurityException e){ + } catch (SecurityException e) { e.printStackTrace(); } - if (D) Log.v(TAG, "Current location is " + location); + if (D) + Log.v(TAG, "Current location is " + location); if (location != null && location.getAccuracy() > LOCATION_ACCURACY_THRESHOLD_METERS) { - if (D) Log.d(TAG, "Ignoring inaccurate location"); + if (D) + Log.d(TAG, "Ignoring inaccurate location"); location = null; } // If lastKnownLocation is not present (because none of the apps in the // device has requested the current location to the system yet) or outdated, - // then try to get the current location use the provider that best matches the criteria. + // then try to get the current location use the provider that best matches the + // criteria. boolean needsUpdate = location == null; if (location != null) { long delta = System.currentTimeMillis() - location.getTime(); needsUpdate = delta > OUTDATED_LOCATION_THRESHOLD_MILLIS; } if (needsUpdate) { - if (D) Log.d(TAG, "Getting best location provider"); + if (D) + Log.d(TAG, "Getting best location provider"); String locationProvider = lm.getBestProvider(sLocationCriteria, true); if (TextUtils.isEmpty(locationProvider)) { Log.e(TAG, "No available location providers matching criteria."); @@ -369,23 +367,26 @@ public class WeatherUpdateService extends Service { } private void onWeatherRequestFailed(int status) { - if (D) Log.d(TAG, "Weather refresh failed ["+status+"]"); + if (D) + Log.d(TAG, "Weather refresh failed [" + status + "]"); cancelTimeoutAlarm(); if (status == CMWeatherManager.RequestStatus.ALREADY_IN_PROGRESS) { - if (D) Log.d(TAG, "A request is already in progress, no need to schedule again"); + if (D) + Log.d(TAG, "A request is already in progress, no need to schedule again"); } else if (status == CMWeatherManager.RequestStatus.FAILED) { - //Something went wrong, let's schedule an update at the next interval from now - //A force update might happen earlier anyway + // Something went wrong, let's schedule an update at the next interval from now + // A force update might happen earlier anyway scheduleUpdate(mContext, Preferences.weatherRefreshIntervalInMs(mContext), false); } else { - //Wait until the next update is due + // Wait until the next update is due scheduleNextUpdate(mContext, false); } broadcastAndCleanUp(true); } private void onCancelUpdateWeatherRequest() { - if (D) Log.d(TAG, "Cancelling active weather request"); + if (D) + Log.d(TAG, "Cancelling active weather request"); if (mIsProcessingWeatherUpdate) { cancelTimeoutAlarm(); mWeatherManager.cancelRequest(mRequestId); @@ -398,7 +399,8 @@ public class WeatherUpdateService extends Service { finishedIntent.putExtra(EXTRA_UPDATE_CANCELLED, updateCancelled); mContext.sendBroadcast(finishedIntent); - if (D) Log.d(TAG, "RELEASING WAKELOCK"); + if (D) + Log.d(TAG, "RELEASING WAKELOCK"); mWakeLock.release(); mIsProcessingWeatherUpdate = false; mContext.stopService(new Intent(mContext, WeatherUpdateService.class)); @@ -407,11 +409,9 @@ public class WeatherUpdateService extends Service { @Override public void onWeatherRequestCompleted(int state, WeatherInfo weatherInfo) { if (state == CMWeatherManager.RequestStatus.COMPLETED) { - mHandler.obtainMessage(WorkerThread.MSG_ON_WEATHER_REQUEST_COMPLETED, weatherInfo) - .sendToTarget(); + mHandler.obtainMessage(WorkerThread.MSG_ON_WEATHER_REQUEST_COMPLETED, weatherInfo).sendToTarget(); } else { - mHandler.obtainMessage(WorkerThread.MSG_WEATHER_REQUEST_FAILED, state, 0) - .sendToTarget(); + mHandler.obtainMessage(WorkerThread.MSG_WEATHER_REQUEST_FAILED, state, 0).sendToTarget(); } } } @@ -441,11 +441,12 @@ public class WeatherUpdateService extends Service { @SuppressLint("MissingPermission") static void registerIfNeeded(Context context, String provider) { synchronized (WeatherLocationListener.class) { - if (D) Log.d(TAG, "Registering location listener"); + if (D) + Log.d(TAG, "Registering location listener"); if (sInstance == null) { final Context appContext = context.getApplicationContext(); - final LocationManager locationManager = - (LocationManager) appContext.getSystemService(Context.LOCATION_SERVICE); + final LocationManager locationManager = (LocationManager) appContext + .getSystemService(Context.LOCATION_SERVICE); // Check location provider after set sInstance, so, if the provider is not // supported, we never enter here again. @@ -456,9 +457,9 @@ public class WeatherUpdateService extends Service { // change this if this call receive different providers LocationProvider lp = locationManager.getProvider(provider); if (lp != null) { - if (D) Log.d(TAG, "LocationManager - Requesting single update"); - locationManager.requestSingleUpdate(provider, sInstance, - appContext.getMainLooper()); + if (D) + Log.d(TAG, "LocationManager - Requesting single update"); + locationManager.requestSingleUpdate(provider, sInstance, appContext.getMainLooper()); sInstance.setTimeoutAlarm(); } } @@ -469,9 +470,10 @@ public class WeatherUpdateService extends Service { synchronized (WeatherLocationListener.class) { if (sInstance != null) { final Context appContext = context.getApplicationContext(); - final LocationManager locationManager = - (LocationManager) appContext.getSystemService(Context.LOCATION_SERVICE); - if (D) Log.d(TAG, "Aborting location request after timeout"); + final LocationManager locationManager = (LocationManager) appContext + .getSystemService(Context.LOCATION_SERVICE); + if (D) + Log.d(TAG, "Aborting location request after timeout"); locationManager.removeUpdates(sInstance); sInstance.cancelTimeoutAlarm(); sInstance = null; @@ -508,7 +510,8 @@ public class WeatherUpdateService extends Service { @Override public void onLocationChanged(Location location) { // Now, we have a location to use. Schedule a weather update right now. - if (D) Log.d(TAG, "The location has changed, schedule an update "); + if (D) + Log.d(TAG, "The location has changed, schedule an update "); synchronized (WeatherLocationListener.class) { scheduleUpdate(mContext.get(), 0, true); cancelTimeoutAlarm(); @@ -519,7 +522,8 @@ public class WeatherUpdateService extends Service { @Override public void onStatusChanged(String provider, int status, Bundle extras) { // Now, we have a location to use. Schedule a weather update right now. - if (D) Log.d(TAG, "The location service has become available, schedule an update "); + if (D) + Log.d(TAG, "The location service has become available, schedule an update "); if (status == LocationProvider.AVAILABLE) { synchronized (WeatherLocationListener.class) { scheduleUpdate(mContext.get(), 0, true); @@ -543,22 +547,25 @@ public class WeatherUpdateService extends Service { private static void scheduleUpdate(Context context, long millisFromNow, boolean force) { AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); long due = SystemClock.elapsedRealtime() + millisFromNow; - if (D) Log.d(TAG, "Next update scheduled at " - + new Date(System.currentTimeMillis() + millisFromNow)); + if (D) + Log.d(TAG, "Next update scheduled at " + new Date(System.currentTimeMillis() + millisFromNow)); am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, due, getUpdateIntent(context, force)); } public static void scheduleNextUpdate(Context context, boolean force) { if (force) { - if (D) Log.d(TAG, "Scheduling next update immediately"); + if (D) + Log.d(TAG, "Scheduling next update immediately"); scheduleUpdate(context, 0, true); } else { final long lastUpdate = Preferences.lastWeatherUpdateTimestamp(context); final long interval = Preferences.weatherRefreshIntervalInMs(context); final long now = SystemClock.elapsedRealtime(); long due = (interval + lastUpdate) - now; - if (due < 0) due = 0; - if (D) Log.d(TAG, "Scheduling in " + due + " ms"); + if (due < 0) + due = 0; + if (D) + Log.d(TAG, "Scheduling in " + due + " ms"); scheduleUpdate(context, due, false); } } diff --git a/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/WeatherUtils.java b/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/WeatherUtils.java index e61eaafef0f82e4f5ac31ac379f5e7b5e45aad9a..0b5f5a252d02d4cf5673247dacd431199699e0ee 100644 --- a/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/WeatherUtils.java +++ b/app/src/apiNougat/java/foundation/e/blisslauncher/features/weather/WeatherUtils.java @@ -2,12 +2,10 @@ package foundation.e.blisslauncher.features.weather; import android.content.Context; import android.content.res.Resources; - -import java.text.DecimalFormat; - import cyanogenmod.app.CMContextConstants; import cyanogenmod.providers.WeatherContract; import foundation.e.blisslauncher.R; +import java.text.DecimalFormat; public final class WeatherUtils { @@ -28,8 +26,11 @@ public final class WeatherUtils { /** * Returns a localized string of the wind direction - * @param context Application context to access resources - * @param windDirection The wind direction in degrees + * + * @param context + * Application context to access resources + * @param windDirection + * The wind direction in degrees * @return The wind direction in string format */ public static String resolveWindDirection(Context context, double windDirection) { @@ -62,14 +63,18 @@ public final class WeatherUtils { /** * Returns the resource name associated to the supplied weather condition code - * @param context Application context to access resources - * @param conditionCode The weather condition code - * @return The resource name if a valid condition code is passed, empty string otherwise + * + * @param context + * Application context to access resources + * @param conditionCode + * The weather condition code + * @return The resource name if a valid condition code is passed, empty string + * otherwise */ public static String resolveWeatherCondition(Context context, int conditionCode) { final Resources res = context.getResources(); - final int resId = res.getIdentifier("weather_" - + WeatherUtils.addOffsetToConditionCodeFromWeatherContract(conditionCode), "string", + final int resId = res.getIdentifier( + "weather_" + WeatherUtils.addOffsetToConditionCodeFromWeatherContract(conditionCode), "string", context.getPackageName()); if (resId != 0) { return res.getString(resId); @@ -89,10 +94,13 @@ public final class WeatherUtils { } /** - * Returns a string with the format xx% (where xx is the humidity value provided) - * @param humidity The humidity value - * @return The formatted string if a valid value is provided, "-" otherwise. Decimals are - * removed + * Returns a string with the format xx% (where xx is the humidity value + * provided) + * + * @param humidity + * The humidity value + * @return The formatted string if a valid value is provided, "-" otherwise. + * Decimals are removed */ public static String formatHumidity(double humidity) { return getFormattedValue(humidity, "%"); @@ -100,12 +108,16 @@ public final class WeatherUtils { /** * Returns a localized string of the speed and speed unit - * @param context Application context to access resources - * @param windSpeed The wind speed - * @param windSpeedUnit The speed unit. See - * {@link lineageos.providers.WeatherContract.WeatherColumns.WindSpeedUnit} + * + * @param context + * Application context to access resources + * @param windSpeed + * The wind speed + * @param windSpeedUnit + * The speed unit. See + * {@link lineageos.providers.WeatherContract.WeatherColumns.WindSpeedUnit} * @return The formatted string if a valid speed and speed unit a provided. - * {@link R.string#unknown} otherwise + * {@link R.string#unknown} otherwise */ public static String formatWindSpeed(Context context, double windSpeed, int windSpeedUnit) { if (windSpeed < 0) { @@ -114,13 +126,13 @@ public final class WeatherUtils { String localizedSpeedUnit; switch (windSpeedUnit) { - case WeatherContract.WeatherColumns.WindSpeedUnit.MPH: + case WeatherContract.WeatherColumns.WindSpeedUnit.MPH : localizedSpeedUnit = context.getString(R.string.weather_mph); break; - case WeatherContract.WeatherColumns.WindSpeedUnit.KPH: + case WeatherContract.WeatherColumns.WindSpeedUnit.KPH : localizedSpeedUnit = context.getString(R.string.weather_kph); break; - default: + default : return context.getString(R.string.unknown); } return getFormattedValue(windSpeed, localizedSpeedUnit); @@ -128,7 +140,9 @@ public final class WeatherUtils { /** * Helper method to convert miles to kilometers - * @param miles The value in miles + * + * @param miles + * The value in miles * @return The value in kilometers */ public static double milesToKilometers(double miles) { @@ -137,7 +151,9 @@ public final class WeatherUtils { /** * Helper method to convert kilometers to miles - * @param km The value in kilometers + * + * @param km + * The value in kilometers * @return The value in miles */ public static double kilometersToMiles(double km) { @@ -145,8 +161,11 @@ public final class WeatherUtils { } /** - * Adds an offset to the condition code reported by the active weather service provider. - * @param conditionCode The condition code from the Weather API + * Adds an offset to the condition code reported by the active weather service + * provider. + * + * @param conditionCode + * The condition code from the Weather API * @return A condition code that correctly maps to our resource IDs */ public static int addOffsetToConditionCodeFromWeatherContract(int conditionCode) { @@ -165,7 +184,9 @@ public final class WeatherUtils { /** * Checks if the Lineage Weather service is available in this device - * @param context Context to be used + * + * @param context + * Context to be used * @return true if service is available, false otherwise */ public static boolean isWeatherServiceAvailable(Context context) { diff --git a/app/src/apiOreo/java/foundation/e/blisslauncher/core/Preferences.java b/app/src/apiOreo/java/foundation/e/blisslauncher/core/Preferences.java index 7c605db26a3ab075ad9d7ddf48a5caaf53bda85c..0d57cdac21dc45172e268e110c5fef827b6728d1 100644 --- a/app/src/apiOreo/java/foundation/e/blisslauncher/core/Preferences.java +++ b/app/src/apiOreo/java/foundation/e/blisslauncher/core/Preferences.java @@ -3,24 +3,20 @@ package foundation.e.blisslauncher.core; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Color; - -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - +import foundation.e.blisslauncher.core.utils.Constants; import java.util.ArrayList; import java.util.Locale; - -import foundation.e.blisslauncher.core.utils.Constants; import lineageos.weather.WeatherInfo; import lineageos.weather.WeatherLocation; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; public class Preferences { - /** - * Weather related keys and constants. - */ + /** Weather related keys and constants. */ private static final String WEATHER_LOCATION_CITY_ID = "city_id"; + private static final String WEATHER_LOCATION_CITY_NAME = "city_name"; private static final String WEATHER_LOCATION_STATE = "state"; private static final String WEATHER_LOCATION_POSTAL_CODE = "postal_code"; @@ -64,8 +60,8 @@ public class Preferences { } public static int weatherFontColor(Context context) { - int color = Color.parseColor(getPrefs(context).getString(Constants.WEATHER_FONT_COLOR, - Constants.DEFAULT_LIGHT_COLOR)); + int color = Color + .parseColor(getPrefs(context).getString(Constants.WEATHER_FONT_COLOR, Constants.DEFAULT_LIGHT_COLOR)); return color; } @@ -75,8 +71,7 @@ public class Preferences { public static boolean useMetricUnits(Context context) { Locale locale = context.getResources().getConfiguration().locale; - boolean defValue = !(locale.equals(Locale.US) - || locale.toString().equals("ms_MY") // Malaysia + boolean defValue = !(locale.equals(Locale.US) || locale.toString().equals("ms_MY") // Malaysia || locale.toString().equals("si_LK") // Sri Lanka ); return getPrefs(context).getBoolean(Constants.WEATHER_USE_METRIC, defValue); @@ -107,17 +102,14 @@ public class Preferences { getPrefs(context).edit().putString(Constants.WEATHER_CUSTOM_LOCATION_CITY, city).apply(); } - public static boolean setCustomWeatherLocation(Context context, - WeatherLocation weatherLocation) { + public static boolean setCustomWeatherLocation(Context context, WeatherLocation weatherLocation) { if (weatherLocation == null) { - getPrefs(context).edit() - .remove(Constants.WEATHER_CUSTOM_LOCATION).apply(); + getPrefs(context).edit().remove(Constants.WEATHER_CUSTOM_LOCATION).apply(); return true; } try { JSONObject jsonObject = weatherLocationToJSON(weatherLocation); - getPrefs(context).edit() - .putString(Constants.WEATHER_CUSTOM_LOCATION, jsonObject.toString()).apply(); + getPrefs(context).edit().putString(Constants.WEATHER_CUSTOM_LOCATION, jsonObject.toString()).apply(); return true; } catch (JSONException e) { // We're here because weatherLocationToJSON() or jsonObject.toString() failed. @@ -127,8 +119,7 @@ public class Preferences { } public static WeatherLocation getCustomWeatherLocation(Context context) { - String weatherLocation = getPrefs(context) - .getString(Constants.WEATHER_CUSTOM_LOCATION, null); + String weatherLocation = getPrefs(context).getString(Constants.WEATHER_CUSTOM_LOCATION, null); if (weatherLocation == null) { return null; @@ -142,8 +133,7 @@ public class Preferences { } } - private static WeatherLocation JSONToWeatherLocation(JSONObject jsonObject) - throws JSONException { + private static WeatherLocation JSONToWeatherLocation(JSONObject jsonObject) throws JSONException { String cityId; String cityName; String state; @@ -158,25 +148,27 @@ public class Preferences { countryId = jsonObject.getString(WEATHER_LOCATION_COUNTRY_ID); countryName = jsonObject.getString(WEATHER_LOCATION_COUNTRY_NAME); - //We need at least city id and city name to build a WeatherLocation + // We need at least city id and city name to build a WeatherLocation if (cityId == null && cityName == null) { return null; } WeatherLocation.Builder location = new WeatherLocation.Builder(cityId, cityName); - if (countryId != null) location.setCountryId(countryId); - if (countryName != null) location.setCountry(countryName); - if (state != null) location.setState(state); - if (postalCode != null) location.setPostalCode(postalCode); + if (countryId != null) + location.setCountryId(countryId); + if (countryName != null) + location.setCountry(countryName); + if (state != null) + location.setState(state); + if (postalCode != null) + location.setPostalCode(postalCode); return location.build(); } private static JSONObject weatherLocationToJSON(WeatherLocation location) throws JSONException { - return new JSONObject() - .put(WEATHER_LOCATION_CITY_ID, location.getCityId()) - .put(WEATHER_LOCATION_CITY_NAME, location.getCity()) - .put(WEATHER_LOCATION_STATE, location.getState()) + return new JSONObject().put(WEATHER_LOCATION_CITY_ID, location.getCityId()) + .put(WEATHER_LOCATION_CITY_NAME, location.getCity()).put(WEATHER_LOCATION_STATE, location.getState()) .put(WEATHER_LOCATION_POSTAL_CODE, location.getPostalCode()) .put(WEATHER_LOCATION_COUNTRY_ID, location.getCountryId()) .put(WEATHER_LOCATION_COUNTRY_NAME, location.getCountry()); @@ -190,9 +182,8 @@ public class Preferences { JSONObject jsonObject = new JSONObject(); boolean serialized = false; try { - //These members always return a value that can be parsed - jsonObject - .put(WEATHER_INFO_CITY, info.getCity()) + // These members always return a value that can be parsed + jsonObject.put(WEATHER_INFO_CITY, info.getCity()) .put(WEATHER_INFO_CONDITION_CODE, info.getConditionCode()) .put(WEATHER_INFO_TEMPERATURE, info.getTemperature()) .put(WEATHER_INFO_TEMPERATURE_UNIT, info.getTemperatureUnit()) @@ -205,24 +196,21 @@ public class Preferences { jsonObject.put(WEATHER_INFO_HUMIDITY, Double.isNaN(humidity) ? "NaN" : humidity); double todaysHigh = info.getTodaysHigh(); - jsonObject.put(WEATHER_INFO_TODAYS_HIGH, Double.isNaN(todaysHigh) - ? "NaN" : todaysHigh); + jsonObject.put(WEATHER_INFO_TODAYS_HIGH, Double.isNaN(todaysHigh) ? "NaN" : todaysHigh); double todaysLow = info.getTodaysLow(); - jsonObject.put(WEATHER_INFO_TODAYS_LOW, Double.isNaN(todaysLow) - ? "NaN" : todaysLow); + jsonObject.put(WEATHER_INFO_TODAYS_LOW, Double.isNaN(todaysLow) ? "NaN" : todaysLow); double windSpeed = info.getWindSpeed(); double windDirection = info.getWindDirection(); jsonObject.put(WEATHER_INFO_WIND_SPEED, Double.isNaN(windSpeed) ? "NaN" : windSpeed) .put(WEATHER_INFO_WIND_SPEED_UNIT, info.getWindSpeedUnit()) - .put(WEATHER_INFO_WIND_SPEED_DIRECTION, Double.isNaN(windDirection) - ? "NaN" : windDirection); + .put(WEATHER_INFO_WIND_SPEED_DIRECTION, Double.isNaN(windDirection) ? "NaN" : windDirection); JSONArray forecastArray = new JSONArray(); for (WeatherInfo.DayForecast forecast : info.getForecasts()) { - JSONObject jsonForecast = new JSONObject() - .put(DAY_FORECAST_CONDITION_CODE, forecast.getConditionCode()); + JSONObject jsonForecast = new JSONObject().put(DAY_FORECAST_CONDITION_CODE, + forecast.getConditionCode()); double low = forecast.getLow(); jsonForecast.put(DAY_FORECAST_LOW, Double.isNaN(low) ? "NaN" : low); @@ -257,7 +245,8 @@ public class Preferences { public static WeatherInfo getCachedWeatherInfo(Context context) { final String cachedInfo = getPrefs(context).getString(Constants.WEATHER_DATA, null); - if (cachedInfo == null) return null; + if (cachedInfo == null) + return null; String city; int conditionCode; @@ -295,21 +284,26 @@ public class Preferences { high = forecast.getDouble(DAY_FORECAST_HIGH); code = forecast.getInt(DAY_FORECAST_CONDITION_CODE); WeatherInfo.DayForecast.Builder f = new WeatherInfo.DayForecast.Builder(code); - if (!Double.isNaN(low)) f.setLow(low); - if (!Double.isNaN(high)) f.setHigh(high); + if (!Double.isNaN(low)) + f.setLow(low); + if (!Double.isNaN(high)) + f.setHigh(high); forecastList.add(f.build()); } WeatherInfo.Builder weatherInfo = new WeatherInfo.Builder(city, temperature, tempUnit) - .setWeatherCondition(conditionCode) - .setTimestamp(timestamp); + .setWeatherCondition(conditionCode).setTimestamp(timestamp); - if (!Double.isNaN(humidity)) weatherInfo.setHumidity(humidity); + if (!Double.isNaN(humidity)) + weatherInfo.setHumidity(humidity); if (!Double.isNaN(windSpeed) && !Double.isNaN(windDirection)) { weatherInfo.setWind(windSpeed, windDirection, windSpeedUnit); } - if (forecastList.size() > 0) weatherInfo.setForecast(forecastList); - if (!Double.isNaN(todaysHigh)) weatherInfo.setTodaysHigh(todaysHigh); - if (!Double.isNaN(todaysLow)) weatherInfo.setTodaysLow(todaysLow); + if (forecastList.size() > 0) + weatherInfo.setForecast(forecastList); + if (!Double.isNaN(todaysHigh)) + weatherInfo.setTodaysHigh(todaysHigh); + if (!Double.isNaN(todaysLow)) + weatherInfo.setTodaysLow(todaysLow); return weatherInfo.build(); } catch (JSONException e) { } @@ -344,11 +338,11 @@ public class Preferences { getPrefs(context).edit().putBoolean(NOTIFICATION_ACCESS, false).apply(); } - public static int getCurrentMigrationVersion(Context context){ + public static int getCurrentMigrationVersion(Context context) { return getPrefs(context).getInt(CURRENT_MIGRATION_VERSION, 0); } - public static void setCurrentMigrationVersion(Context context, int version){ + public static void setCurrentMigrationVersion(Context context, int version) { getPrefs(context).edit().putInt(CURRENT_MIGRATION_VERSION, version).apply(); } @@ -360,8 +354,7 @@ public class Preferences { getPrefs(context).edit().putBoolean(ENABLE_LOCATION, true).apply(); } - public static boolean getEnableLocation( - Context context) { + public static boolean getEnableLocation(Context context) { return getPrefs(context).getBoolean(ENABLE_LOCATION, false); } diff --git a/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/CustomLocationPreference.java b/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/CustomLocationPreference.java index acabed861621a880f83e45c14f19917a412b8009..e33b04f224ea8aad667103ff22febe1d18508e9d 100644 --- a/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/CustomLocationPreference.java +++ b/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/CustomLocationPreference.java @@ -13,17 +13,16 @@ import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; - -import java.util.HashSet; -import java.util.List; - import foundation.e.blisslauncher.R; import foundation.e.blisslauncher.core.Preferences; +import java.util.HashSet; +import java.util.List; import lineageos.weather.LineageWeatherManager; import lineageos.weather.WeatherLocation; public class CustomLocationPreference extends EditTextPreference - implements LineageWeatherManager.LookupCityRequestListener { + implements + LineageWeatherManager.LookupCityRequestListener { public CustomLocationPreference(Context context) { super(context); } @@ -52,15 +51,14 @@ public class CustomLocationPreference extends EditTextPreference okButton.setOnClickListener(v -> { CustomLocationPreference.this.onClick(d, DialogInterface.BUTTON_POSITIVE); final String customLocationToLookUp = getEditText().getText().toString(); - if (TextUtils.equals(customLocationToLookUp, "")) return; + if (TextUtils.equals(customLocationToLookUp, "")) + return; final LineageWeatherManager weatherManager = LineageWeatherManager.getInstance(getContext()); mProgressDialog = new ProgressDialog(getContext()); mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mProgressDialog.setMessage(getContext().getString(R.string.weather_progress_title)); - mProgressDialog.setOnCancelListener( - dialog -> weatherManager.cancelRequest(mCustomLocationRequestId)); - mCustomLocationRequestId = weatherManager.lookupCity(customLocationToLookUp, - CustomLocationPreference.this); + mProgressDialog.setOnCancelListener(dialog -> weatherManager.cancelRequest(mCustomLocationRequestId)); + mCustomLocationRequestId = weatherManager.lookupCity(customLocationToLookUp, CustomLocationPreference.this); mProgressDialog.show(); }); } @@ -86,14 +84,10 @@ public class CustomLocationPreference extends EditTextPreference private void handleResultDisambiguation(final List results) { CharSequence[] items = buildItemList(results); - new AlertDialog.Builder(getContext()) - .setSingleChoiceItems(items, -1, (dialog, which) -> { - applyLocation(results.get(which)); - dialog.dismiss(); - }) - .setNegativeButton(android.R.string.cancel, null) - .setTitle(R.string.weather_select_location) - .show(); + new AlertDialog.Builder(getContext()).setSingleChoiceItems(items, -1, (dialog, which) -> { + applyLocation(results.get(which)); + dialog.dismiss(); + }).setNegativeButton(android.R.string.cancel, null).setTitle(R.string.weather_select_location).show(); } private CharSequence[] buildItemList(List results) { @@ -125,8 +119,7 @@ public class CustomLocationPreference extends EditTextPreference } builder.append(result.getCity()); if (needCountry) { - String country = result.getCountry() != null - ? result.getCountry() : result.getCountryId(); + String country = result.getCountry() != null ? result.getCountry() : result.getCountryId(); builder.append(" (").append(country).append(")"); } items[i] = builder.toString(); @@ -149,12 +142,10 @@ public class CustomLocationPreference extends EditTextPreference public void onLookupCityRequestCompleted(int status, final List locations) { mHandler.post(() -> { final Context context = getContext(); - Log.i(TAG, "onLookupCityRequestCompleted: "+status+" "+(locations == null)); + Log.i(TAG, "onLookupCityRequestCompleted: " + status + " " + (locations == null)); if (locations == null || locations.isEmpty()) { - Toast.makeText(context, - context.getString(R.string.weather_retrieve_location_dialog_title), - Toast.LENGTH_SHORT) - .show(); + Toast.makeText(context, context.getString(R.string.weather_retrieve_location_dialog_title), + Toast.LENGTH_SHORT).show(); } else if (locations.size() > 1) { handleResultDisambiguation(locations); } else { diff --git a/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/DeviceStatusService.java b/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/DeviceStatusService.java index 43635b91989ef95793f646a5511038f385ebfddc..66dd96d45e467b0325a823411857b85d9116518d 100644 --- a/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/DeviceStatusService.java +++ b/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/DeviceStatusService.java @@ -8,7 +8,6 @@ import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.IBinder; import android.util.Log; - import foundation.e.blisslauncher.core.utils.Constants; public class DeviceStatusService extends Service { @@ -21,12 +20,13 @@ public class DeviceStatusService extends Service { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); - // Network connection has changed, make sure the weather update service knows about it + // Network connection has changed, make sure the weather update service knows + // about it if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) { - boolean hasConnection = !intent.getBooleanExtra( - ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); + boolean hasConnection = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); - if (D) Log.d(TAG, "Got connectivity change, has connection: " + hasConnection); + if (D) + Log.d(TAG, "Got connectivity change, has connection: " + hasConnection); Intent i = new Intent(context, WeatherUpdateService.class); if (hasConnection) { @@ -35,10 +35,12 @@ public class DeviceStatusService extends Service { context.stopService(i); } } else if (Intent.ACTION_SCREEN_OFF.equals(action)) { - if (D) Log.d(TAG, "onDisplayOff: Cancel pending update"); + if (D) + Log.d(TAG, "onDisplayOff: Cancel pending update"); WeatherUpdateService.cancelUpdates(context); } else if (Intent.ACTION_SCREEN_ON.equals(action)) { - if (D) Log.d(TAG, "onDisplayOn: Reschedule update"); + if (D) + Log.d(TAG, "onDisplayOn: Reschedule update"); WeatherUpdateService.scheduleNextUpdate(context, false); } } @@ -55,13 +57,15 @@ public class DeviceStatusService extends Service { @Override public void onDestroy() { - if (D) Log.d(TAG, "Stopping service"); + if (D) + Log.d(TAG, "Stopping service"); unregisterReceiver(mDeviceStatusListenerReceiver); } @Override public int onStartCommand(Intent intent, int flags, int startId) { - if (D) Log.d(TAG, "Starting service"); + if (D) + Log.d(TAG, "Starting service"); return START_STICKY; } diff --git a/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/ForecastBuilder.java b/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/ForecastBuilder.java index 01adeb765a03281245cfb340aa86e7e09bde7267..0672f8aa4e4f000147468db5200deedb84f3462b 100644 --- a/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/ForecastBuilder.java +++ b/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/ForecastBuilder.java @@ -14,15 +14,13 @@ import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; - +import foundation.e.blisslauncher.R; +import foundation.e.blisslauncher.core.Preferences; import java.util.Calendar; import java.util.GregorianCalendar; import java.util.List; import java.util.Locale; import java.util.TimeZone; - -import foundation.e.blisslauncher.R; -import foundation.e.blisslauncher.core.Preferences; import lineageos.weather.WeatherInfo; import lineageos.weather.util.WeatherUtils; @@ -33,9 +31,12 @@ public class ForecastBuilder { /** * This method is used to build the forecast panel * - * @param context Context to be used - * @param weatherPanel a view that will contain the forecast - * @param w the Weather info object that contains the forecast data + * @param context + * Context to be used + * @param weatherPanel + * a view that will contain the forecast + * @param w + * the Weather info object that contains the forecast data */ @SuppressLint("InflateParams") public static void buildLargePanel(Context context, View weatherPanel, WeatherInfo w) { @@ -67,9 +68,8 @@ public class ForecastBuilder { // Weather Image ImageView weatherImage = weatherPanel.findViewById(R.id.weather_image); String iconsSet = Preferences.getWeatherIconSet(context); - weatherImage.setImageBitmap( - WeatherIconUtils.getWeatherIconBitmap(context, iconsSet, color, - w.getConditionCode(), WeatherIconUtils.getNextHigherDensity(context))); + weatherImage.setImageBitmap(WeatherIconUtils.getWeatherIconBitmap(context, iconsSet, color, + w.getConditionCode(), WeatherIconUtils.getNextHigherDensity(context))); // City TextView city = weatherPanel.findViewById(R.id.weather_city); @@ -77,14 +77,11 @@ public class ForecastBuilder { // Weather Condition TextView weatherCondition = weatherPanel.findViewById(R.id.weather_condition); - weatherCondition.setText( - foundation.e.blisslauncher.features.weather.WeatherUtils.resolveWeatherCondition( - context, - w.getConditionCode())); + weatherCondition.setText(foundation.e.blisslauncher.features.weather.WeatherUtils + .resolveWeatherCondition(context, w.getConditionCode())); // Weather Temps - TextView weatherTemp = weatherPanel.findViewById( - R.id.weather_current_temperature); + TextView weatherTemp = weatherPanel.findViewById(R.id.weather_current_temperature); weatherTemp.setText(WeatherUtils.formatTemperature(temp, tempUnit)); // Weather Temps Panel additional networkItems @@ -97,26 +94,20 @@ public class ForecastBuilder { int windSpeedUnit = w.getWindSpeedUnit(); if (windSpeedUnit == MPH && useMetric) { windSpeedUnit = KPH; - windSpeed = foundation.e.blisslauncher.features.weather.WeatherUtils.milesToKilometers( - windSpeed); + windSpeed = foundation.e.blisslauncher.features.weather.WeatherUtils.milesToKilometers(windSpeed); } else if (windSpeedUnit == KPH && !useMetric) { windSpeedUnit = MPH; - windSpeed = foundation.e.blisslauncher.features.weather.WeatherUtils.kilometersToMiles( - windSpeed); + windSpeed = foundation.e.blisslauncher.features.weather.WeatherUtils.kilometersToMiles(windSpeed); } - // Humidity and Wind TextView weatherHumWind = weatherPanel.findViewById(R.id.weather_chance_rain); - weatherHumWind.setText( - String.format("%s, %s %s", - foundation.e.blisslauncher.features.weather.WeatherUtils.formatHumidity( - w.getHumidity()), - foundation.e.blisslauncher.features.weather.WeatherUtils.formatWindSpeed( - context, windSpeed, windSpeedUnit), - foundation.e.blisslauncher.features.weather.WeatherUtils - .resolveWindDirection( - context, w.getWindDirection()))); + weatherHumWind.setText(String.format("%s, %s %s", + foundation.e.blisslauncher.features.weather.WeatherUtils.formatHumidity(w.getHumidity()), + foundation.e.blisslauncher.features.weather.WeatherUtils.formatWindSpeed(context, windSpeed, + windSpeedUnit), + foundation.e.blisslauncher.features.weather.WeatherUtils.resolveWindDirection(context, + w.getWindDirection()))); LinearLayout forecastView = weatherPanel.findViewById(R.id.forecast_view); buildSmallPanel(context, forecastView, w); } @@ -124,9 +115,12 @@ public class ForecastBuilder { /** * This method is used to build the small, horizontal forecasts panel * - * @param context Context to be used - * @param smallPanel a horizontal {@link LinearLayout} that will contain the forecasts - * @param w the Weather info object that contains the forecast data + * @param context + * Context to be used + * @param smallPanel + * a horizontal {@link LinearLayout} that will contain the forecasts + * @param w + * the Weather info object that contains the forecast data */ @SuppressLint("InflateParams") private static void buildSmallPanel(Context context, LinearLayout smallPanel, WeatherInfo w) { @@ -136,8 +130,7 @@ public class ForecastBuilder { } // Get things ready - LayoutInflater inflater - = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); int color = Preferences.weatherFontColor(context); final boolean useMetric = Preferences.useMetricUnits(context); @@ -152,8 +145,7 @@ public class ForecastBuilder { Calendar calendar = new GregorianCalendar(MyTimezone); int weatherTempUnit = w.getTemperatureUnit(); int numForecasts = forecasts.size(); - int itemSidePadding = context.getResources().getDimensionPixelSize( - R.dimen.forecast_item_padding_side); + int itemSidePadding = context.getResources().getDimensionPixelSize(R.dimen.forecast_item_padding_side); // Iterate through the Forecasts for (int count = 0; count < numForecasts; count++) { @@ -165,20 +157,18 @@ public class ForecastBuilder { // The day of the week TextView day = forecastItem.findViewById(R.id.forecast_day); - day.setText(calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, - Locale.getDefault())); + day.setText(calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.getDefault())); calendar.roll(Calendar.DAY_OF_WEEK, true); // Weather Image ImageView image = forecastItem.findViewById(R.id.weather_image); String iconsSet = Preferences.getWeatherIconSet(context); - final int resId = WeatherIconUtils.getWeatherIconResource(context, iconsSet, - d.getConditionCode()); + final int resId = WeatherIconUtils.getWeatherIconResource(context, iconsSet, d.getConditionCode()); if (resId != 0) { image.setImageResource(resId); } else { - image.setImageBitmap(WeatherIconUtils.getWeatherIconBitmap(context, iconsSet, - color, d.getConditionCode())); + image.setImageBitmap( + WeatherIconUtils.getWeatherIconBitmap(context, iconsSet, color, d.getConditionCode())); } // Temperatures @@ -194,8 +184,7 @@ public class ForecastBuilder { highTemp = lineageos.weather.util.WeatherUtils.celsiusToFahrenheit(highTemp); tempUnit = FAHRENHEIT; } - String dayLow = lineageos.weather.util.WeatherUtils.formatTemperature(lowTemp, - tempUnit); + String dayLow = lineageos.weather.util.WeatherUtils.formatTemperature(lowTemp, tempUnit); String dayHigh = WeatherUtils.formatTemperature(highTemp, tempUnit); TextView temps = forecastItem.findViewById(R.id.weather_temps); temps.setText(String.format("%s\n%s", dayLow, dayHigh)); @@ -207,14 +196,14 @@ public class ForecastBuilder { // Add a divider to the right for all but the last view if (count < numForecasts - 1) { View divider = new View(context); - smallPanel.addView(divider, new LinearLayout.LayoutParams( - itemSidePadding, LinearLayout.LayoutParams.MATCH_PARENT)); + smallPanel.addView(divider, + new LinearLayout.LayoutParams(itemSidePadding, LinearLayout.LayoutParams.MATCH_PARENT)); } } smallPanel.setOnClickListener(v -> { Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage("foundation.e.weather"); - if(launchIntent != null){ + if (launchIntent != null) { launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(launchIntent); } diff --git a/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/IconSelectionPreference.java b/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/IconSelectionPreference.java index 57b4e882da15b8cacc64c9557aa4bab3d5362f13..18752a5d682d650aba7d64697700fe277c529bf9 100644 --- a/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/IconSelectionPreference.java +++ b/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/IconSelectionPreference.java @@ -25,17 +25,13 @@ import android.widget.ArrayAdapter; import android.widget.GridView; import android.widget.ImageView; import android.widget.TextView; - import androidx.annotation.NonNull; - +import foundation.e.blisslauncher.R; import java.util.ArrayList; import java.util.Arrays; import java.util.Locale; -import foundation.e.blisslauncher.R; - -public class IconSelectionPreference extends DialogPreference implements - AdapterView.OnItemClickListener { +public class IconSelectionPreference extends DialogPreference implements AdapterView.OnItemClickListener { private static final String INTENT_CATEGORY_ICONPACK = "com.dvtonder.chronus.ICON_PACK"; private static final String SEARCH_URI = "https://market.android.com/search?q=%s&c=apps"; @@ -46,24 +42,26 @@ public class IconSelectionPreference extends DialogPreference implements int descriptionResId; Drawable previewDrawable; int previewResId; - IconSetDescriptor(String name, int descriptionResId, - int previewResId) { + + IconSetDescriptor(String name, int descriptionResId, int previewResId) { this.name = name; this.descriptionResId = descriptionResId; this.previewResId = previewResId; } - IconSetDescriptor(String packageName, CharSequence description, - Drawable preview) { + + IconSetDescriptor(String packageName, CharSequence description, Drawable preview) { this.name = "ext:" + packageName; this.description = description; this.previewDrawable = preview; } + public CharSequence getDescription(Context context) { if (description != null) { return description; } return context.getString(descriptionResId); } + @Override public boolean equals(Object other) { if (other instanceof IconSetDescriptor) { @@ -74,16 +72,13 @@ public class IconSelectionPreference extends DialogPreference implements } } - private static final IconSetDescriptor ICON_SETS[] = new IconSetDescriptor[] { - new IconSetDescriptor("color", R.string.weather_icons_standard, - R.drawable.weather_color_28), - new IconSetDescriptor("mono", R.string.weather_icons_monochrome, - R.drawable.weather_28), - new IconSetDescriptor("vclouds", R.string.weather_icons_vclouds, - R.drawable.weather_vclouds_28) - }; + private static final IconSetDescriptor ICON_SETS[] = new IconSetDescriptor[]{ + new IconSetDescriptor("color", R.string.weather_icons_standard, R.drawable.weather_color_28), + new IconSetDescriptor("mono", R.string.weather_icons_monochrome, R.drawable.weather_28), + new IconSetDescriptor("vclouds", R.string.weather_icons_vclouds, R.drawable.weather_vclouds_28)}; private static final IntentFilter PACKAGE_CHANGE_FILTER = new IntentFilter(); + static { PACKAGE_CHANGE_FILTER.addAction(Intent.ACTION_PACKAGE_ADDED); PACKAGE_CHANGE_FILTER.addAction(Intent.ACTION_PACKAGE_REMOVED); @@ -134,8 +129,7 @@ public class IconSelectionPreference extends DialogPreference implements AlertDialog d = (AlertDialog) getDialog(); d.getButton(DialogInterface.BUTTON_NEUTRAL).setOnClickListener(view -> { - String uri = String.format(Locale.US, SEARCH_URI, - getContext().getString(R.string.icon_set_store_filter)); + String uri = String.format(Locale.US, SEARCH_URI, getContext().getString(R.string.icon_set_store_filter)); viewUri(getContext(), uri); }); } @@ -219,7 +213,7 @@ public class IconSelectionPreference extends DialogPreference implements public IconSetAdapter(Context context) { super(context, R.layout.icon_item, 0, populateIconSets(context)); - mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); + mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } public void reenumerateIconSets() { @@ -246,8 +240,7 @@ public class IconSelectionPreference extends DialogPreference implements } private static ArrayList populateIconSets(Context context) { - ArrayList result = new ArrayList<>( - Arrays.asList(ICON_SETS)); + ArrayList result = new ArrayList<>(Arrays.asList(ICON_SETS)); PackageManager pm = context.getPackageManager(); Intent i = new Intent(Intent.ACTION_MAIN); @@ -259,8 +252,7 @@ public class IconSelectionPreference extends DialogPreference implements Resources res = pm.getResourcesForApplication(appInfo); int previewResId = res.getIdentifier("weather_28", "drawable", appInfo.packageName); Drawable preview = previewResId != 0 ? res.getDrawable(previewResId) : null; - result.add(new IconSetDescriptor(appInfo.packageName, - appInfo.loadLabel(pm), preview)); + result.add(new IconSetDescriptor(appInfo.packageName, appInfo.loadLabel(pm), preview)); } catch (PackageManager.NameNotFoundException e) { // shouldn't happen, ignore package } diff --git a/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/PermissionRequestActivity.java b/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/PermissionRequestActivity.java index 9b4637a9a7e222dd4de16d7b3c9ec75e8da4fced..45fe3335d75d8ed6c5a2f1a239669735f33db0f7 100644 --- a/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/PermissionRequestActivity.java +++ b/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/PermissionRequestActivity.java @@ -6,7 +6,6 @@ import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; import android.os.ResultReceiver; - import androidx.annotation.NonNull; public class PermissionRequestActivity extends Activity { @@ -38,16 +37,14 @@ public class PermissionRequestActivity extends Activity { } public boolean hasLocationPermission() { - return checkSelfPermission( - Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED; + return checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED; } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) { - if (grantResults.length > 0 - && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { mResult = RESULT_OK; } } diff --git a/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/WeatherIconUtils.java b/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/WeatherIconUtils.java index 7804e09ee81d9eec6aea37e02abdb7e18ed11ee5..dbcc2525bb23ff1830efbb10b80c2b374ed02435 100644 --- a/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/WeatherIconUtils.java +++ b/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/WeatherIconUtils.java @@ -13,7 +13,6 @@ import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.DisplayMetrics; import android.util.Log; - import foundation.e.blisslauncher.R; import foundation.e.blisslauncher.core.utils.Constants; @@ -27,9 +26,9 @@ public class WeatherIconUtils { } final Resources res = context.getResources(); - final int resId = res.getIdentifier("weather_" + iconSet + "_" - + WeatherUtils.addOffsetToConditionCodeFromWeatherContract(conditionCode), "drawable", - context.getPackageName()); + final int resId = res.getIdentifier( + "weather_" + iconSet + "_" + WeatherUtils.addOffsetToConditionCodeFromWeatherContract(conditionCode), + "drawable", context.getPackageName()); if (resId != 0) { return resId; @@ -39,13 +38,12 @@ public class WeatherIconUtils { return R.drawable.weather_color_na; } - public static Bitmap getWeatherIconBitmap(Context context, String iconSet, - int color, int conditionCode) { + public static Bitmap getWeatherIconBitmap(Context context, String iconSet, int color, int conditionCode) { return getWeatherIconBitmap(context, iconSet, color, conditionCode, 0); } - public static Bitmap getWeatherIconBitmap(Context context, String iconSet, - int color, int conditionCode, int density) { + public static Bitmap getWeatherIconBitmap(Context context, String iconSet, int color, int conditionCode, + int density) { boolean isMonoSet = Constants.MONOCHROME.equals(iconSet); Resources res = null; int resId = 0; @@ -63,8 +61,8 @@ public class WeatherIconUtils { } if (resId == 0) { String identifier = isMonoSet - ? "weather_" + fixedConditionCode : "weather_" - + iconSet + "_" + fixedConditionCode; + ? "weather_" + fixedConditionCode + : "weather_" + iconSet + "_" + fixedConditionCode; res = context.getResources(); resId = res.getIdentifier(identifier, "drawable", context.getPackageName()); } @@ -86,8 +84,7 @@ public class WeatherIconUtils { return src; } - final Bitmap dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(), - Bitmap.Config.ARGB_8888); + final Bitmap dest = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888); Canvas c = new Canvas(dest); final Paint paint = new Paint(); @@ -99,19 +96,20 @@ public class WeatherIconUtils { public static Bitmap getBitmapFromResource(Resources res, int resId, int density) { if (density == 0) { - if (D) Log.d(TAG, "Decoding resource id = " + resId + " for default density"); + if (D) + Log.d(TAG, "Decoding resource id = " + resId + " for default density"); return BitmapFactory.decodeResource(res, resId); } - if (D) Log.d(TAG, "Decoding resource id = " + resId + " for density = " + density); + if (D) + Log.d(TAG, "Decoding resource id = " + resId + " for density = " + density); Drawable d = res.getDrawableForDensity(resId, density); if (d instanceof BitmapDrawable) { BitmapDrawable bd = (BitmapDrawable) d; return bd.getBitmap(); } - Bitmap result = Bitmap.createBitmap(d.getIntrinsicWidth(), - d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); + Bitmap result = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(result); d.setBounds(0, 0, result.getWidth(), result.getHeight()); d.draw(canvas); diff --git a/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/WeatherPreferences.java b/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/WeatherPreferences.java index 5fcf7231a489d1c857a905c4d6bbb382056d14bf..daf5c06f768951959240f3e4f888f0bc62e7a07a 100644 --- a/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/WeatherPreferences.java +++ b/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/WeatherPreferences.java @@ -19,18 +19,16 @@ import android.provider.Settings; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; - import androidx.annotation.NonNull; - import foundation.e.blisslauncher.R; import foundation.e.blisslauncher.core.Preferences; import foundation.e.blisslauncher.core.utils.Constants; import lineageos.weather.LineageWeatherManager; - -public class WeatherPreferences extends PreferenceActivity implements - SharedPreferences.OnSharedPreferenceChangeListener, - LineageWeatherManager.WeatherServiceProviderChangeListener { +public class WeatherPreferences extends PreferenceActivity + implements + SharedPreferences.OnSharedPreferenceChangeListener, + LineageWeatherManager.WeatherServiceProviderChangeListener { private static final String TAG = "WeatherPreferences"; public static final int LOCATION_PERMISSION_REQUEST_CODE = 1; @@ -52,12 +50,10 @@ public class WeatherPreferences extends PreferenceActivity implements // Load networkItems that need custom summaries etc. mUseCustomLoc = (SwitchPreference) findPreference(Constants.WEATHER_USE_CUSTOM_LOCATION); - mCustomWeatherLoc = (EditTextPreference) findPreference( - Constants.WEATHER_CUSTOM_LOCATION_CITY); + mCustomWeatherLoc = (EditTextPreference) findPreference(Constants.WEATHER_CUSTOM_LOCATION_CITY); mIconSet = (IconSelectionPreference) findPreference(Constants.WEATHER_ICONS); mUseMetric = (SwitchPreference) findPreference(Constants.WEATHER_USE_METRIC); - mUseCustomlocation = (SwitchPreference) findPreference( - Constants.WEATHER_USE_CUSTOM_LOCATION); + mUseCustomlocation = (SwitchPreference) findPreference(Constants.WEATHER_USE_CUSTOM_LOCATION); mWeatherSource = (PreferenceScreen) findPreference(Constants.WEATHER_SOURCE); mWeatherSource.setOnPreferenceChangeListener((preference, o) -> { if (Preferences.getWeatherSource(mContext) != null) { @@ -91,8 +87,7 @@ public class WeatherPreferences extends PreferenceActivity implements public void onResume() { super.onResume(); - getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener( - this); + getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); if (mPostResumeRunnable != null) { mPostResumeRunnable.run(); @@ -112,8 +107,7 @@ public class WeatherPreferences extends PreferenceActivity implements @Override public void onPause() { super.onPause(); - getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener( - this); + getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this); final LineageWeatherManager weatherManager = LineageWeatherManager.getInstance(mContext); weatherManager.unregisterWeatherServiceProviderChangeListener(this); } @@ -121,10 +115,10 @@ public class WeatherPreferences extends PreferenceActivity implements @Override public void onDestroy() { super.onDestroy(); - if (mUseCustomlocation.isChecked() - && Preferences.getCustomWeatherLocationCity(mContext) == null) { - //The user decided to toggle the custom location switch, but forgot to set a custom - //location, we need to go back to geo location + if (mUseCustomlocation.isChecked() && Preferences.getCustomWeatherLocationCity(mContext) == null) { + // The user decided to toggle the custom location switch, but forgot to set a + // custom + // location, we need to go back to geo location Preferences.setUseCustomWeatherLocation(mContext, false); } } @@ -155,8 +149,10 @@ public class WeatherPreferences extends PreferenceActivity implements } if (TextUtils.equals(key, Constants.WEATHER_SOURCE)) { - // The weather source changed, invalidate the custom location settings and change - // back to GeoLocation to force the user to specify a new custom location if needed + // The weather source changed, invalidate the custom location settings and + // change + // back to GeoLocation to force the user to specify a new custom location if + // needed Preferences.setCustomWeatherLocationCity(mContext, null); Preferences.setCustomWeatherLocation(mContext, null); Preferences.setUseCustomWeatherLocation(mContext, false); @@ -165,8 +161,8 @@ public class WeatherPreferences extends PreferenceActivity implements } if (key.equals(Constants.WEATHER_USE_CUSTOM_LOCATION)) { - if (!mUseCustomLoc.isChecked() || (mUseCustomLoc.isChecked() && - Preferences.getCustomWeatherLocation(mContext) != null)) { + if (!mUseCustomLoc.isChecked() + || (mUseCustomLoc.isChecked() && Preferences.getCustomWeatherLocation(mContext) != null)) { forceWeatherUpdate = true; } } @@ -187,8 +183,8 @@ public class WeatherPreferences extends PreferenceActivity implements } if (Constants.DEBUG) { - Log.v(TAG, "Preference " + key + " changed, need update " + - needWeatherUpdate + " force update " + forceWeatherUpdate); + Log.v(TAG, "Preference " + key + " changed, need update " + needWeatherUpdate + " force update " + + forceWeatherUpdate); } if ((needWeatherUpdate || forceWeatherUpdate)) { @@ -201,13 +197,13 @@ public class WeatherPreferences extends PreferenceActivity implements } public static boolean hasLocationPermission(Context context) { - return context.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) - == PackageManager.PERMISSION_GRANTED; + return context + .checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED; } - //=============================================================================================== + // =============================================================================================== // Utility classes and supporting methods - //=============================================================================================== + // =============================================================================================== private void updateLocationSummary() { if (mUseCustomLoc.isChecked()) { @@ -233,13 +229,11 @@ public class WeatherPreferences extends PreferenceActivity implements builder.setTitle(R.string.weather_retrieve_location_dialog_title); builder.setMessage(R.string.weather_retrieve_location_dialog_message); builder.setCancelable(false); - builder.setPositiveButton(R.string.weather_retrieve_location_dialog_enable_button, - (dialog1, whichButton) -> { - Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); - intent.setFlags( - Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); - startActivityForResult(intent, 203); - }); + builder.setPositiveButton(R.string.weather_retrieve_location_dialog_enable_button, (dialog1, whichButton) -> { + Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); + startActivityForResult(intent, 203); + }); builder.setNegativeButton(R.string.cancel, null); dialog = builder.create(); dialog.show(); @@ -250,8 +244,7 @@ public class WeatherPreferences extends PreferenceActivity implements if (requestCode == 203) { LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { - Toast.makeText(this, getString(R.string.toast_custom_location), - Toast.LENGTH_SHORT).show(); + Toast.makeText(this, getString(R.string.toast_custom_location), Toast.LENGTH_SHORT).show(); } else { startService(new Intent(this, WeatherUpdateService.class) .putExtra(WeatherUpdateService.ACTION_FORCE_UPDATE, true)); @@ -271,8 +264,7 @@ public class WeatherPreferences extends PreferenceActivity implements public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) { - if (grantResults.length > 0 - && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // We only get here if user tried to enable the preference, // hence safe to turn it on after permission is granted LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); diff --git a/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/WeatherSourceListenerService.java b/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/WeatherSourceListenerService.java index 6cb26d48701e29fa6d1131e0b1cead95aa8110c4..e935ec462ab88c36a66c86a8102f1f2d68e9acbb 100644 --- a/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/WeatherSourceListenerService.java +++ b/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/WeatherSourceListenerService.java @@ -5,13 +5,13 @@ import android.content.Context; import android.content.Intent; import android.os.IBinder; import android.util.Log; - import foundation.e.blisslauncher.core.Preferences; import foundation.e.blisslauncher.core.utils.Constants; import lineageos.weather.LineageWeatherManager; public class WeatherSourceListenerService extends Service - implements LineageWeatherManager.WeatherServiceProviderChangeListener { + implements + LineageWeatherManager.WeatherServiceProviderChangeListener { private static final String TAG = WeatherSourceListenerService.class.getSimpleName(); private static final boolean D = Constants.DEBUG; @@ -20,16 +20,20 @@ public class WeatherSourceListenerService extends Service @Override public void onWeatherServiceProviderChanged(String providerLabel) { - if (D) Log.d(TAG, "Weather Source changed " + providerLabel); + if (D) + Log.d(TAG, "Weather Source changed " + providerLabel); Preferences.setWeatherSource(mContext, providerLabel); Preferences.setCachedWeatherInfo(mContext, 0, null); - //The data contained in WeatherLocation is tightly coupled to the weather provider - //that generated that data, so we need to clear the cached weather location and let the new - //weather provider regenerate the data if the user decides to use custom location again + // The data contained in WeatherLocation is tightly coupled to the weather + // provider + // that generated that data, so we need to clear the cached weather location and + // let the new + // weather provider regenerate the data if the user decides to use custom + // location again Preferences.setCustomWeatherLocationCity(mContext, null); Preferences.setCustomWeatherLocation(mContext, null); Preferences.setUseCustomWeatherLocation(mContext, false); - + if (providerLabel != null) { mContext.startService(new Intent(mContext, WeatherUpdateService.class) .putExtra(WeatherUpdateService.ACTION_FORCE_UPDATE, true)); @@ -39,11 +43,11 @@ public class WeatherSourceListenerService extends Service @Override public void onCreate() { mContext = getApplicationContext(); - final LineageWeatherManager weatherManager - = LineageWeatherManager.getInstance(mContext); + final LineageWeatherManager weatherManager = LineageWeatherManager.getInstance(mContext); weatherManager.registerWeatherServiceProviderChangeListener(this); mRegistered = true; - if (D) Log.d(TAG, "Listener registered"); + if (D) + Log.d(TAG, "Listener registered"); } @Override diff --git a/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/WeatherUpdateService.java b/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/WeatherUpdateService.java index 71d25641f20d842636a0c95af670c46b7882dd60..6d2a0005b9d1926cb6187a018b5b36b8d9fa0554 100644 --- a/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/WeatherUpdateService.java +++ b/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/WeatherUpdateService.java @@ -25,15 +25,12 @@ import android.os.SystemClock; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; - import androidx.localbroadcastmanager.content.LocalBroadcastManager; - -import java.lang.ref.WeakReference; -import java.util.Date; - import foundation.e.blisslauncher.R; import foundation.e.blisslauncher.core.Preferences; import foundation.e.blisslauncher.core.utils.Constants; +import java.lang.ref.WeakReference; +import java.util.Date; import lineageos.weather.LineageWeatherManager; import lineageos.weather.WeatherInfo; import lineageos.weather.WeatherLocation; @@ -42,18 +39,14 @@ public class WeatherUpdateService extends Service { private static final String TAG = "WeatherUpdateService"; private static final boolean D = Constants.DEBUG; - public static final String ACTION_FORCE_UPDATE = - "org.indin.blisslauncher.action.FORCE_WEATHER_UPDATE"; - private static final String ACTION_CANCEL_LOCATION_UPDATE = - "org.indin.blisslauncher.action.CANCEL_LOCATION_UPDATE"; + public static final String ACTION_FORCE_UPDATE = "org.indin.blisslauncher.action.FORCE_WEATHER_UPDATE"; + private static final String ACTION_CANCEL_LOCATION_UPDATE = "org.indin.blisslauncher.action.CANCEL_LOCATION_UPDATE"; - private static final String ACTION_CANCEL_UPDATE_WEATHER_REQUEST = - "org.indin.blisslauncher.action.CANCEL_UPDATE_WEATHER_REQUEST"; + private static final String ACTION_CANCEL_UPDATE_WEATHER_REQUEST = "org.indin.blisslauncher.action.CANCEL_UPDATE_WEATHER_REQUEST"; private static final long WEATHER_UPDATE_REQUEST_TIMEOUT_MS = 300L * 1000L; // Broadcast action for end of update - public static final String ACTION_UPDATE_FINISHED = - "org.indin.blisslauncher.action.WEATHER_UPDATE_FINISHED"; + public static final String ACTION_UPDATE_FINISHED = "org.indin.blisslauncher.action.WEATHER_UPDATE_FINISHED"; public static final String EXTRA_UPDATE_CANCELLED = "update_cancelled"; private static final long LOCATION_REQUEST_TIMEOUT = 5L * 60L * 1000L; @@ -83,7 +76,8 @@ public class WeatherUpdateService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { - if (D) Log.v(TAG, "Got intent " + intent); + if (D) + Log.v(TAG, "Got intent " + intent); if (ACTION_CANCEL_LOCATION_UPDATE.equals(intent.getAction())) { WeatherLocationListener.cancel(this); @@ -95,17 +89,12 @@ public class WeatherUpdateService extends Service { if (ACTION_CANCEL_UPDATE_WEATHER_REQUEST.equals(intent.getAction())) { if (mWorkerThread.isProcessing()) { - mWorkerThread.getHandler().obtainMessage( - WorkerThread.MSG_CANCEL_UPDATE_WEATHER_REQUEST).sendToTarget(); + mWorkerThread.getHandler().obtainMessage(WorkerThread.MSG_CANCEL_UPDATE_WEATHER_REQUEST).sendToTarget(); mHandler.post(() -> { final Context context = getApplicationContext(); - final LineageWeatherManager weatherManager - = LineageWeatherManager.getInstance(context); - final String activeProviderLabel - = weatherManager.getActiveWeatherServiceProviderLabel(); - final String noData - = getString(R.string.weather_cannot_reach_provider, - activeProviderLabel); + final LineageWeatherManager weatherManager = LineageWeatherManager.getInstance(context); + final String activeProviderLabel = weatherManager.getActiveWeatherServiceProviderLabel(); + final String noData = getString(R.string.weather_cannot_reach_provider, activeProviderLabel); Toast.makeText(context, noData, Toast.LENGTH_SHORT).show(); }); } @@ -121,65 +110,66 @@ public class WeatherUpdateService extends Service { return START_NOT_STICKY; } - mWorkerThread.getHandler().obtainMessage(WorkerThread.MSG_ON_NEW_WEATHER_REQUEST) - .sendToTarget(); + mWorkerThread.getHandler().obtainMessage(WorkerThread.MSG_ON_NEW_WEATHER_REQUEST).sendToTarget(); return START_REDELIVER_INTENT; } private boolean shouldUpdate(boolean force) { - final LineageWeatherManager weatherManager - = LineageWeatherManager.getInstance(getApplicationContext()); + final LineageWeatherManager weatherManager = LineageWeatherManager.getInstance(getApplicationContext()); if (weatherManager.getActiveWeatherServiceProviderLabel() == null) { - //Why bother if we don't even have an active provider - if (D) Log.d(TAG, "No active weather service provider found, skip"); + // Why bother if we don't even have an active provider + if (D) + Log.d(TAG, "No active weather service provider found, skip"); return false; } final long interval = Preferences.weatherRefreshIntervalInMs(this); if (interval == 0 && !force) { - if (D) Log.v(TAG, "Interval set to manual and update not forced, skip"); + if (D) + Log.v(TAG, "Interval set to manual and update not forced, skip"); return false; } if (!WeatherPreferences.hasLocationPermission(this)) { - if (D) Log.v(TAG, "Application does not have the location permission, skip"); + if (D) + Log.v(TAG, "Application does not have the location permission, skip"); return false; } - - ConnectivityManager cm = (ConnectivityManager) getSystemService( - Context.CONNECTIVITY_SERVICE); + ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo info = cm.getActiveNetworkInfo(); if (info == null || !info.isConnected() || !info.isAvailable()) { - if (D) Log.d(TAG, "Network is not available, skip"); + if (D) + Log.d(TAG, "Network is not available, skip"); return false; } else { if (force) { - if (D) Log.d(TAG, "Forcing weather update"); + if (D) + Log.d(TAG, "Forcing weather update"); return true; } else { final long now = SystemClock.elapsedRealtime(); final long lastUpdate = Preferences.lastWeatherUpdateTimestamp(this); final long due = lastUpdate + interval; if (D) { - Log.d(TAG, "Now " + now + " Last update " + lastUpdate - + " interval " + interval); + Log.d(TAG, "Now " + now + " Last update " + lastUpdate + " interval " + interval); } if (lastUpdate == 0 || due - now < 0) { - if (D) Log.d(TAG, "Should update"); + if (D) + Log.d(TAG, "Should update"); return true; } else { - if (D) Log.v(TAG, "Next weather update due in " + (due - now) + " ms, skip"); + if (D) + Log.v(TAG, "Next weather update due in " + (due - now) + " ms, skip"); return false; } } } } - private class WorkerThread extends HandlerThread - implements LineageWeatherManager.WeatherUpdateRequestListener { + private class WorkerThread extends HandlerThread implements LineageWeatherManager.WeatherUpdateRequestListener { public static final int MSG_ON_NEW_WEATHER_REQUEST = 1; public static final int MSG_ON_WEATHER_REQUEST_COMPLETED = 2; @@ -192,7 +182,7 @@ public class WeatherUpdateService extends Service { private PendingIntent mTimeoutPendingIntent; private int mRequestId; private final LineageWeatherManager mWeatherManager; - final private Context mContext; + private final Context mContext; public WorkerThread(Context context) { super("weather-service-worker"); @@ -204,24 +194,25 @@ public class WeatherUpdateService extends Service { mHandler = new Handler(getLooper()) { @Override public void handleMessage(Message msg) { - if (D) Log.d(TAG, "Msg " + msg.what); + if (D) + Log.d(TAG, "Msg " + msg.what); switch (msg.what) { - case MSG_ON_NEW_WEATHER_REQUEST: + case MSG_ON_NEW_WEATHER_REQUEST : onNewWeatherRequest(); break; - case MSG_ON_WEATHER_REQUEST_COMPLETED: + case MSG_ON_WEATHER_REQUEST_COMPLETED : WeatherInfo info = (WeatherInfo) msg.obj; onWeatherRequestCompleted(info); break; - case MSG_WEATHER_REQUEST_FAILED: + case MSG_WEATHER_REQUEST_FAILED : int status = msg.arg1; onWeatherRequestFailed(status); break; - case MSG_CANCEL_UPDATE_WEATHER_REQUEST: + case MSG_CANCEL_UPDATE_WEATHER_REQUEST : onCancelUpdateWeatherRequest(); break; - default: - //Unknown message, pass it on... + default : + // Unknown message, pass it on... super.handleMessage(msg); } } @@ -238,7 +229,8 @@ public class WeatherUpdateService extends Service { AlarmManager am = (AlarmManager) mContext.getSystemService(ALARM_SERVICE); long elapseTime = SystemClock.elapsedRealtime() + WEATHER_UPDATE_REQUEST_TIMEOUT_MS; am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, elapseTime, mTimeoutPendingIntent); - if (D) Log.v(TAG, "Timeout alarm set to expire in " + elapseTime + " ms"); + if (D) + Log.v(TAG, "Timeout alarm set to expire in " + elapseTime + " ms"); } private void cancelTimeoutAlarm() { @@ -247,7 +239,8 @@ public class WeatherUpdateService extends Service { AlarmManager am = (AlarmManager) mContext.getSystemService(ALARM_SERVICE); am.cancel(mTimeoutPendingIntent); mTimeoutPendingIntent = null; - if (D) Log.v(TAG, "Timeout alarm cancelled"); + if (D) + Log.v(TAG, "Timeout alarm cancelled"); } } @@ -263,12 +256,11 @@ public class WeatherUpdateService extends Service { } mIsProcessingWeatherUpdate = true; - final PowerManager pm - = (PowerManager) mContext.getSystemService(POWER_SERVICE); - mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, - "blisslauncher:WeatherUpdateService"); + final PowerManager pm = (PowerManager) mContext.getSystemService(POWER_SERVICE); + mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "blisslauncher:WeatherUpdateService"); mWakeLock.setReferenceCounted(false); - if (D) Log.v(TAG, "ACQUIRING WAKELOCK"); + if (D) + Log.v(TAG, "ACQUIRING WAKELOCK"); mWakeLock.acquire(); WeatherLocation customWeatherLocation = null; @@ -277,34 +269,37 @@ public class WeatherUpdateService extends Service { } if (customWeatherLocation != null) { mRequestId = mWeatherManager.requestWeatherUpdate(customWeatherLocation, this); - if (D) Log.d(TAG, "Request submitted using WeatherLocation"); + if (D) + Log.d(TAG, "Request submitted using WeatherLocation"); startTimeoutAlarm(); } else { final Location location = getCurrentLocation(); if (location != null) { mRequestId = mWeatherManager.requestWeatherUpdate(location, this); - if (D) Log.d(TAG, "Request submitted using Location"); + if (D) + Log.d(TAG, "Request submitted using Location"); startTimeoutAlarm(); } else { // work with cached location from last request for now // a listener to update it is already scheduled if possible WeatherInfo cachedInfo = Preferences.getCachedWeatherInfo(mContext); if (cachedInfo != null) { - mHandler.obtainMessage(MSG_ON_WEATHER_REQUEST_COMPLETED, - cachedInfo).sendToTarget(); - if (D) Log.d(TAG, "Returning cached weather data [ " - + cachedInfo.toString() + " ]"); + mHandler.obtainMessage(MSG_ON_WEATHER_REQUEST_COMPLETED, cachedInfo).sendToTarget(); + if (D) + Log.d(TAG, "Returning cached weather data [ " + cachedInfo.toString() + " ]"); } else { - mHandler.obtainMessage(MSG_WEATHER_REQUEST_FAILED, - LineageWeatherManager.RequestStatus.FAILED, 0).sendToTarget(); + mHandler.obtainMessage(MSG_WEATHER_REQUEST_FAILED, LineageWeatherManager.RequestStatus.FAILED, + 0).sendToTarget(); } } } } public void tearDown() { - if (D) Log.d(TAG, "Tearing down worker thread"); - if (isProcessing()) mWeatherManager.cancelRequest(mRequestId); + if (D) + Log.d(TAG, "Tearing down worker thread"); + if (isProcessing()) + mWeatherManager.cancelRequest(mRequestId); quit(); } @@ -313,31 +308,34 @@ public class WeatherUpdateService extends Service { } private Location getCurrentLocation() { - final LocationManager lm - = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); + final LocationManager lm = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); Location location = null; - try{ + try { location = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); - }catch (SecurityException e){ + } catch (SecurityException e) { e.printStackTrace(); } - if (D && location != null) Log.v(TAG, "Current location is " + location + ", accuracy: " + location.getAccuracy()); + if (D && location != null) + Log.v(TAG, "Current location is " + location + ", accuracy: " + location.getAccuracy()); if (location != null && location.getAccuracy() > LOCATION_ACCURACY_THRESHOLD_METERS) { - if (D) Log.d(TAG, "Ignoring inaccurate location"); + if (D) + Log.d(TAG, "Ignoring inaccurate location"); location = null; } // If lastKnownLocation is not present (because none of the apps in the // device has requested the current location to the system yet) or outdated, - // then try to get the current location use the provider that best matches the criteria. + // then try to get the current location use the provider that best matches the + // criteria. boolean needsUpdate = location == null; if (location != null) { long delta = System.currentTimeMillis() - location.getTime(); needsUpdate = delta > OUTDATED_LOCATION_THRESHOLD_MILLIS; } if (needsUpdate) { - if (D) Log.d(TAG, "Getting best location provider"); + if (D) + Log.d(TAG, "Getting best location provider"); String locationProvider = lm.getBestProvider(sLocationCriteria, true); if (TextUtils.isEmpty(locationProvider)) { Log.e(TAG, "No available location providers matching criteria."); @@ -362,23 +360,26 @@ public class WeatherUpdateService extends Service { } private void onWeatherRequestFailed(int status) { - if (D) Log.d(TAG, "Weather refresh failed ["+status+"]"); + if (D) + Log.d(TAG, "Weather refresh failed [" + status + "]"); cancelTimeoutAlarm(); if (status == LineageWeatherManager.RequestStatus.ALREADY_IN_PROGRESS) { - if (D) Log.d(TAG, "A request is already in progress, no need to schedule again"); + if (D) + Log.d(TAG, "A request is already in progress, no need to schedule again"); } else if (status == LineageWeatherManager.RequestStatus.FAILED) { - //Something went wrong, let's schedule an update at the next interval from now - //A force update might happen earlier anyway + // Something went wrong, let's schedule an update at the next interval from now + // A force update might happen earlier anyway scheduleUpdate(mContext, Preferences.weatherRefreshIntervalInMs(mContext), false); } else { - //Wait until the next update is due + // Wait until the next update is due scheduleNextUpdate(mContext, false); } broadcastAndCleanUp(true); } private void onCancelUpdateWeatherRequest() { - if (D) Log.d(TAG, "Cancelling active weather request"); + if (D) + Log.d(TAG, "Cancelling active weather request"); if (mIsProcessingWeatherUpdate) { cancelTimeoutAlarm(); mWeatherManager.cancelRequest(mRequestId); @@ -391,7 +392,8 @@ public class WeatherUpdateService extends Service { finishedIntent.putExtra(EXTRA_UPDATE_CANCELLED, updateCancelled); mContext.sendBroadcast(finishedIntent); - if (D) Log.d(TAG, "RELEASING WAKELOCK"); + if (D) + Log.d(TAG, "RELEASING WAKELOCK"); mWakeLock.release(); mIsProcessingWeatherUpdate = false; mContext.stopService(new Intent(mContext, WeatherUpdateService.class)); @@ -400,11 +402,9 @@ public class WeatherUpdateService extends Service { @Override public void onWeatherRequestCompleted(int state, WeatherInfo weatherInfo) { if (state == LineageWeatherManager.RequestStatus.COMPLETED) { - mHandler.obtainMessage(WorkerThread.MSG_ON_WEATHER_REQUEST_COMPLETED, weatherInfo) - .sendToTarget(); + mHandler.obtainMessage(WorkerThread.MSG_ON_WEATHER_REQUEST_COMPLETED, weatherInfo).sendToTarget(); } else { - mHandler.obtainMessage(WorkerThread.MSG_WEATHER_REQUEST_FAILED, state, 0) - .sendToTarget(); + mHandler.obtainMessage(WorkerThread.MSG_WEATHER_REQUEST_FAILED, state, 0).sendToTarget(); } } } @@ -434,11 +434,12 @@ public class WeatherUpdateService extends Service { @SuppressLint("MissingPermission") static void registerIfNeeded(Context context, String provider) { synchronized (WeatherLocationListener.class) { - if (D) Log.d(TAG, "Registering location listener"); + if (D) + Log.d(TAG, "Registering location listener"); if (sInstance == null) { final Context appContext = context.getApplicationContext(); - final LocationManager locationManager = - (LocationManager) appContext.getSystemService(Context.LOCATION_SERVICE); + final LocationManager locationManager = (LocationManager) appContext + .getSystemService(Context.LOCATION_SERVICE); // Check location provider after set sInstance, so, if the provider is not // supported, we never enter here again. @@ -449,9 +450,9 @@ public class WeatherUpdateService extends Service { // change this if this call receive different providers LocationProvider lp = locationManager.getProvider(provider); if (lp != null) { - if (D) Log.d(TAG, "LocationManager - Requesting single update"); - locationManager.requestSingleUpdate(provider, sInstance, - appContext.getMainLooper()); + if (D) + Log.d(TAG, "LocationManager - Requesting single update"); + locationManager.requestSingleUpdate(provider, sInstance, appContext.getMainLooper()); sInstance.setTimeoutAlarm(); } } @@ -462,9 +463,10 @@ public class WeatherUpdateService extends Service { synchronized (WeatherLocationListener.class) { if (sInstance != null) { final Context appContext = context.getApplicationContext(); - final LocationManager locationManager = - (LocationManager) appContext.getSystemService(Context.LOCATION_SERVICE); - if (D) Log.d(TAG, "Aborting location request after timeout"); + final LocationManager locationManager = (LocationManager) appContext + .getSystemService(Context.LOCATION_SERVICE); + if (D) + Log.d(TAG, "Aborting location request after timeout"); locationManager.removeUpdates(sInstance); sInstance.cancelTimeoutAlarm(); sInstance = null; @@ -501,7 +503,8 @@ public class WeatherUpdateService extends Service { @Override public void onLocationChanged(Location location) { // Now, we have a location to use. Schedule a weather update right now. - if (D) Log.d(TAG, "The location has changed, schedule an update "); + if (D) + Log.d(TAG, "The location has changed, schedule an update "); synchronized (WeatherLocationListener.class) { scheduleUpdate(mContext.get(), 0, true); cancelTimeoutAlarm(); @@ -512,7 +515,8 @@ public class WeatherUpdateService extends Service { @Override public void onStatusChanged(String provider, int status, Bundle extras) { // Now, we have a location to use. Schedule a weather update right now. - if (D) Log.d(TAG, "The location service has become available, schedule an update "); + if (D) + Log.d(TAG, "The location service has become available, schedule an update "); if (status == LocationProvider.AVAILABLE) { synchronized (WeatherLocationListener.class) { scheduleUpdate(mContext.get(), 0, true); @@ -536,22 +540,25 @@ public class WeatherUpdateService extends Service { private static void scheduleUpdate(Context context, long millisFromNow, boolean force) { AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); long due = SystemClock.elapsedRealtime() + millisFromNow; - if (D) Log.d(TAG, "Next update scheduled at " - + new Date(System.currentTimeMillis() + millisFromNow)); + if (D) + Log.d(TAG, "Next update scheduled at " + new Date(System.currentTimeMillis() + millisFromNow)); am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, due, getUpdateIntent(context, force)); } public static void scheduleNextUpdate(Context context, boolean force) { if (force) { - if (D) Log.d(TAG, "Scheduling next update immediately"); + if (D) + Log.d(TAG, "Scheduling next update immediately"); scheduleUpdate(context, 0, true); } else { final long lastUpdate = Preferences.lastWeatherUpdateTimestamp(context); final long interval = Preferences.weatherRefreshIntervalInMs(context); final long now = SystemClock.elapsedRealtime(); long due = (interval + lastUpdate) - now; - if (due < 0) due = 0; - if (D) Log.d(TAG, "Scheduling in " + due + " ms"); + if (due < 0) + due = 0; + if (D) + Log.d(TAG, "Scheduling in " + due + " ms"); scheduleUpdate(context, due, false); } } diff --git a/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/WeatherUtils.java b/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/WeatherUtils.java index a56717f8556344ee4057cc9b40f472f027b9785c..6baebab0c8560c6e9a64ea740bd9eafdcf82f0c8 100644 --- a/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/WeatherUtils.java +++ b/app/src/apiOreo/java/foundation/e/blisslauncher/features/weather/WeatherUtils.java @@ -2,10 +2,8 @@ package foundation.e.blisslauncher.features.weather; import android.content.Context; import android.content.res.Resources; - -import java.text.DecimalFormat; - import foundation.e.blisslauncher.R; +import java.text.DecimalFormat; import lineageos.app.LineageContextConstants; import lineageos.providers.WeatherContract; import lineageos.providers.WeatherContract.WeatherColumns.WeatherCode; @@ -29,8 +27,11 @@ public final class WeatherUtils { /** * Returns a localized string of the wind direction - * @param context Application context to access resources - * @param windDirection The wind direction in degrees + * + * @param context + * Application context to access resources + * @param windDirection + * The wind direction in degrees * @return The wind direction in string format */ public static String resolveWindDirection(Context context, double windDirection) { @@ -63,14 +64,18 @@ public final class WeatherUtils { /** * Returns the resource name associated to the supplied weather condition code - * @param context Application context to access resources - * @param conditionCode The weather condition code - * @return The resource name if a valid condition code is passed, empty string otherwise + * + * @param context + * Application context to access resources + * @param conditionCode + * The weather condition code + * @return The resource name if a valid condition code is passed, empty string + * otherwise */ public static String resolveWeatherCondition(Context context, int conditionCode) { final Resources res = context.getResources(); - final int resId = res.getIdentifier("weather_" - + WeatherUtils.addOffsetToConditionCodeFromWeatherContract(conditionCode), "string", + final int resId = res.getIdentifier( + "weather_" + WeatherUtils.addOffsetToConditionCodeFromWeatherContract(conditionCode), "string", context.getPackageName()); if (resId != 0) { return res.getString(resId); @@ -90,10 +95,13 @@ public final class WeatherUtils { } /** - * Returns a string with the format xx% (where xx is the humidity value provided) - * @param humidity The humidity value - * @return The formatted string if a valid value is provided, "-" otherwise. Decimals are - * removed + * Returns a string with the format xx% (where xx is the humidity value + * provided) + * + * @param humidity + * The humidity value + * @return The formatted string if a valid value is provided, "-" otherwise. + * Decimals are removed */ public static String formatHumidity(double humidity) { return getFormattedValue(humidity, "%"); @@ -101,12 +109,16 @@ public final class WeatherUtils { /** * Returns a localized string of the speed and speed unit - * @param context Application context to access resources - * @param windSpeed The wind speed - * @param windSpeedUnit The speed unit. See - * {@link lineageos.providers.WeatherContract.WeatherColumns.WindSpeedUnit} + * + * @param context + * Application context to access resources + * @param windSpeed + * The wind speed + * @param windSpeedUnit + * The speed unit. See + * {@link lineageos.providers.WeatherContract.WeatherColumns.WindSpeedUnit} * @return The formatted string if a valid speed and speed unit a provided. - * {@link R.string#unknown} otherwise + * {@link R.string#unknown} otherwise */ public static String formatWindSpeed(Context context, double windSpeed, int windSpeedUnit) { if (windSpeed < 0) { @@ -115,13 +127,13 @@ public final class WeatherUtils { String localizedSpeedUnit; switch (windSpeedUnit) { - case WeatherContract.WeatherColumns.WindSpeedUnit.MPH: + case WeatherContract.WeatherColumns.WindSpeedUnit.MPH : localizedSpeedUnit = context.getString(R.string.weather_mph); break; - case WeatherContract.WeatherColumns.WindSpeedUnit.KPH: + case WeatherContract.WeatherColumns.WindSpeedUnit.KPH : localizedSpeedUnit = context.getString(R.string.weather_kph); break; - default: + default : return context.getString(R.string.unknown); } return getFormattedValue(windSpeed, localizedSpeedUnit); @@ -129,7 +141,9 @@ public final class WeatherUtils { /** * Helper method to convert miles to kilometers - * @param miles The value in miles + * + * @param miles + * The value in miles * @return The value in kilometers */ public static double milesToKilometers(double miles) { @@ -138,7 +152,9 @@ public final class WeatherUtils { /** * Helper method to convert kilometers to miles - * @param km The value in kilometers + * + * @param km + * The value in kilometers * @return The value in miles */ public static double kilometersToMiles(double km) { @@ -146,8 +162,11 @@ public final class WeatherUtils { } /** - * Adds an offset to the condition code reported by the active weather service provider. - * @param conditionCode The condition code from the Weather API + * Adds an offset to the condition code reported by the active weather service + * provider. + * + * @param conditionCode + * The condition code from the Weather API * @return A condition code that correctly maps to our resource IDs */ public static int addOffsetToConditionCodeFromWeatherContract(int conditionCode) { @@ -166,7 +185,9 @@ public final class WeatherUtils { /** * Checks if the Lineage Weather service is available in this device - * @param context Context to be used + * + * @param context + * Context to be used * @return true if service is available, false otherwise */ public static boolean isWeatherServiceAvailable(Context context) { diff --git a/app/src/main/java/foundation/e/blisslauncher/BlissLauncher.java b/app/src/main/java/foundation/e/blisslauncher/BlissLauncher.java index c808f8158c3333792d0deed7c4576598ce082850..114ae806d2de27025eeac5d363198c0910f99c91 100755 --- a/app/src/main/java/foundation/e/blisslauncher/BlissLauncher.java +++ b/app/src/main/java/foundation/e/blisslauncher/BlissLauncher.java @@ -8,7 +8,6 @@ import android.database.ContentObserver; import android.net.Uri; import android.os.Handler; import android.provider.Settings; - import foundation.e.blisslauncher.core.DeviceProfile; import foundation.e.blisslauncher.core.IconsHandler; import foundation.e.blisslauncher.core.blur.BlurWallpaperProvider; @@ -17,8 +16,7 @@ import foundation.e.blisslauncher.features.launcher.AppProvider; import foundation.e.blisslauncher.features.notification.NotificationService; public class BlissLauncher extends Application { - public static final Uri NOTIFICATION_BADGING_URI = - Settings.Secure.getUriFor("notification_badging"); + public static final Uri NOTIFICATION_BADGING_URI = Settings.Secure.getUriFor("notification_badging"); private IconsHandler iconsPackHandler; private DeviceProfile deviceProfile; @@ -32,8 +30,7 @@ public class BlissLauncher extends Application { public void onCreate() { super.onCreate(); sAppWidgetManager = AppWidgetManager.getInstance(getApplicationContext()); - sAppWidgetHost = new WidgetHost(getApplicationContext(), - R.id.APPWIDGET_HOST_ID); + sAppWidgetHost = new WidgetHost(getApplicationContext(), R.id.APPWIDGET_HOST_ID); sAppWidgetHost.startListening(); connectAppProvider(); @@ -45,16 +42,14 @@ public class BlissLauncher extends Application { onNotificationSettingsChanged(); } }; - getContentResolver().registerContentObserver( - NOTIFICATION_BADGING_URI, false, notificationSettingsObserver); + getContentResolver().registerContentObserver(NOTIFICATION_BADGING_URI, false, notificationSettingsObserver); } private void onNotificationSettingsChanged() { - boolean areNotificationDotsEnabled = Settings.Secure.getInt( - getContentResolver(), NOTIFICATION_BADGING_URI.getLastPathSegment(), 1) == 1; + boolean areNotificationDotsEnabled = Settings.Secure.getInt(getContentResolver(), + NOTIFICATION_BADGING_URI.getLastPathSegment(), 1) == 1; if (areNotificationDotsEnabled) { - NotificationService.requestRebind(new ComponentName( - this, NotificationService.class)); + NotificationService.requestRebind(new ComponentName(this, NotificationService.class)); } } diff --git a/app/src/main/java/foundation/e/blisslauncher/FixedScaleDrawable.java b/app/src/main/java/foundation/e/blisslauncher/FixedScaleDrawable.java index 1f40317c456baa88ec881e07e1fba851c9df438c..34d9190f5b680289887285e9d67d9954e33ef7f6 100644 --- a/app/src/main/java/foundation/e/blisslauncher/FixedScaleDrawable.java +++ b/app/src/main/java/foundation/e/blisslauncher/FixedScaleDrawable.java @@ -7,11 +7,11 @@ import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.DrawableWrapper; import android.os.Build; import android.util.AttributeSet; - import org.xmlpull.v1.XmlPullParser; /** - * Extension of {@link DrawableWrapper} which scales the child drawables by a fixed amount. + * Extension of {@link DrawableWrapper} which scales the child drawables by a + * fixed amount. */ @TargetApi(Build.VERSION_CODES.N) public class FixedScaleDrawable extends DrawableWrapper { @@ -29,17 +29,18 @@ public class FixedScaleDrawable extends DrawableWrapper { @Override public void draw(Canvas canvas) { int saveCount = canvas.save(); - canvas.scale(mScaleX, mScaleY, - getBounds().exactCenterX(), getBounds().exactCenterY()); + canvas.scale(mScaleX, mScaleY, getBounds().exactCenterX(), getBounds().exactCenterY()); super.draw(canvas); canvas.restoreToCount(saveCount); } @Override - public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs) { } + public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs) { + } @Override - public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Resources.Theme theme) { } + public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Resources.Theme theme) { + } public void setScale(float scale) { float h = getIntrinsicHeight(); diff --git a/app/src/main/java/foundation/e/blisslauncher/core/AdaptiveIconGenerator.java b/app/src/main/java/foundation/e/blisslauncher/core/AdaptiveIconGenerator.java index 1eccc03f74f0660eff67dd7f420264b80e7738a4..6ad413fdd5206054cb538dbbdf0043577c377e4f 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/AdaptiveIconGenerator.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/AdaptiveIconGenerator.java @@ -1,5 +1,9 @@ package foundation.e.blisslauncher.core; +import static java.lang.Math.max; +import static java.lang.Math.min; +import static java.lang.Math.round; + import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; @@ -8,20 +12,15 @@ import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.util.Log; import android.util.SparseIntArray; - import androidx.annotation.NonNull; import androidx.core.graphics.ColorUtils; - import foundation.e.blisslauncher.FixedScaleDrawable; import foundation.e.blisslauncher.core.customviews.AdaptiveIconDrawableCompat; -import static java.lang.Math.max; -import static java.lang.Math.min; -import static java.lang.Math.round; - public class AdaptiveIconGenerator { - // Average number of derived colors (based on averages with ~100 icons and performance testing) + // Average number of derived colors (based on averages with ~100 icons and + // performance testing) private static final int NUMBER_OF_COLORS_GUESSTIMATE = 45; // Found after some experimenting, might be improved with some more testing @@ -106,16 +105,9 @@ public class AdaptiveIconGenerator { bitmap.getPixels(pixels, 0, width, 0, 0, width, height); /* - * Calculate the number of padding pixels around the actual icon (i) - * +----------------+ - * | top | - * +---+--------+---+ - * | | | | - * | l | i | r | - * | | | | - * +---+--------+---+ - * | bottom | - * +----------------+ + * Calculate the number of padding pixels around the actual icon (i) + * +----------------+ | top | +---+--------+---+ | | | | | l | i | r | | | | | + * +---+--------+---+ | bottom | +----------------+ */ float adjHeight = height - bounds.top - bounds.bottom; float l = bounds.left * width * adjHeight; @@ -124,9 +116,12 @@ public class AdaptiveIconGenerator { float bottom = bounds.bottom * height * width; int addPixels = round(l + top + r + bottom); - // Any icon with less than 10% transparent pixels (padding excluded) is considered "full-bleed-ish" + // Any icon with less than 10% transparent pixels (padding excluded) is + // considered + // "full-bleed-ish" final int maxTransparent = (int) (round(size * .10) + addPixels); - // Any icon with less than 27% transparent pixels (padding excluded) doesn't need a color mix-in + // Any icon with less than 27% transparent pixels (padding excluded) doesn't + // need a color mix-in final int noMixinScore = (int) (round(size * .27) + addPixels); int highScore = 0; @@ -159,15 +154,17 @@ public class AdaptiveIconGenerator { // add back the alpha channel bestRGB |= 0xff << 24; - // not yet checked = not set to false = has to be full bleed, isBackgroundWhite = true = is adaptive + // not yet checked = not set to false = has to be full bleed, isBackgroundWhite + // = true = is + // adaptive isFullBleed |= !fullBleedChecked && !isBackgroundWhite; // return early if a mix-in isnt needed noMixinNeeded = !isFullBleed && !isBackgroundWhite && almostSquarish && transparentScore <= noMixinScore; // Currently, it's set to true so a white background is used for all the icons. - if(useWhiteBackground) { - //backgroundColor = Color.WHITE; + if (useWhiteBackground) { + // backgroundColor = Color.WHITE; backgroundColor = Color.WHITE & 0x80FFFFFF; onExitLoop(); return; @@ -194,7 +191,8 @@ public class AdaptiveIconGenerator { // Apply light background to mostly dark icons boolean veryDark = lightness < .35 && singleColor; - // Adjust color to reach suitable contrast depending on the relationship between the colors + // Adjust color to reach suitable contrast depending on the relationship between + // the colors final int opaqueSize = size - transparentScore; final float pxPerColor = opaqueSize / (float) numColors; float mixRatio = min(max(pxPerColor / highScore, .15f), .7f); @@ -211,10 +209,7 @@ public class AdaptiveIconGenerator { } private Drawable genResult() { - AdaptiveIconDrawableCompat tmp = new AdaptiveIconDrawableCompat( - new ColorDrawable(), - new FixedScaleDrawable() - ); + AdaptiveIconDrawableCompat tmp = new AdaptiveIconDrawableCompat(new ColorDrawable(), new FixedScaleDrawable()); ((FixedScaleDrawable) tmp.getForeground()).setDrawable(icon); if (isFullBleed || noMixinNeeded) { float scale; diff --git a/app/src/main/java/foundation/e/blisslauncher/core/AdaptiveIconProvider.java b/app/src/main/java/foundation/e/blisslauncher/core/AdaptiveIconProvider.java index 7986be8021095f016e2baa5a0c11f918600ed24c..1c1a549e7f268cfca66b364b635378599614d64b 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/AdaptiveIconProvider.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/AdaptiveIconProvider.java @@ -28,18 +28,16 @@ public class AdaptiveIconProvider { public Drawable load(Context context, String packageName) { if (context == null) { - throw new IllegalStateException( - "Loader.with(Context) must be called before loading an icon."); + throw new IllegalStateException("Loader.with(Context) must be called before loading an icon."); } - PackageManager packageManager = context.getPackageManager(); Drawable background = null, foreground = null; try { Resources resources = packageManager.getResourcesForApplication(packageName); Resources.Theme theme = resources.newTheme(); - ResourceUtils.setFakeConfig(resources, 26); //Build.VERSION_CODES.O = 26 + ResourceUtils.setFakeConfig(resources, 26); // Build.VERSION_CODES.O = 26 AssetManager assetManager = resources.getAssets(); @@ -52,15 +50,13 @@ public class AdaptiveIconProvider { String matcher = "application"; while ((eventType = manifestParser.nextToken()) != XmlPullParser.END_DOCUMENT) { - if (eventType == XmlPullParser.START_TAG && manifestParser.getName().equals( - matcher)) { + if (eventType == XmlPullParser.START_TAG && manifestParser.getName().equals(matcher)) { Log.d(TAG, "Manifest Parser Count: " + manifestParser.getAttributeCount()); for (int i = 0; i < manifestParser.getAttributeCount(); i++) { Log.d(TAG, "Icon parser: " + manifestParser.getAttributeName(i)); if (manifestParser.getAttributeName(i).equalsIgnoreCase("icon")) { - iconId = Integer.parseInt( - manifestParser.getAttributeValue(i).substring(1)); + iconId = Integer.parseInt(manifestParser.getAttributeValue(i).substring(1)); Log.d(TAG, "Iconid:" + iconId); break; } @@ -91,58 +87,46 @@ public class AdaptiveIconProvider { } } - /*for (int dir = 0; dir < IC_DIRS.length && parser == null; dir++) { - for (int config = 0; config < IC_CONFIGS.length && parser == null; config++) { - for (String name : (iconName != null && !iconName.equals("ic_launcher")) - ? new String[]{iconName, "ic_launcher", "ic_launcher_round"} : new String[]{"ic_launcher", "ic_launcher_round"}) { - try { - String path = "res/" + IC_DIRS[dir] + IC_CONFIGS[config] + "/" + name - + ".xml"; - Log.i(TAG, "path: " + path); - parser = assetManager.openXmlResourceParser(path); - } catch (Exception e) { - e.printStackTrace(); - } - - if (parser != null) { - break; - } - } - } - }*/ + /* + * for (int dir = 0; dir < IC_DIRS.length && parser == null; dir++) { for (int + * config = 0; config < IC_CONFIGS.length && parser == null; config++) { for + * (String name : (iconName != null && !iconName.equals("ic_launcher")) ? new + * String[]{iconName, "ic_launcher", "ic_launcher_round"} : new + * String[]{"ic_launcher", "ic_launcher_round"}) { try { String path = "res/" + + * IC_DIRS[dir] + IC_CONFIGS[config] + "/" + name + ".xml"; Log.i(TAG, "path: " + * + path); parser = assetManager.openXmlResourceParser(path); } catch + * (Exception e) { e.printStackTrace(); } + * + * if (parser != null) { break; } } } } + */ int backgroundRes = -1, foregroundRes = -1; if (parser != null) { int event; while ((event = parser.getEventType()) != XmlPullParser.END_DOCUMENT) { - Log.i(TAG, packageName + ":parserName: " + parser.getName() + " " - + parser.getAttributeCount()); + Log.i(TAG, packageName + ":parserName: " + parser.getName() + " " + parser.getAttributeCount()); if (event == XmlPullParser.START_TAG) { switch (parser.getName()) { - case "background": + case "background" : try { backgroundRes = parser.getAttributeResourceValue( - "http://schemas.android.com/apk/res/android", - "drawable", 0); + "http://schemas.android.com/apk/res/android", "drawable", 0); } catch (Exception e) { try { backgroundRes = parser.getAttributeResourceValue( - "http://schemas.android.com/apk/res/android", - "mipmap", 0); + "http://schemas.android.com/apk/res/android", "mipmap", 0); } catch (Exception ignored) { } } break; - case "foreground": + case "foreground" : try { foregroundRes = parser.getAttributeResourceValue( - "http://schemas.android.com/apk/res/android", - "drawable", 0); + "http://schemas.android.com/apk/res/android", "drawable", 0); } catch (Exception e) { try { foregroundRes = parser.getAttributeResourceValue( - "http://schemas.android.com/apk/res/android", - "mipmap", 0); + "http://schemas.android.com/apk/res/android", "mipmap", 0); } catch (Exception ignored) { } } @@ -162,18 +146,14 @@ public class AdaptiveIconProvider { background = ResourcesCompat.getDrawable(resources, backgroundRes, theme); } catch (Resources.NotFoundException e) { e.printStackTrace(); - /*try { - background = ResourcesCompat.getDrawable(resources, - resources.getIdentifier("ic_launcher_background", "mipmap", - packageName), theme); - } catch (Resources.NotFoundException e1) { - try { - background = ResourcesCompat.getDrawable(resources, - resources.getIdentifier("ic_launcher_background", "drawable", - packageName), theme); - } catch (Resources.NotFoundException ignored) { - } - }*/ + /* + * try { background = ResourcesCompat.getDrawable(resources, + * resources.getIdentifier("ic_launcher_background", "mipmap", packageName), + * theme); } catch (Resources.NotFoundException e1) { try { background = + * ResourcesCompat.getDrawable(resources, + * resources.getIdentifier("ic_launcher_background", "drawable", packageName), + * theme); } catch (Resources.NotFoundException ignored) { } } + */ } } @@ -182,18 +162,14 @@ public class AdaptiveIconProvider { foreground = ResourcesCompat.getDrawable(resources, foregroundRes, theme); } catch (Resources.NotFoundException e) { e.printStackTrace(); - /*try { - foreground = ResourcesCompat.getDrawable(resources, - resources.getIdentifier("ic_launcher_foreground", "mipmap", - packageName), theme); - } catch (Resources.NotFoundException e1) { - try { - foreground = ResourcesCompat.getDrawable(resources, - resources.getIdentifier("ic_launcher_foreground", "drawable", - packageName), theme); - } catch (Resources.NotFoundException ignored) { - } - }*/ + /* + * try { foreground = ResourcesCompat.getDrawable(resources, + * resources.getIdentifier("ic_launcher_foreground", "mipmap", packageName), + * theme); } catch (Resources.NotFoundException e1) { try { foreground = + * ResourcesCompat.getDrawable(resources, + * resources.getIdentifier("ic_launcher_foreground", "drawable", packageName), + * theme); } catch (Resources.NotFoundException ignored) { } } + */ } } } catch (Exception e) { diff --git a/app/src/main/java/foundation/e/blisslauncher/core/Alarm.java b/app/src/main/java/foundation/e/blisslauncher/core/Alarm.java index 4aa4694c96f88165ef0e722ccb6380c52b7d503d..2e9014a254b5fe04f337ac4eacc5fb9dbb5d52bf 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/Alarm.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/Alarm.java @@ -7,7 +7,8 @@ public class Alarm implements Runnable { // if we reach this time and the alarm hasn't been cancelled, call the listener private long mAlarmTriggerTime; - // if we've scheduled a call to run() (ie called mHandler.postDelayed), this variable is true. + // if we've scheduled a call to run() (ie called mHandler.postDelayed), this + // variable is true. // We use this to avoid having multiple pending callbacks private boolean mWaitingForCallback; @@ -23,7 +24,8 @@ public class Alarm implements Runnable { mAlarmListener = alarmListener; } - // Sets the alarm to go off in a certain number of milliseconds. If the alarm is already set, + // Sets the alarm to go off in a certain number of milliseconds. If the alarm is + // already set, // it's overwritten and only the new alarm setting is used public void setAlarm(long millisecondsInFuture) { long currentTime = SystemClock.uptimeMillis(); diff --git a/app/src/main/java/foundation/e/blisslauncher/core/ColorExtractor.java b/app/src/main/java/foundation/e/blisslauncher/core/ColorExtractor.java index f3b4b69798226f07974eb3f528109deed06dc5b0..a599dc040db360826ced2e28aed41866562af53f 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/ColorExtractor.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/ColorExtractor.java @@ -1,6 +1,5 @@ package foundation.e.blisslauncher.core; - /* * Copyright (C) 2017 The Android Open Source Project * @@ -22,15 +21,11 @@ import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.util.SparseArray; - import java.util.HashSet; import java.util.Set; - import kotlin.collections.ArraysKt; -/** - * Utility class for extracting colors from a bitmap. - */ +/** Utility class for extracting colors from a bitmap. */ public class ColorExtractor { private static final String TAG = "ColorExtractor"; @@ -40,10 +35,13 @@ public class ColorExtractor { } /** - * This picks a dominant color, looking for high-saturation, high-value, repeated hues. + * This picks a dominant color, looking for high-saturation, high-value, + * repeated hues. * - * @param bitmap The bitmap to scan - * @param samples The approximate max number of samples to use. + * @param bitmap + * The bitmap to scan + * @param samples + * The approximate max number of samples to use. */ public static int findDominantColorByHue(Bitmap bitmap, int samples) { final int height = bitmap.getHeight(); @@ -57,7 +55,8 @@ public class ColorExtractor { float[] hsv = new float[3]; // First get the best hue, by creating a histogram over 360 hue buckets, - // where each pixel contributes a score weighted by saturation, value, and alpha. + // where each pixel contributes a score weighted by saturation, value, and + // alpha. float[] hueScoreHistogram = new float[360]; float highScore = -1; int bestHue = -1; @@ -124,7 +123,8 @@ public class ColorExtractor { } public static boolean isSingleColor(Drawable drawable, int color) { - if (drawable == null) return true; + if (drawable == null) + return true; final int testColor = posterize(color); if (drawable instanceof ColorDrawable) { return posterize(((ColorDrawable) drawable).getColor()) == testColor; @@ -154,8 +154,10 @@ public class ColorExtractor { /* * References: - * https://www.cs.umb.edu/~jreyes/csit114-fall-2007/project4/filters.html#posterize - * https://github.com/gitgraghu/image-processing/blob/master/src/Effects/Posterize.java + * https://www.cs.umb.edu/~jreyes/csit114-fall-2007/project4/filters.html# + * posterize + * https://github.com/gitgraghu/image-processing/blob/master/src/Effects/ + * Posterize.java */ public static int posterize(int rgb) { int red = (0xff & (rgb >> 16)); diff --git a/app/src/main/java/foundation/e/blisslauncher/core/DeviceProfile.java b/app/src/main/java/foundation/e/blisslauncher/core/DeviceProfile.java index efa4d261fc80d3515e353ef039cc9fc10f06c363..cdf665b85a3383b97a31253fe43517be5b65ec37 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/DeviceProfile.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/DeviceProfile.java @@ -80,7 +80,7 @@ public class DeviceProfile { public int dateTextBottomPadding; public int dateTextTopPadding; - //Uninstall icon + // Uninstall icon public int uninstallIconSizePx; public int uninstallIconPadding; @@ -88,7 +88,7 @@ public class DeviceProfile { public int cellHeightPx; public int workspaceCellPaddingXPx; - //Widget + // Widget public int maxWidgetWidth; public int maxWidgetHeight; @@ -172,8 +172,7 @@ public class DeviceProfile { statusBarHeight = res.getDimensionPixelSize(resourceId); } - ComponentName cn = new ComponentName(context.getPackageName(), - this.getClass().getName()); + ComponentName cn = new ComponentName(context.getPackageName(), this.getClass().getName()); pageIndicatorSizePx = Utilities.pxFromDp(8, dm); pageIndicatorTopPaddingPx = Utilities.pxFromDp(8, dm); @@ -187,32 +186,32 @@ public class DeviceProfile { // Calculate all of the remaining variables. updateAvailableDimensions(dm, res); - /* // Now that we have all of the variables calculated, we can tune certain sizes. - float aspectRatio = ((float) Math.max(widthPx, heightPx)) / Math.min(widthPx, heightPx); - boolean isTallDevice = Float.compare(aspectRatio, TALL_DEVICE_ASPECT_RATIO_THRESHOLD) >= 0; - if (isTallDevice) { - // We increase the hotseat size when there is extra space. - // ie. For a display with a large aspect ratio, we can keep the icons on the workspace - // in portrait mode closer together by adding more height to the hotseat. - // Note: This calculation was created after noticing a pattern in the design spec. - int extraSpace = getCellSize().y - iconSizePx - iconDrawablePaddingPx; - hotseatBarSizePx += extraSpace - pageIndicatorSizePx; - - // Recalculate the available dimensions using the new hotseat size. - updateAvailableDimensions(dm, res); - }*/ + /* + * // Now that we have all of the variables calculated, we can tune certain + * sizes. float aspectRatio = ((float) Math.max(widthPx, heightPx)) / + * Math.min(widthPx, heightPx); boolean isTallDevice = + * Float.compare(aspectRatio, TALL_DEVICE_ASPECT_RATIO_THRESHOLD) >= 0; if + * (isTallDevice) { // We increase the hotseat size when there is extra space. + * // ie. For a display with a large aspect ratio, we can keep the icons on the + * workspace // in portrait mode closer together by adding more height to the + * hotseat. // Note: This calculation was created after noticing a pattern in + * the design spec. int extraSpace = getCellSize().y - iconSizePx - + * iconDrawablePaddingPx; hotseatBarSizePx += extraSpace - pageIndicatorSizePx; + * + * // Recalculate the available dimensions using the new hotseat size. + * updateAvailableDimensions(dm, res); } + */ } - private void updateAvailableDimensions(DisplayMetrics dm, Resources res) { updateIconSize(1f, res, dm); - // Check to see if the icons fit within the available height. If not, then scale down. + // Check to see if the icons fit within the available height. If not, then scale + // down. int usedHeight = (cellHeightPx * numRows); - int remainHeight = - (availableHeightPx - usedHeight - hotseatCellHeightPx - pageIndicatorSizePx - - pageIndicatorTopPaddingPx - pageIndicatorBottomPaddingPx); + int remainHeight = (availableHeightPx - usedHeight - hotseatCellHeightPx - pageIndicatorSizePx + - pageIndicatorTopPaddingPx - pageIndicatorBottomPaddingPx); int incrementHeight = remainHeight / (numRows + 1); cellHeightPx = cellHeightPx + incrementHeight; hotseatCellHeightPx = hotseatCellHeightPx + incrementHeight; @@ -221,17 +220,12 @@ public class DeviceProfile { private void updateIconSize(float scale, Resources res, DisplayMetrics dm) { // Workspace - /*if (availableWidthPx < 640) { - iconSizePx = 95; - } else if (availableWidthPx < 960) { - iconSizePx = 126; - } else if (availableWidthPx < 1100) { - iconSizePx = 160; - } else if (availableWidthPx < 1200) { - iconSizePx = 190; - } else { - iconSizePx = 213; - }*/ + /* + * if (availableWidthPx < 640) { iconSizePx = 95; } else if (availableWidthPx < + * 960) { iconSizePx = 126; } else if (availableWidthPx < 1100) { iconSizePx = + * 160; } else if (availableWidthPx < 1200) { iconSizePx = 190; } else { + * iconSizePx = 213; } + */ float a = 1.578f; float b = 1.23f; @@ -241,9 +235,9 @@ public class DeviceProfile { iconDrawablePaddingPx = (availableWidthPx - iconSizePx * 4) / 5; int tempUninstallIconSize = iconSizePx * 72 / 192; - uninstallIconSizePx = - (tempUninstallIconSize > iconDrawablePaddingPx) ? iconDrawablePaddingPx - : tempUninstallIconSize; + uninstallIconSizePx = (tempUninstallIconSize > iconDrawablePaddingPx) + ? iconDrawablePaddingPx + : tempUninstallIconSize; uninstallIconPadding = iconSizePx * 10 / 192; calendarIconWidth = iconSizePx; @@ -252,10 +246,10 @@ public class DeviceProfile { dateTextviewHeight = iconSizePx * 152 / 192; dateTextSize = iconSizePx * 154 / 192; - dateTextTopPadding = (dateTextviewHeight - (int) (1.14 * Utilities.calculateTextHeight( - (float) dateTextSize / 2))) / 2; - dateTextBottomPadding = (dateTextviewHeight - (int) (0.86 * Utilities.calculateTextHeight( - (float) dateTextSize / 2))) / 2; + dateTextTopPadding = (dateTextviewHeight + - (int) (1.14 * Utilities.calculateTextHeight((float) dateTextSize / 2))) / 2; + dateTextBottomPadding = (dateTextviewHeight + - (int) (0.86 * Utilities.calculateTextHeight((float) dateTextSize / 2))) / 2; cellHeightWithoutPaddingPx = iconSizePx + Utilities.pxFromDp(4, dm) + Utilities.calculateTextHeight(iconTextSizePx); @@ -268,8 +262,7 @@ public class DeviceProfile { hotseatCellHeightPx = hotseatCellHeightWithoutPaddingPx + iconDrawablePaddingPx; numRows = (availableHeightPx - Utilities.pxFromDp(8, dm) - pageIndicatorTopPaddingPx - - pageIndicatorBottomPaddingPx - - pageIndicatorSizePx - hotseatCellHeightPx) / cellHeightPx; + - pageIndicatorBottomPaddingPx - pageIndicatorSizePx - hotseatCellHeightPx) / cellHeightPx; maxAppsPerPage = numColumns * numRows; @@ -282,7 +275,6 @@ public class DeviceProfile { maxWidgetHeight = getWorkspaceHeight(); } - public static int calculateCellWidth(int width, int countX) { return width / countX; } @@ -321,13 +313,13 @@ public class DeviceProfile { public int getCellHeight(int containerType) { switch (containerType) { - case TYPE_WORKSPACE: + case TYPE_WORKSPACE : return cellHeightPx; - case TYPE_FOLDER: + case TYPE_FOLDER : return folderCellHeightPx; - case TYPE_HOTSEAT: + case TYPE_HOTSEAT : return hotseatCellHeightPx; - default: + default : // ?? return 0; } @@ -341,8 +333,7 @@ public class DeviceProfile { } public Path getRoundedCornerPath(int iconSize) { - return resizePath(PathParser.createPathFromPathData(AdaptiveIconUtils.getMaskPath()), - iconSize, iconSize); + return resizePath(PathParser.createPathFromPathData(AdaptiveIconUtils.getMaskPath()), iconSize, iconSize); } private Path resizePath(Path path, int width, int height) { @@ -388,20 +379,13 @@ public class DeviceProfile { private int getLauncherIconDensity(int requiredSize) { // Densities typically defined by an app. - int[] densityBuckets = new int[]{ - DisplayMetrics.DENSITY_LOW, - DisplayMetrics.DENSITY_MEDIUM, - DisplayMetrics.DENSITY_TV, - DisplayMetrics.DENSITY_HIGH, - DisplayMetrics.DENSITY_XHIGH, - DisplayMetrics.DENSITY_XXHIGH, - DisplayMetrics.DENSITY_XXXHIGH - }; + int[] densityBuckets = new int[]{DisplayMetrics.DENSITY_LOW, DisplayMetrics.DENSITY_MEDIUM, + DisplayMetrics.DENSITY_TV, DisplayMetrics.DENSITY_HIGH, DisplayMetrics.DENSITY_XHIGH, + DisplayMetrics.DENSITY_XXHIGH, DisplayMetrics.DENSITY_XXXHIGH}; int density = DisplayMetrics.DENSITY_XXXHIGH; for (int i = densityBuckets.length - 1; i >= 0; i--) { - float expectedSize = ICON_SIZE_DEFINED_IN_APP_DP * densityBuckets[i] - / DisplayMetrics.DENSITY_DEFAULT; + float expectedSize = ICON_SIZE_DEFINED_IN_APP_DP * densityBuckets[i] / DisplayMetrics.DENSITY_DEFAULT; if (expectedSize >= requiredSize) { density = densityBuckets[i]; } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/IconsHandler.java b/app/src/main/java/foundation/e/blisslauncher/core/IconsHandler.java index 83bd9fa9d90ac9929db0a507790f82d1bc062d0e..c5b9f9801c4be3bde38484586c829e06a71d3f55 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/IconsHandler.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/IconsHandler.java @@ -36,7 +36,8 @@ import foundation.e.blisslauncher.core.utils.GraphicsUtil; import foundation.e.blisslauncher.core.utils.UserHandle; /** - * Inspired from http://stackoverflow.com/questions/31490630/how-to-load-icon-from-icon-pack + * Inspired from + * http://stackoverflow.com/questions/31490630/how-to-load-icon-from-icon-pack */ public class IconsHandler { @@ -70,26 +71,24 @@ public class IconsHandler { loadIconsPack("foundation.e.blissiconpack"); } - private boolean iconPackExists(PackageManager packageManager) { try { - packageManager.getPackageInfo("foundation.e.blissiconpack", - PackageManager.GET_META_DATA); + packageManager.getPackageInfo("foundation.e.blissiconpack", PackageManager.GET_META_DATA); } catch (PackageManager.NameNotFoundException e) { return false; } return true; } - /** * Parse icons pack metadata * - * @param packageName Android package ID of the package to parse + * @param packageName + * Android package ID of the package to parse */ public void loadIconsPack(String packageName) { - //clear icons pack + // clear icons pack if (iconPackExists(pm)) { iconsPackPackageName = packageName; } else { @@ -114,10 +113,8 @@ public class IconsHandler { NodeList items = doc.getElementsByTagName("item"); for (int i = 0; i < items.getLength(); i++) { Node item = items.item(i); - String componentName = item.getAttributes().getNamedItem( - "component").getTextContent(); - String drawableName = item.getAttributes().getNamedItem( - "drawable").getTextContent(); + String componentName = item.getAttributes().getNamedItem("component").getTextContent(); + String drawableName = item.getAttributes().getNamedItem("drawable").getTextContent(); if (!packagesDrawables.containsKey(componentName)) { packagesDrawables.put(componentName, drawableName); @@ -131,37 +128,34 @@ public class IconsHandler { } - private Drawable getDefaultAppDrawable(LauncherActivityInfo activityInfo, UserHandle userHandle) { return activityInfo.getIcon(0); } public boolean isClock(String componentName) { - return packagesDrawables.get(componentName) != null && - packagesDrawables.get(componentName).equals("clock"); + return packagesDrawables.get(componentName) != null && packagesDrawables.get(componentName).equals("clock"); } public boolean isCalendar(String componentName) { - return packagesDrawables.get(componentName) != null && - packagesDrawables.get(componentName).equals("calendar"); + return packagesDrawables.get(componentName) != null && packagesDrawables.get(componentName).equals("calendar"); } - /** * Get or generate icon for an app */ public Drawable getDrawableIconForPackage(LauncherActivityInfo activityInfo, UserHandle userHandle) { - /* // system icons, nothing to do - if (iconsPackPackageName.equalsIgnoreCase("default")) { - return this.getDefaultAppDrawable(componentName, userHandle); - }*/ + /* + * // system icons, nothing to do if + * (iconsPackPackageName.equalsIgnoreCase("default")) { return + * this.getDefaultAppDrawable(componentName, userHandle); } + */ ComponentName componentName = activityInfo.getComponentName(); String drawable = packagesDrawables.get(activityInfo.getComponentName().toString()); - if (drawable != null) { //there is a custom icon + if (drawable != null) { // there is a custom icon int id = iconPackres.getIdentifier(drawable, "drawable", iconsPackPackageName); if (id > 0) { - //noinspection deprecation: Resources.getDrawable(int, Theme) requires SDK 21+ + // noinspection deprecation: Resources.getDrawable(int, Theme) requires SDK 21+ try { return getBadgedIcon(iconPackres.getDrawable(id), activityInfo.getUser()); } catch (Resources.NotFoundException e) { @@ -181,19 +175,19 @@ public class IconsHandler { systemIcon = this.getDefaultAppDrawable(activityInfo, userHandle); if (Utilities.ATLEAST_OREO && systemIcon instanceof AdaptiveIconDrawable) { - systemIcon = new AdaptiveIconDrawableCompat( - ((AdaptiveIconDrawable) systemIcon).getBackground(), + systemIcon = new AdaptiveIconDrawableCompat(((AdaptiveIconDrawable) systemIcon).getBackground(), ((AdaptiveIconDrawable) systemIcon).getForeground()); return systemIcon; } else { // Icon is not adaptive, try to load using reflection. - Drawable adaptiveIcon = new AdaptiveIconProvider().load(ctx, - componentName.getPackageName()); + Drawable adaptiveIcon = new AdaptiveIconProvider().load(ctx, componentName.getPackageName()); if (adaptiveIcon != null) { systemIcon = adaptiveIcon; } else { - // Failed to load adaptive icon, Generate an adaptive icon from app default icon. - systemIcon = new AdaptiveIconGenerator(ctx, getDefaultAppDrawable(activityInfo, userHandle)).getResult(); + // Failed to load adaptive icon, Generate an adaptive icon from app default + // icon. + systemIcon = new AdaptiveIconGenerator(ctx, getDefaultAppDrawable(activityInfo, userHandle)) + .getResult(); } } @@ -202,30 +196,28 @@ public class IconsHandler { return badgedIcon; } - public void resetIconDrawableForPackage(ComponentName componentName, UserHandle userHandle) { if (!packagesDrawables.containsKey(componentName.toString())) { LauncherApps launcherApps = (LauncherApps) ctx.getSystemService(Context.LAUNCHER_APPS_SERVICE); - for (LauncherActivityInfo launcherActivityInfo : launcherApps.getActivityList(componentName.getPackageName(), userHandle.getRealHandle())) { + for (LauncherActivityInfo launcherActivityInfo : launcherApps + .getActivityList(componentName.getPackageName(), userHandle.getRealHandle())) { if (launcherActivityInfo.getComponentName().flattenToString().equals(componentName.flattenToString())) { Drawable icon = this.getDefaultAppDrawable(launcherActivityInfo, userHandle); if (Utilities.ATLEAST_OREO && icon instanceof AdaptiveIconDrawable) { - icon = new AdaptiveIconDrawableCompat( - ((AdaptiveIconDrawable) icon).getBackground(), + icon = new AdaptiveIconDrawableCompat(((AdaptiveIconDrawable) icon).getBackground(), ((AdaptiveIconDrawable) icon).getForeground()); } else { - Drawable adaptiveIcon = new AdaptiveIconProvider().load(ctx, - componentName.getPackageName()); + Drawable adaptiveIcon = new AdaptiveIconProvider().load(ctx, componentName.getPackageName()); if (adaptiveIcon != null) { icon = adaptiveIcon; } else { - icon = graphicsUtil.convertToRoundedCorner(ctx, - graphicsUtil.addBackground(icon, false)); + icon = graphicsUtil.convertToRoundedCorner(ctx, graphicsUtil.addBackground(icon, false)); } } Drawable badgedIcon = getBadgedIcon(icon, launcherActivityInfo.getUser()); - cacheStoreDrawable(userHandle.addUserSuffixToString(componentName.flattenToString(), '/'), badgedIcon); + cacheStoreDrawable(userHandle.addUserSuffixToString(componentName.flattenToString(), '/'), + badgedIcon); } } } @@ -255,8 +247,8 @@ public class IconsHandler { } private Bitmap getBitmapFromDrawable(Drawable drawable) { - final Bitmap bmp = Bitmap.createBitmap(drawable.getIntrinsicWidth(), - drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); + final Bitmap bmp = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), + Bitmap.Config.ARGB_8888); final Canvas canvas = new Canvas(bmp); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); @@ -272,8 +264,7 @@ public class IconsHandler { FileInputStream fis; try { fis = new FileInputStream(cacheGetFileName(key)); - BitmapDrawable drawable = - new BitmapDrawable(this.ctx.getResources(), BitmapFactory.decodeStream(fis)); + BitmapDrawable drawable = new BitmapDrawable(this.ctx.getResources(), BitmapFactory.decodeStream(fis)); fis.close(); return drawable; } catch (Exception e) { @@ -291,7 +282,6 @@ public class IconsHandler { return new File(getIconsCacheDir() + File.separator + iconsPackPackageName + "_" + key.hashCode() + ".png"); } - /** * returns icons cache directory. */ @@ -323,19 +313,17 @@ public class IconsHandler { } /** - * Returns a drawable suitable for the all apps view. If the package or the resource do not - * exist, it returns null. + * Returns a drawable suitable for the all apps view. If the package or the + * resource do not exist, it returns null. */ - public static Drawable createIconDrawable(Intent.ShortcutIconResource iconRes, - Context context) { + public static Drawable createIconDrawable(Intent.ShortcutIconResource iconRes, Context context) { PackageManager packageManager = context.getPackageManager(); // the resource try { Resources resources = packageManager.getResourcesForApplication(iconRes.packageName); if (resources != null) { final int id = resources.getIdentifier(iconRes.resourceName, null, null); - return resources.getDrawableForDensity( - id, + return resources.getDrawableForDensity(id, BlissLauncher.getApplication(context).getDeviceProfile().fillResIconDpi); } } catch (Exception e) { @@ -345,15 +333,16 @@ public class IconsHandler { } /** - * Returns a drawable which is of the appropriate size to be displayed as an icon + * Returns a drawable which is of the appropriate size to be displayed as an + * icon */ public static Drawable createIconDrawable(Bitmap icon, Context context) { return new BitmapDrawable(icon); } public Drawable getFullResDefaultActivityIcon() { - return getFullResIcon(Resources.getSystem(), Utilities.ATLEAST_OREO ? - android.R.drawable.sym_def_app_icon : android.R.mipmap.sym_def_app_icon); + return getFullResIcon(Resources.getSystem(), + Utilities.ATLEAST_OREO ? android.R.drawable.sym_def_app_icon : android.R.mipmap.sym_def_app_icon); } private Drawable getFullResIcon(Resources resources, int iconId) { diff --git a/app/src/main/java/foundation/e/blisslauncher/core/UserManagerCompat.java b/app/src/main/java/foundation/e/blisslauncher/core/UserManagerCompat.java index a6866fdbb31f08c33e42245f9c63ea8abff0574a..2289c8f6ab482467b67ab0695daaca184070c696 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/UserManagerCompat.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/UserManagerCompat.java @@ -2,7 +2,6 @@ package foundation.e.blisslauncher.core; import android.content.Context; import android.os.UserHandle; - import java.util.List; public abstract class UserManagerCompat { @@ -29,17 +28,21 @@ public abstract class UserManagerCompat { } } - /** - * Creates a cache for users. - */ + /** Creates a cache for users. */ public abstract void enableAndResetCache(); public abstract List getUserProfiles(); + public abstract long getSerialNumberForUser(UserHandle user); + public abstract UserHandle getUserForSerialNumber(long serialNumber); + public abstract CharSequence getBadgedLabelForUser(CharSequence label, UserHandle user); + public abstract long getUserCreationTime(UserHandle user); + public abstract boolean isQuietModeEnabled(UserHandle user); + public abstract boolean isUserUnlocked(UserHandle user); public abstract boolean isDemoUser(); diff --git a/app/src/main/java/foundation/e/blisslauncher/core/UserManagerCompatVL.java b/app/src/main/java/foundation/e/blisslauncher/core/UserManagerCompatVL.java index ce8c8d08dbf144ec8f78922fd5994f5aeb850031..6b0a6d40d77aa22faa55554025807935e0bc1307 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/UserManagerCompatVL.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/UserManagerCompatVL.java @@ -6,14 +6,12 @@ import android.content.pm.PackageManager; import android.os.UserHandle; import android.os.UserManager; import android.util.ArrayMap; - +import foundation.e.blisslauncher.core.utils.Constants; +import foundation.e.blisslauncher.core.utils.LongArrayMap; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import foundation.e.blisslauncher.core.utils.Constants; -import foundation.e.blisslauncher.core.utils.LongArrayMap; - public class UserManagerCompatVL extends UserManagerCompat { protected final UserManager mUserManager; @@ -21,7 +19,8 @@ public class UserManagerCompatVL extends UserManagerCompat { private final Context mContext; protected LongArrayMap mUsers; - // Create a separate reverse map as LongArrayMap.indexOfValue checks if objects are same + // Create a separate reverse map as LongArrayMap.indexOfValue checks if objects + // are same // and not {@link Object#equals} protected ArrayMap mUserToSerialMap; @@ -108,7 +107,7 @@ public class UserManagerCompatVL extends UserManagerCompat { SharedPreferences prefs = Preferences.getPrefs(mContext); String key = Constants.USER_CREATION_TIME_KEY + getSerialNumberForUser(user); if (!prefs.contains(key)) { - Preferences.setUserCreationTime(mContext, key); + Preferences.setUserCreationTime(mContext, key); } return prefs.getLong(key, 0); } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/UserManagerCompatVM.java b/app/src/main/java/foundation/e/blisslauncher/core/UserManagerCompatVM.java index 053cfd4827bd3e4adda7b66ba6b40cfec5975ae4..6359c7c75383a4ac0e6708648f884464729fe4c0 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/UserManagerCompatVM.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/UserManagerCompatVM.java @@ -16,4 +16,4 @@ public class UserManagerCompatVM extends UserManagerCompatVL { public long getUserCreationTime(UserHandle user) { return mUserManager.getUserCreationTime(user); } -} \ No newline at end of file +} diff --git a/app/src/main/java/foundation/e/blisslauncher/core/Utilities.java b/app/src/main/java/foundation/e/blisslauncher/core/Utilities.java index 61ff7e5d1c768b9c19ddbbf59662f031f118b6e3..f8518544d7ef00adc54f5706a8af782ac6e1b173 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/Utilities.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/Utilities.java @@ -13,9 +13,6 @@ import android.util.Log; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; - -import org.apache.commons.lang3.StringUtils; - import java.io.ByteArrayOutputStream; import java.io.IOException; import java.lang.reflect.Method; @@ -28,33 +25,25 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; - +import org.apache.commons.lang3.StringUtils; public class Utilities { private static final String TAG = "Utilities"; - private static final Pattern sTrimPattern = - Pattern.compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$"); + private static final Pattern sTrimPattern = Pattern + .compile("^[\\s|\\p{javaSpaceChar}]*(.*)[\\s|\\p{javaSpaceChar}]*$"); - /** - * Use hard coded values to compile with android source. - */ - public static final boolean ATLEAST_R = - Build.VERSION.SDK_INT >= 30; + /** Use hard coded values to compile with android source. */ + public static final boolean ATLEAST_R = Build.VERSION.SDK_INT >= 30; - public static final boolean ATLEAST_OREO = - Build.VERSION.SDK_INT >= 26; + public static final boolean ATLEAST_OREO = Build.VERSION.SDK_INT >= 26; - public static final boolean ATLEAST_NOUGAT_MR1 = - Build.VERSION.SDK_INT >= 25; + public static final boolean ATLEAST_NOUGAT_MR1 = Build.VERSION.SDK_INT >= 25; - public static final boolean ATLEAST_NOUGAT = - Build.VERSION.SDK_INT >= 24; - - public static final boolean ATLEAST_MARSHMALLOW = - Build.VERSION.SDK_INT >= 23; + public static final boolean ATLEAST_NOUGAT = Build.VERSION.SDK_INT >= 24; + public static final boolean ATLEAST_MARSHMALLOW = Build.VERSION.SDK_INT >= 23; // These values are same as that in {@link AsyncTask}. private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); @@ -62,15 +51,13 @@ public class Utilities { private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1; private static final int KEEP_ALIVE = 1; /** - * An {@link Executor} to be used with async task with no limit on the queue size. + * An {@link Executor} to be used with async task with no limit on the queue + * size. */ - public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor( - CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, KEEP_ALIVE, - TimeUnit.SECONDS, new LinkedBlockingQueue()); + public static final Executor THREAD_POOL_EXECUTOR = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, + KEEP_ALIVE, TimeUnit.SECONDS, new LinkedBlockingQueue()); - /** - * Compresses the bitmap to a byte array for serialization. - */ + /** Compresses the bitmap to a byte array for serialization. */ public static byte[] flattenBitmap(Bitmap bitmap) { // Try go guesstimate how much space the icon will take when serialized // to avoid unnecessary allocations/copies during the write. @@ -87,13 +74,13 @@ public class Utilities { } } - public static float dpiFromPx(int size, DisplayMetrics metrics){ + public static float dpiFromPx(int size, DisplayMetrics metrics) { float densityRatio = (float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT; return (size / densityRatio); } + public static int pxFromDp(float size, DisplayMetrics metrics) { - return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, - size, metrics)); + return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, size, metrics)); } public static float pxFromDp(int dp, Context context) { @@ -102,13 +89,10 @@ public class Utilities { } public static int pxFromSp(float size, DisplayMetrics metrics) { - return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, - size, metrics)); + return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, size, metrics)); } - /** - * Calculates the height of a given string at a specific text size. - */ + /** Calculates the height of a given string at a specific text size. */ public static int calculateTextHeight(float textSizePx) { Paint p = new Paint(); p.setTextSize(textSizePx); @@ -117,21 +101,22 @@ public class Utilities { } public static String convertMonthToString() { - Calendar cal=Calendar.getInstance(); + Calendar cal = Calendar.getInstance(); SimpleDateFormat month_date = new SimpleDateFormat("MMM"); return month_date.format(cal.getTime()); } /** - * Trims the string, removing all whitespace at the beginning and end of the string. - * Non-breaking whitespaces are also removed. + * Trims the string, removing all whitespace at the beginning and end of the + * string. Non-breaking whitespaces are also removed. */ public static String trim(CharSequence s) { if (s == null) { return null; } - // Just strip any sequence of whitespace or java space characters from the beginning and end + // Just strip any sequence of whitespace or java space characters from the + // beginning and end Matcher m = sTrimPattern.matcher(s); return m.replaceAll("$1"); } @@ -212,19 +197,18 @@ public class Utilities { } /** - * Utility method to determine whether the given point, in local coordinates, - * is inside the view, where the area of the view is expanded by the slop factor. - * This method is called while processing touch-move events to determine if the event - * is still within the view. + * Utility method to determine whether the given point, in local coordinates, is + * inside the view, where the area of the view is expanded by the slop factor. + * This method is called while processing touch-move events to determine if the + * event is still within the view. */ public static boolean pointInView(View v, float localX, float localY, float slop) { - return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) && - localY < (v.getHeight() + slop); + return localX >= -slop && localY >= -slop && localX < (v.getWidth() + slop) && localY < (v.getHeight() + slop); } /** - * Ensures that a value is within given bounds. Specifically: - * If value is less than lowerBound, return lowerBound; else if value is greater than upperBound, + * Ensures that a value is within given bounds. Specifically: If value is less + * than lowerBound, return lowerBound; else if value is greater than upperBound, * return upperBound; else return value unchanged. */ public static int boundToRange(int value, int lowerBound, int upperBound) { diff --git a/app/src/main/java/foundation/e/blisslauncher/core/broadcast/ManagedProfileBroadcastReceiver.java b/app/src/main/java/foundation/e/blisslauncher/core/broadcast/ManagedProfileBroadcastReceiver.java index 94f511a2712da1b2021e0733748137f26e14ed0b..ddd9356205c27d6a1929776bf8c69dd0aca06807 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/broadcast/ManagedProfileBroadcastReceiver.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/broadcast/ManagedProfileBroadcastReceiver.java @@ -13,29 +13,31 @@ import foundation.e.blisslauncher.core.events.ForceReloadEvent; public class ManagedProfileBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { - Log.i("PROFILE", "onReceive: "+intent.getAction()); + Log.i("PROFILE", "onReceive: " + intent.getAction()); final String action = intent.getAction(); if (Intent.ACTION_MANAGED_PROFILE_ADDED.equals(action) || Intent.ACTION_MANAGED_PROFILE_REMOVED.equals(action)) { EventRelay.getInstance().push(new ForceReloadEvent()); - } else if (Intent.ACTION_MANAGED_PROFILE_AVAILABLE.equals(action) || - Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE.equals(action) || - Intent.ACTION_MANAGED_PROFILE_UNLOCKED.equals(action)) { + } else if (Intent.ACTION_MANAGED_PROFILE_AVAILABLE.equals(action) + || Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE.equals(action) + || Intent.ACTION_MANAGED_PROFILE_UNLOCKED.equals(action)) { UserHandle user = intent.getParcelableExtra(Intent.EXTRA_USER); if (user != null) { - /*if (Intent.ACTION_MANAGED_PROFILE_AVAILABLE.equals(action) || - Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE.equals(action)) { - //enqueueModelUpdateTask(new PackageUpdatedTask(PackageUpdatedTask.OP_USER_AVAILABILITY_CHANGE, user)); - } + /* + * if (Intent.ACTION_MANAGED_PROFILE_AVAILABLE.equals(action) || + * Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE.equals(action)) { + * //enqueueModelUpdateTask(new + * PackageUpdatedTask(PackageUpdatedTask.OP_USER_AVAILABILITY_CHANGE, user)); } + * + * // ACTION_MANAGED_PROFILE_UNAVAILABLE sends the profile back to locked mode, + * so // we need to run the state change task again. if + * (Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE.equals(action) || + * Intent.ACTION_MANAGED_PROFILE_UNLOCKED.equals(action)) { + * //enqueueModelUpdateTask(new UserLockStateChangedTask(user)); } + */ - // ACTION_MANAGED_PROFILE_UNAVAILABLE sends the profile back to locked mode, so - // we need to run the state change task again. - if (Intent.ACTION_MANAGED_PROFILE_UNAVAILABLE.equals(action) || - Intent.ACTION_MANAGED_PROFILE_UNLOCKED.equals(action)) { - //enqueueModelUpdateTask(new UserLockStateChangedTask(user)); - }*/ - - // TODO: Need to handle it more gracefully. Currently it just recreate the launcher. + // TODO: Need to handle it more gracefully. Currently it just recreate the + // launcher. EventRelay.getInstance().push(new ForceReloadEvent()); } } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/broadcast/PackageAddedRemovedHandler.java b/app/src/main/java/foundation/e/blisslauncher/core/broadcast/PackageAddedRemovedHandler.java index 6e5280833b9a16cfdb2ff4cc55a98d4ed16dda92..93dc3af1c2c119c51098c6c8df3d5129e764c957 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/broadcast/PackageAddedRemovedHandler.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/broadcast/PackageAddedRemovedHandler.java @@ -5,7 +5,6 @@ import android.content.Context; import android.content.Intent; import android.os.Process; import android.util.Log; - import foundation.e.blisslauncher.BlissLauncher; import foundation.e.blisslauncher.core.events.AppAddEvent; import foundation.e.blisslauncher.core.events.AppChangeEvent; @@ -17,17 +16,17 @@ public class PackageAddedRemovedHandler extends BroadcastReceiver { private static final String TAG = "PackageAddedRemovedHand"; - public static void handleEvent(Context ctx, String action, String packageName, UserHandle user, - boolean replacing) { + public static void handleEvent(Context ctx, String action, String packageName, UserHandle user, boolean replacing) { if (!Process.myUserHandle().equals(user.getRealHandle())) { return; } - Log.d(TAG, "handleEvent() called with: ctx = [" + ctx + "], action = [" + action + "], packageName = [" + packageName + "], user = [" + user + "], replacing = [" + replacing + "]"); + Log.d(TAG, "handleEvent() called with: ctx = [" + ctx + "], action = [" + action + "], packageName = [" + + packageName + "], user = [" + user + "], replacing = [" + replacing + "]"); // Insert into history new packages (not updated ones) if ("android.intent.action.PACKAGE_ADDED".equals(action) && !replacing) { Intent launchIntent = ctx.getPackageManager().getLaunchIntentForPackage(packageName); - if (launchIntent == null) {//for some plugin app + if (launchIntent == null) { // for some plugin app return; } @@ -41,8 +40,8 @@ public class PackageAddedRemovedHandler extends BroadcastReceiver { if ("android.intent.action.PACKAGE_CHANGED".equalsIgnoreCase(action)) { Intent launchIntent = ctx.getPackageManager().getLaunchIntentForPackage(packageName); if (launchIntent != null) { - BlissLauncher.getApplication(ctx).getIconsHandler().resetIconDrawableForPackage( - launchIntent.getComponent(), user); + BlissLauncher.getApplication(ctx).getIconsHandler() + .resetIconDrawableForPackage(launchIntent.getComponent(), user); } BlissLauncher.getApplication(ctx).resetIconsHandler(); @@ -57,11 +56,11 @@ public class PackageAddedRemovedHandler extends BroadcastReceiver { BlissLauncher.getApplication(ctx).getAppProvider().reload(false); } - if("android.intent.action.MEDIA_MOUNTED".equals(action)) { + if ("android.intent.action.MEDIA_MOUNTED".equals(action)) { Intent launchIntent = ctx.getPackageManager().getLaunchIntentForPackage(packageName); if (launchIntent != null) { - BlissLauncher.getApplication(ctx).getIconsHandler().resetIconDrawableForPackage( - launchIntent.getComponent(), user); + BlissLauncher.getApplication(ctx).getIconsHandler() + .resetIconDrawableForPackage(launchIntent.getComponent(), user); AppChangeEvent appChangeEvent = new AppChangeEvent(packageName, user); EventRelay.getInstance().push(appChangeEvent); } @@ -74,11 +73,7 @@ public class PackageAddedRemovedHandler extends BroadcastReceiver { if (packageName.equalsIgnoreCase(ctx.getPackageName())) { return; } - handleEvent(ctx, - intent.getAction(), - packageName, new UserHandle(), - intent.getBooleanExtra(Intent.EXTRA_REPLACING, false) - ); - + handleEvent(ctx, intent.getAction(), packageName, new UserHandle(), + intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)); } } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/broadcast/TimeChangeBroadcastReceiver.java b/app/src/main/java/foundation/e/blisslauncher/core/broadcast/TimeChangeBroadcastReceiver.java index e1cde5cc7368d1d31c318f9fc63ac0d7ceb526b5..444969176ef52180d944182370c09ad62f5e0e66 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/broadcast/TimeChangeBroadcastReceiver.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/broadcast/TimeChangeBroadcastReceiver.java @@ -4,7 +4,6 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; - import foundation.e.blisslauncher.core.events.EventRelay; import foundation.e.blisslauncher.core.events.TimeChangedEvent; diff --git a/app/src/main/java/foundation/e/blisslauncher/core/broadcast/WallpaperChangeReceiver.java b/app/src/main/java/foundation/e/blisslauncher/core/broadcast/WallpaperChangeReceiver.java index 45bebbc83ff6f888b58430c40ac9b81387160260..abeb38c7de56b6c605a40a60297f279d3216a0b4 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/broadcast/WallpaperChangeReceiver.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/broadcast/WallpaperChangeReceiver.java @@ -1,5 +1,7 @@ package foundation.e.blisslauncher.core.broadcast; +import static android.content.Context.WALLPAPER_SERVICE; + import android.app.WallpaperManager; import android.content.BroadcastReceiver; import android.content.Context; @@ -7,18 +9,15 @@ import android.content.Intent; import android.content.IntentFilter; import android.os.IBinder; import android.view.View; - import foundation.e.blisslauncher.core.blur.BlurWallpaperProvider; -import static android.content.Context.WALLPAPER_SERVICE; - public class WallpaperChangeReceiver extends BroadcastReceiver { private final Context mContext; private IBinder mWindowToken; private boolean mRegistered; private View mWorkspace; - public WallpaperChangeReceiver(View workspace){ + public WallpaperChangeReceiver(View workspace) { this.mWorkspace = workspace; this.mContext = mWorkspace.getContext(); } @@ -35,8 +34,7 @@ public class WallpaperChangeReceiver extends BroadcastReceiver { mWorkspace.getContext().unregisterReceiver(this); mRegistered = false; } else if (mWindowToken != null && !mRegistered) { - mWorkspace.getContext() - .registerReceiver(this, new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED)); + mWorkspace.getContext().registerReceiver(this, new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED)); onReceive(mWorkspace.getContext(), null); mRegistered = true; } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/AdaptiveIconDrawableCompat.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/AdaptiveIconDrawableCompat.java index ee839e7f46c1538c859731be6866ecc3f6a440d0..1c72f8787813721e6f8fc7bf88726fe2460aeb4e 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/AdaptiveIconDrawableCompat.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/AdaptiveIconDrawableCompat.java @@ -24,36 +24,36 @@ import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.TypedValue; - import androidx.annotation.NonNull; import androidx.annotation.Nullable; - -import org.xmlpull.v1.XmlPullParser; -import org.xmlpull.v1.XmlPullParserException; - +import foundation.e.blisslauncher.core.utils.AdaptiveIconUtils; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; - -import foundation.e.blisslauncher.core.utils.AdaptiveIconUtils; +import org.xmlpull.v1.XmlPullParser; +import org.xmlpull.v1.XmlPullParserException; /** - *

This class can also be created via XML inflation using <adaptive-icon> tag - * in addition to dynamic creation. + * This class can also be created via XML inflation using + * <adaptive-icon> tag in addition to dynamic creation. * - *

This drawable supports two drawable layers: foreground and background. The layers are clipped - * when rendering using the mask defined in the device configuration. + *

+ * This drawable supports two drawable layers: foreground and background. The + * layers are clipped when rendering using the mask defined in the device + * configuration. * *

    - *
  • Both foreground and background layers should be sized at 108 x 108 dp.
  • - *
  • The inner 72 x 72 dp of the icon appears within the masked viewport.
  • - *
  • The outer 18 dp on each of the 4 sides of the layers is reserved for use by the system UI - * surfaces to create interesting visual effects, such as parallax or pulsing.
  • + *
  • Both foreground and background layers should be sized at 108 x 108 dp. + *
  • The inner 72 x 72 dp of the icon appears within the masked viewport. + *
  • The outer 18 dp on each of the 4 sides of the layers is reserved for use + * by the system UI surfaces to create interesting visual effects, such as + * parallax or pulsing. *
* - * Such motion effect is achieved by internally setting the bounds of the foreground and - * background layer as following: + * Such motion effect is achieved by internally setting the bounds of the + * foreground and background layer as following: + * *
  * Rect(getBounds().left - getBounds().getWidth() * #getExtraInsetFraction(),
  *      getBounds().top - getBounds().getHeight() * #getExtraInsetFraction(),
@@ -64,36 +64,36 @@ import foundation.e.blisslauncher.core.utils.AdaptiveIconUtils;
 public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Callback {
 
     /**
-     * Mask path is defined inside device configuration in following dimension: [100 x 100]
+     * Mask path is defined inside device configuration in following dimension: [100
+     * x 100]
      */
     public static float MASK_SIZE = 180f;
 
-    /**
-     * Launcher icons design guideline
-     */
+    /** Launcher icons design guideline */
     private static final float SAFEZONE_SCALE = 66f / 72f;
 
     /**
      * All four sides of the layers are padded with extra inset so as to provide
-     * extra content to reveal within the clip path when performing affine transformations on the
-     * layers.
+     * extra content to reveal within the clip path when performing affine
+     * transformations on the layers.
      *
+     * 

* Each layers will reserve 25% of it's width and height. * - * As a result, the view port of the layers is smaller than their intrinsic width and height. + *

+ * As a result, the view port of the layers is smaller than their intrinsic + * width and height. */ private static final float EXTRA_INSET_PERCENTAGE = 1 / 4f; + private static final float DEFAULT_VIEW_PORT_SCALE = 1f / (1 + 2 * EXTRA_INSET_PERCENTAGE); - /** - * Clip path defined in R.string.config_icon_mask. - */ + /** Clip path defined in R.string.config_icon_mask. */ private static Path sMask; - /** - * Scaled mask based on the view bounds. - */ + /** Scaled mask based on the view bounds. */ private final Path mMask; + private final Matrix mMaskMatrix; private final Region mTransparentRegion; @@ -102,9 +102,7 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal private static final int BACKGROUND_ID = 0; private static final int FOREGROUND_ID = 1; - /** - * State variable that maintains the {@link ChildDrawable} array. - */ + /** State variable that maintains the {@link ChildDrawable} array. */ LayerState mLayerState; private Shader mLayersShader; @@ -117,8 +115,7 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal private boolean mSuspendChildInvalidation; private boolean mChildRequestedInvalidation; private final Canvas mCanvas; - private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | - Paint.FILTER_BITMAP_FLAG); + private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG); private Method methodCreatePathFromPathData; private Method methodExtractThemeAttrs; @@ -127,9 +124,7 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal private static final String TAG = "AdaptiveIconDrawable"; - /** - * Constructor used for xml inflation. - */ + /** Constructor used for xml inflation. */ public AdaptiveIconDrawableCompat() { this((LayerState) null, null); } @@ -147,7 +142,7 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal sMask = PathParser.createPathFromPathData(getMaskPath()); } mMask = PathParser.createPathFromPathData(getMaskPath()); - //mMask = DeviceProfile.path; + // mMask = DeviceProfile.path; mMaskMatrix = new Matrix(); mCanvas = new Canvas(); mTransparentRegion = new Region(); @@ -157,8 +152,7 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal private void initReflections() { try { Class pathParser = getClass().getClassLoader().loadClass("android.util.PathParser"); - methodCreatePathFromPathData = pathParser.getDeclaredMethod("createPathFromPathData", - String.class); + methodCreatePathFromPathData = pathParser.getDeclaredMethod("createPathFromPathData", String.class); methodExtractThemeAttrs = TypedArray.class.getDeclaredMethod("extractThemeAttrs"); } catch (ClassNotFoundException | NoSuchMethodException e) { e.printStackTrace(); @@ -189,8 +183,7 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal final ChildDrawable layer = new ChildDrawable(mLayerState.mDensity); layer.mDrawable = drawable; layer.mDrawable.setCallback(this); - mLayerState.mChildrenChangingConfigurations |= - layer.mDrawable.getChangingConfigurations(); + mLayerState.mChildrenChangingConfigurations |= layer.mDrawable.getChangingConfigurations(); return layer; } @@ -201,16 +194,17 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal /** * Constructor used to dynamically create this drawable. * - * @param backgroundDrawable drawable that should be rendered in the background - * @param foregroundDrawable drawable that should be rendered in the foreground + * @param backgroundDrawable + * drawable that should be rendered in the background + * @param foregroundDrawable + * drawable that should be rendered in the foreground */ - public AdaptiveIconDrawableCompat(Drawable backgroundDrawable, - Drawable foregroundDrawable) { + public AdaptiveIconDrawableCompat(Drawable backgroundDrawable, Drawable foregroundDrawable) { this(backgroundDrawable, foregroundDrawable, true); } - public AdaptiveIconDrawableCompat(Drawable backgroundDrawable, - Drawable foregroundDrawable, boolean useMyUglyWorkaround) { + public AdaptiveIconDrawableCompat(Drawable backgroundDrawable, Drawable foregroundDrawable, + boolean useMyUglyWorkaround) { this((LayerState) null, null); if (backgroundDrawable != null) { addLayer(BACKGROUND_ID, createChildDrawable(backgroundDrawable)); @@ -224,8 +218,10 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal /** * Sets the layer to the {@param index} and invalidates cache. * - * @param index The index of the layer. - * @param layer The layer to add. + * @param index + * The index of the layer. + * @param layer + * The layer to add. */ private void addLayer(int index, @NonNull ChildDrawable layer) { mLayerState.mChildren[index] = layer; @@ -233,9 +229,8 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal } @Override - public void inflate(@NonNull Resources r, @NonNull XmlPullParser parser, - @NonNull AttributeSet attrs, @Nullable Theme theme) - throws XmlPullParserException, IOException { + public void inflate(@NonNull Resources r, @NonNull XmlPullParser parser, @NonNull AttributeSet attrs, + @Nullable Theme theme) throws XmlPullParserException, IOException { super.inflate(r, parser, attrs, theme); final LayerState state = mLayerState; @@ -246,12 +241,12 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal // The density may have changed since the last update. This will // apply scaling to any existing constant state properties. final int deviceDensity = resolveDensity(r, 0); - //state.setDensity(deviceDensity); + // state.setDensity(deviceDensity); final ChildDrawable[] array = state.mChildren; for (int i = 0; i < state.mChildren.length; i++) { final ChildDrawable layer = array[i]; - //layer.setDensity(deviceDensity); + // layer.setDensity(deviceDensity); } inflateLayers(r, parser, attrs, theme); @@ -264,10 +259,11 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal /** * All four sides of the layers are padded with extra inset so as to provide - * extra content to reveal within the clip path when performing affine transformations on the - * layers. + * extra content to reveal within the clip path when performing affine + * transformations on the layers. * - * @see #getForeground() and #getBackground() for more info on how this value is used + * @see #getForeground() and #getBackground() for more info on how this value is + * used */ public static float getExtraInsetFraction() { return EXTRA_INSET_PERCENTAGE; @@ -279,8 +275,8 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal /** * When called before the bound is set, the returned path is identical to - * R.string.config_icon_mask. After the bound is set, the - * returned path's computed bound is same as the #getBounds(). + * R.string.config_icon_mask. After the bound is set, the returned path's + * computed bound is same as the #getBounds(). * * @return the mask path object used to clip the drawable */ @@ -289,9 +285,10 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal } /** - * Returns the foreground drawable managed by this class. The bound of this drawable is - * extended by {@link #getExtraInsetFraction()} * getBounds().width on left/right sides and by - * {@link #getExtraInsetFraction()} * getBounds().height on top/bottom sides. + * Returns the foreground drawable managed by this class. The bound of this + * drawable is extended by {@link #getExtraInsetFraction()} * getBounds().width + * on left/right sides and by {@link #getExtraInsetFraction()} * + * getBounds().height on top/bottom sides. * * @return the foreground drawable managed by this drawable */ @@ -300,9 +297,10 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal } /** - * Returns the foreground drawable managed by this class. The bound of this drawable is - * extended by {@link #getExtraInsetFraction()} * getBounds().width on left/right sides and by - * {@link #getExtraInsetFraction()} * getBounds().height on top/bottom sides. + * Returns the foreground drawable managed by this class. The bound of this + * drawable is extended by {@link #getExtraInsetFraction()} * getBounds().width + * on left/right sides and by {@link #getExtraInsetFraction()} * + * getBounds().height on top/bottom sides. * * @return the background drawable managed by this drawable */ @@ -329,7 +327,8 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal } /** - * Set the child layer bounds bigger than the view port size by {@link #DEFAULT_VIEW_PORT_SCALE} + * Set the child layer bounds bigger than the view port size by + * {@link #DEFAULT_VIEW_PORT_SCALE} */ private void updateLayerBoundsInternal(Rect bounds) { int cX = bounds.width() / 2; @@ -358,8 +357,7 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal mMaskMatrix.setScale(b.width() / MASK_SIZE, b.height() / MASK_SIZE); sMask.transform(mMaskMatrix, mMask); - if (mMaskBitmap == null || mMaskBitmap.getWidth() != b.width() || - mMaskBitmap.getHeight() != b.height()) { + if (mMaskBitmap == null || mMaskBitmap.getWidth() != b.width() || mMaskBitmap.getHeight() != b.height()) { mMaskBitmap = Bitmap.createBitmap(b.width(), b.height(), Bitmap.Config.ALPHA_8); mLayersBitmap = Bitmap.createBitmap(b.width(), b.height(), Bitmap.Config.ARGB_8888); } @@ -385,7 +383,7 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal } if (mLayersShader == null) { mCanvas.setBitmap(mLayersBitmap); - //mCanvas.drawColor(Color.BLACK); + // mCanvas.drawColor(Color.BLACK); for (int i = 0; i < LayerState.N_CHILDREN; i++) { if (mLayerState.mChildren[i] == null) { continue; @@ -400,9 +398,8 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal } if (mMaskBitmap != null) { Rect bounds = getBounds(); - //mPaint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); - canvas.drawBitmap(mMaskBitmap, bounds.left, - bounds.top, mPaint); + // mPaint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN)); + canvas.drawBitmap(mMaskBitmap, bounds.left, bounds.top, mPaint); } } @@ -419,8 +416,7 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal public Region getSafeZone() { mMaskMatrix.reset(); - mMaskMatrix.setScale(SAFEZONE_SCALE, SAFEZONE_SCALE, getBounds().centerX(), - getBounds().centerY()); + mMaskMatrix.setScale(SAFEZONE_SCALE, SAFEZONE_SCALE, getBounds().centerX(), getBounds().centerY()); Path p = new Path(); mMask.transform(mMaskMatrix, p); Region safezoneRegion = new Region(getBounds()); @@ -429,8 +425,7 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal } @Override - public @Nullable - Region getTransparentRegion() { + public @Nullable Region getTransparentRegion() { if (mTransparentRegion.isEmpty()) { mMask.toggleInverseFillType(); mTransparentRegion.set(getBounds()); @@ -440,12 +435,9 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal return mTransparentRegion; } - /** - * Inflates child layers using the specified parser. - */ - private void inflateLayers(@NonNull Resources r, @NonNull XmlPullParser parser, - @NonNull AttributeSet attrs, @Nullable Theme theme) - throws XmlPullParserException, IOException { + /** Inflates child layers using the specified parser. */ + private void inflateLayers(@NonNull Resources r, @NonNull XmlPullParser parser, @NonNull AttributeSet attrs, + @Nullable Theme theme) throws XmlPullParserException, IOException { final LayerState state = mLayerState; final int innerDepth = parser.getDepth() + 1; @@ -463,19 +455,18 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal } String tagName = parser.getName(); switch (tagName) { - case "background": + case "background" : childIndex = BACKGROUND_ID; break; - case "foreground": + case "foreground" : childIndex = FOREGROUND_ID; break; - default: + default : continue; } final ChildDrawable layer = new ChildDrawable(state.mDensity); - final TypedArray a = obtainAttributes(r, theme, attrs, - new int[]{android.R.attr.drawable}); + final TypedArray a = obtainAttributes(r, theme, attrs, new int[]{android.R.attr.drawable}); updateLayerFromTypedArray(layer, a); a.recycle(); @@ -487,16 +478,15 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal while ((type = parser.next()) == XmlPullParser.TEXT) { } if (type != XmlPullParser.START_TAG) { - throw new XmlPullParserException(parser.getPositionDescription() - + ": or tag requires a 'drawable'" - + "attribute or child tag defining a drawable"); + throw new XmlPullParserException( + parser.getPositionDescription() + ": or tag requires a 'drawable'" + + "attribute or child tag defining a drawable"); } // We found a child drawable. Take ownership. layer.mDrawable = Drawable.createFromXmlInner(r, parser, attrs, theme); layer.mDrawable.setCallback(this); - state.mChildrenChangingConfigurations |= - layer.mDrawable.getChangingConfigurations(); + state.mChildrenChangingConfigurations |= layer.mDrawable.getChangingConfigurations(); } addLayer(childIndex, layer); } @@ -511,7 +501,8 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal // Extract the theme attributes, if any. layer.mThemeAttrs = invoke(methodExtractThemeAttrs, a); - @SuppressLint("ResourceType") Drawable dr = getDrawable(a, 0); + @SuppressLint("ResourceType") + Drawable dr = getDrawable(a, 0); if (dr != null) { if (layer.mDrawable != null) { // It's possible that a drawable was already set, in which case @@ -524,8 +515,7 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal // Take ownership of the new drawable. layer.mDrawable = dr; layer.mDrawable.setCallback(this); - state.mChildrenChangingConfigurations |= - layer.mDrawable.getChangingConfigurations(); + state.mChildrenChangingConfigurations |= layer.mDrawable.getChangingConfigurations(); } } @@ -849,9 +839,8 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal return this; } - protected static @NonNull - TypedArray obtainAttributes(@NonNull Resources res, - @Nullable Theme theme, @NonNull AttributeSet set, @NonNull int[] attrs) { + protected static @NonNull TypedArray obtainAttributes(@NonNull Resources res, @Nullable Theme theme, + @NonNull AttributeSet set, @NonNull int[] attrs) { if (theme == null) { return res.obtainAttributes(set, attrs); } @@ -867,8 +856,7 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal mDensity = density; } - ChildDrawable(@NonNull ChildDrawable orig, @NonNull AdaptiveIconDrawableCompat owner, - @Nullable Resources res) { + ChildDrawable(@NonNull ChildDrawable orig, @NonNull AdaptiveIconDrawableCompat owner, @Nullable Resources res) { final Drawable dr = orig.mDrawable; final Drawable clone; @@ -895,8 +883,7 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal } public boolean canApplyTheme() { - return mThemeAttrs != null - || (mDrawable != null && mDrawable.canApplyTheme()); + return mThemeAttrs != null || (mDrawable != null && mDrawable.canApplyTheme()); } public final void setDensity(int targetDensity) { @@ -909,13 +896,14 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal static class LayerState extends ConstantState { private int[] mThemeAttrs; - final static int N_CHILDREN = 2; + static final int N_CHILDREN = 2; ChildDrawable[] mChildren; // The density at which to render the drawable and its children. int mDensity; - // The density to use when inflating/looking up the children drawables. A value of 0 means + // The density to use when inflating/looking up the children drawables. A value + // of 0 means // use the system's density. int mSrcDensityOverride = 0; @@ -931,8 +919,7 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal private boolean mIsStateful; private boolean mAutoMirrored = false; - LayerState(@Nullable LayerState orig, @NonNull AdaptiveIconDrawableCompat owner, - @Nullable Resources res) { + LayerState(@Nullable LayerState orig, @NonNull AdaptiveIconDrawableCompat owner, @Nullable Resources res) { mDensity = resolveDensity(res, orig != null ? orig.mDensity : 0); mChildren = new ChildDrawable[N_CHILDREN]; if (orig != null) { @@ -997,8 +984,7 @@ public class AdaptiveIconDrawableCompat extends Drawable implements Drawable.Cal @Override public int getChangingConfigurations() { - return mChangingConfigurations - | mChildrenChangingConfigurations; + return mChangingConfigurations | mChildrenChangingConfigurations; } public final int getOpacity() { diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/AppWidgetResizeFrame.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/AppWidgetResizeFrame.java index 7f34e229e027986cc72538a284feb4d23e0a63b2..78780275a19d7e10001c0a3043e7dc4973e8249d 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/AppWidgetResizeFrame.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/AppWidgetResizeFrame.java @@ -6,9 +6,7 @@ import android.content.Context; import android.graphics.Rect; import android.widget.FrameLayout; import android.widget.ImageView; - import androidx.annotation.NonNull; - import foundation.e.blisslauncher.R; public class AppWidgetResizeFrame extends FrameLayout { @@ -59,7 +57,6 @@ public class AppWidgetResizeFrame extends FrameLayout { private static final String TAG = "AppWidgetResizeFrame"; - public AppWidgetResizeFrame(@NonNull Context context, RoundedWidgetView widgetView) { super(context); mRoundedWidgetView = widgetView; @@ -67,12 +64,13 @@ public class AppWidgetResizeFrame extends FrameLayout { final AppWidgetProviderInfo info = widgetView.getAppWidgetInfo(); Rect padding = AppWidgetHostView.getDefaultPaddingForWidget(context, info.provider, null); - // We want to account for the extra amount of padding that we are adding to the widget + // We want to account for the extra amount of padding that we are adding to the + // widget // to ensure that it gets the full amount of space that it has requested mMinHeight = info.minHeight + padding.top + padding.bottom; setBackgroundResource(R.drawable.widget_resize_frame); setPadding(0, 0, 0, 0); - //setLayoutParams(mRoundedWidgetView.getLayoutParams()); + // setLayoutParams(mRoundedWidgetView.getLayoutParams()); } } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/BlissDragShadowBuilder.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/BlissDragShadowBuilder.java index d81c756470f2ab85ff6c7bf45c991ed55fb812a3..372be64e1c269be16c9ab59a80c43440f61afe62 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/BlissDragShadowBuilder.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/BlissDragShadowBuilder.java @@ -5,10 +5,7 @@ import android.graphics.Point; import android.util.Log; import android.view.View; -/** - * Created by falcon on 15/2/18. - */ - +/** Created by falcon on 15/2/18. */ public class BlissDragShadowBuilder extends View.DragShadowBuilder { private final int mX; @@ -26,20 +23,19 @@ public class BlissDragShadowBuilder extends View.DragShadowBuilder { // Stores the View parameter passed to DragShadowBuilder. super(v); - mX = (int) x; mY = (int) y; - Log.i(TAG, "Touchpoint: "+mX+" "+mY); + Log.i(TAG, "Touchpoint: " + mX + " " + mY); - xOffset = mX - v.getWidth()/2; - yOffset = (mY - v.getHeight()/2); - - Log.i(TAG, "Offset: "+xOffset+" "+yOffset); + xOffset = mX - v.getWidth() / 2; + yOffset = (mY - v.getHeight() / 2); + Log.i(TAG, "Offset: " + xOffset + " " + yOffset); } - // Defines a callback that sends the drag shadow dimensions and touch point back to the + // Defines a callback that sends the drag shadow dimensions and touch point back + // to the // system. @Override public void onProvideShadowMetrics(Point size, Point touch) { @@ -53,7 +49,8 @@ public class BlissDragShadowBuilder extends View.DragShadowBuilder { // Sets the height of the shadow to half the height of the original View height = getView().getHeight(); - // Sets the size parameter's width and height values. These get back to the system + // Sets the size parameter's width and height values. These get back to the + // system // through the size parameter. size.set(width, height); // Sets size parameter to member that will be used for scaling shadow image. @@ -67,10 +64,8 @@ public class BlissDragShadowBuilder extends View.DragShadowBuilder { public void onDrawShadow(Canvas canvas) { canvas.save(); // Draws the ColorDrawable in the Canvas passed in from the system. - canvas.scale(mScaleFactor.x / (float) getView().getWidth(), - mScaleFactor.y / (float) getView().getHeight()); + canvas.scale(mScaleFactor.x / (float) getView().getWidth(), mScaleFactor.y / (float) getView().getHeight()); getView().draw(canvas); canvas.restore(); } - } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/BlissFrameLayout.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/BlissFrameLayout.java index 33de0a70aad6a78d726b2c8356c47d89b23fd361..ab1e5353ea0c75a0fa1b4c48bcd0cba28e188284 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/BlissFrameLayout.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/BlissFrameLayout.java @@ -11,11 +11,6 @@ import android.view.View; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; - import foundation.e.blisslauncher.BlissLauncher; import foundation.e.blisslauncher.R; import foundation.e.blisslauncher.core.DeviceProfile; @@ -27,11 +22,11 @@ import foundation.e.blisslauncher.core.database.model.LauncherItem; import foundation.e.blisslauncher.core.database.model.ShortcutItem; import foundation.e.blisslauncher.core.utils.Constants; import foundation.e.blisslauncher.features.notification.DotRenderer; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; -/** - * Created by falcon on 20/3/18. - */ - +/** Created by falcon on 20/3/18. */ public class BlissFrameLayout extends FrameLayout { private final Context mContext; @@ -42,8 +37,8 @@ public class BlissFrameLayout extends FrameLayout { private float mBadgeScale; - private static final Property BADGE_SCALE_PROPERTY - = new Property(Float.TYPE, "badgeScale") { + private static final Property BADGE_SCALE_PROPERTY = new Property( + Float.TYPE, "badgeScale") { @Override public Float get(BlissFrameLayout bubbleTextView) { return bubbleTextView.mBadgeScale; @@ -64,13 +59,11 @@ public class BlissFrameLayout extends FrameLayout { this(context, null, 0); } - public BlissFrameLayout(Context context, - AttributeSet attrs) { + public BlissFrameLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } - public BlissFrameLayout(Context context, AttributeSet attrs, - int defStyleAttr) { + public BlissFrameLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mContext = context; init(); @@ -154,17 +147,14 @@ public class BlissFrameLayout extends FrameLayout { private void bindFolderItem(FolderItem folderItem) { final TextView label = findViewById(R.id.app_label); final SquareFrameLayout icon = findViewById(R.id.app_icon); - final SquareImageView squareImageView = findViewById( - R.id.icon_image_view); + final SquareImageView squareImageView = findViewById(R.id.icon_image_view); icon.enableBlur(); LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) icon.getLayoutParams(); layoutParams.leftMargin = mDeviceProfile.iconDrawablePaddingPx / 2; layoutParams.rightMargin = mDeviceProfile.iconDrawablePaddingPx / 2; - label.setPadding((int) Utilities.pxFromDp(4, mContext), - (int) Utilities.pxFromDp(0, mContext), - (int) Utilities.pxFromDp(4, mContext), - (int) Utilities.pxFromDp(0, mContext)); + label.setPadding((int) Utilities.pxFromDp(4, mContext), (int) Utilities.pxFromDp(0, mContext), + (int) Utilities.pxFromDp(4, mContext), (int) Utilities.pxFromDp(0, mContext)); squareImageView.setImageDrawable(folderItem.icon); label.setText(folderItem.title.toString()); label.setTextSize(12); @@ -178,16 +168,13 @@ public class BlissFrameLayout extends FrameLayout { private void bindShortcutItem(ShortcutItem shortcutItem) { final TextView label = findViewById(R.id.app_label); final SquareFrameLayout icon = findViewById(R.id.app_icon); - final SquareImageView squareImageView = findViewById( - R.id.icon_image_view); + final SquareImageView squareImageView = findViewById(R.id.icon_image_view); LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) icon.getLayoutParams(); layoutParams.leftMargin = mDeviceProfile.iconDrawablePaddingPx / 2; layoutParams.rightMargin = mDeviceProfile.iconDrawablePaddingPx / 2; - label.setPadding((int) Utilities.pxFromDp(4, mContext), - (int) Utilities.pxFromDp(0, mContext), - (int) Utilities.pxFromDp(4, mContext), - (int) Utilities.pxFromDp(0, mContext)); + label.setPadding((int) Utilities.pxFromDp(4, mContext), (int) Utilities.pxFromDp(0, mContext), + (int) Utilities.pxFromDp(4, mContext), (int) Utilities.pxFromDp(0, mContext)); squareImageView.setImageDrawable(shortcutItem.icon); label.setText(shortcutItem.title.toString()); label.setTextSize(12); @@ -201,18 +188,14 @@ public class BlissFrameLayout extends FrameLayout { private void bindApplicationItem(ApplicationItem applicationItem) { final TextView label = findViewById(R.id.app_label); final SquareFrameLayout icon = findViewById(R.id.app_icon); - final SquareImageView squareImageView = findViewById( - R.id.icon_image_view); + final SquareImageView squareImageView = findViewById(R.id.icon_image_view); LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) icon.getLayoutParams(); layoutParams.leftMargin = mDeviceProfile.iconDrawablePaddingPx / 2; layoutParams.rightMargin = mDeviceProfile.iconDrawablePaddingPx / 2; - label.setPadding((int) Utilities.pxFromDp(4, mContext), - (int) Utilities.pxFromDp(0, mContext), - (int) Utilities.pxFromDp(4, mContext), - (int) Utilities.pxFromDp(0, mContext)); + label.setPadding((int) Utilities.pxFromDp(4, mContext), (int) Utilities.pxFromDp(0, mContext), + (int) Utilities.pxFromDp(4, mContext), (int) Utilities.pxFromDp(0, mContext)); if (applicationItem.appType == ApplicationItem.TYPE_CLOCK) { - final CustomAnalogClock analogClock = findViewById( - R.id.icon_clock); + final CustomAnalogClock analogClock = findViewById(R.id.icon_clock); analogClock.setAutoUpdate(true); analogClock.setVisibility(View.VISIBLE); squareImageView.setVisibility(GONE); @@ -228,8 +211,7 @@ public class BlissFrameLayout extends FrameLayout { dateTextView.getLayoutParams().height = mDeviceProfile.dateTextviewHeight; dateTextView.getLayoutParams().width = mDeviceProfile.calendarIconWidth; int datePx = mDeviceProfile.dateTextSize; - dateTextView.setPadding(0, mDeviceProfile.dateTextTopPadding, 0, - mDeviceProfile.dateTextBottomPadding); + dateTextView.setPadding(0, mDeviceProfile.dateTextTopPadding, 0, mDeviceProfile.dateTextBottomPadding); dateTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, datePx / 2); @@ -237,10 +219,8 @@ public class BlissFrameLayout extends FrameLayout { squareImageView.setVisibility(GONE); CalendarIcon calendarIcon = new CalendarIcon(monthTextView, dateTextView); - calendarIcon.monthTextView.setText( - Utilities.convertMonthToString()); - calendarIcon.dayTextView.setText( - String.valueOf(Calendar.getInstance().get(Calendar.DAY_OF_MONTH))); + calendarIcon.monthTextView.setText(Utilities.convertMonthToString()); + calendarIcon.dayTextView.setText(String.valueOf(Calendar.getInstance().get(Calendar.DAY_OF_MONTH))); } else { squareImageView.setImageDrawable(applicationItem.icon); } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/BlissInput.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/BlissInput.java index 659c9e593ae74ac2ce3009e8f663b29ad3fbe36c..360b3b8e6df224d461834b1aae2bc1a71d4dccdf 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/BlissInput.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/BlissInput.java @@ -3,7 +3,6 @@ package foundation.e.blisslauncher.core.customviews; import android.content.Context; import android.util.AttributeSet; import android.view.DragEvent; - import androidx.appcompat.widget.AppCompatEditText; public class BlissInput extends AppCompatEditText { diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/CustomAnalogClock.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/CustomAnalogClock.java index e801ffbf63bbd70c7b2536d6df2fedbca60d01c1..83ab8cb31217fa9fa23f02d619da8504b80bd555 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/CustomAnalogClock.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/CustomAnalogClock.java @@ -7,18 +7,12 @@ import android.graphics.drawable.Drawable; import android.os.Handler; import android.util.AttributeSet; import android.view.View; - import androidx.core.content.ContextCompat; - -import java.util.Calendar; - import foundation.e.blisslauncher.BlissLauncher; import foundation.e.blisslauncher.R; +import java.util.Calendar; -/** - * Created by falcon on 8/3/18. - */ - +/** Created by falcon on 8/3/18. */ public class CustomAnalogClock extends View { public static boolean is24; @@ -58,14 +52,15 @@ public class CustomAnalogClock extends View { } public void init(Context context) { - init(context, R.drawable.clock, R.drawable.hours, - R.drawable.minutes, R.drawable.seconds, 0, false, false); + init(context, R.drawable.clock, R.drawable.hours, R.drawable.minutes, R.drawable.seconds, 0, false, false); } /** - * Will set the scale of the view, for example 0.5f will draw the clock with half of its radius + * Will set the scale of the view, for example 0.5f will draw the clock with + * half of its radius * - * @param scale the scale to render the view in + * @param scale + * the scale to render the view in */ public void setScale(float scale) { if (scale <= 0) { @@ -81,8 +76,7 @@ public class CustomAnalogClock extends View { setFace(r.getDrawable(drawableRes)); } - public void init(Context context, int watchFace, int hourHand, - int minuteHand, int secHand, int alpha, boolean is24, + public void init(Context context, int watchFace, int hourHand, int minuteHand, int secHand, int alpha, boolean is24, boolean hourOnTop) { this.mContext = context; CustomAnalogClock.is24 = is24; @@ -115,10 +109,10 @@ public class CustomAnalogClock extends View { } /** - * Sets the currently displayed time in {@link System#currentTimeMillis()} - * time. + * Sets the currently displayed time in {@link System#currentTimeMillis()} time. * - * @param time the time to display on the clock + * @param time + * the time to display on the clock */ public void setTime(long time) { mCalendar.setTimeInMillis(time); @@ -128,7 +122,8 @@ public class CustomAnalogClock extends View { /** * Sets the currently displayed time. * - * @param calendar The time to display on the clock + * @param calendar + * The time to display on the clock */ public void setTime(Calendar calendar) { mCalendar = calendar; @@ -172,21 +167,16 @@ public class CustomAnalogClock extends View { if (availW < w || availH < h) { scaled = true; - final float scale = Math.min((float) availW / (float) w, - (float) availH / (float) h); + final float scale = Math.min((float) availW / (float) w, (float) availH / (float) h); canvas.save(); canvas.scale(scale, scale, cX, cY); } if (sizeChanged) { // Extend bottom by 1 and top by -1 for proper bounds - mFace.setBounds(cX - (w / 2), - cY - (h / 2) - 1, - cX + (w / 2), - cY + (h / 2) + 1); + mFace.setBounds(cX - (w / 2), cY - (h / 2) - 1, cX + (w / 2), cY + (h / 2) + 1); } - mFace.draw(canvas); mHandsOverlay.onDraw(canvas, cX, cY, w, h, mCalendar, sizeChanged); @@ -231,8 +221,7 @@ public class CustomAnalogClock extends View { } @Override - protected void onLayout(boolean changed, int left, int top, int right, - int bottom) { + protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); mRight = right; mLeft = left; diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/DialOverlay.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/DialOverlay.java index f3582fc5ad55ad619cd0a0218ef094e93c005416..1e1b78704d8cd7a5e344e823ce65a0b594afa11d 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/DialOverlay.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/DialOverlay.java @@ -1,26 +1,26 @@ package foundation.e.blisslauncher.core.customviews; - import android.graphics.Canvas; - import java.util.Calendar; -/** - * An overlay for a clock dial. - */ +/** An overlay for a clock dial. */ public interface DialOverlay { /** * Subclasses should implement this to draw the overlay. * - * @param canvas the canvas onto which you must draw - * @param cX the x coordinate of the center - * @param cY the y coordinate of the center - * @param w the width of the canvas - * @param h the height of the canvas - * @param calendar the desired date/time + * @param canvas + * the canvas onto which you must draw + * @param cX + * the x coordinate of the center + * @param cY + * the y coordinate of the center + * @param w + * the width of the canvas + * @param h + * the height of the canvas + * @param calendar + * the desired date/time */ - void onDraw(Canvas canvas, float cX, float cY, int w, int h, Calendar calendar, - boolean sizeChanged); - + void onDraw(Canvas canvas, float cX, float cY, int w, int h, Calendar calendar, boolean sizeChanged); } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/HandsOverlay.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/HandsOverlay.java index 077f22175ef7859c37e4aaaf737f4fd201f40d26..122699243d001c425ba0e96b98d5100e160db7bb 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/HandsOverlay.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/HandsOverlay.java @@ -4,13 +4,9 @@ import android.content.Context; import android.content.res.Resources; import android.graphics.Canvas; import android.graphics.drawable.Drawable; - import java.util.Calendar; -/** - * Created by falcon on 8/3/18. - */ - +/** Created by falcon on 8/3/18. */ public class HandsOverlay implements DialOverlay { private final Drawable mHour; @@ -30,18 +26,18 @@ public class HandsOverlay implements DialOverlay { mHour = null; mMinute = null; - mSecond= null; + mSecond = null; } - public HandsOverlay(Drawable hourHand, Drawable minuteHand,Drawable secHand) { + public HandsOverlay(Drawable hourHand, Drawable minuteHand, Drawable secHand) { mUseLargeFace = false; mHour = hourHand; mMinute = minuteHand; - mSecond=secHand; + mSecond = secHand; } - public HandsOverlay withScale(float scale){ + public HandsOverlay withScale(float scale) { this.scale = scale; return this; } @@ -53,16 +49,17 @@ public class HandsOverlay implements DialOverlay { mHour = r.getDrawable(hourHandRes); mMinute = r.getDrawable(minuteHandRes); - mSecond=r.getDrawable(minuteHandRes); + mSecond = r.getDrawable(minuteHandRes); } public static float getHourHandAngle(int h, int m) { - return CustomAnalogClock.is24 ? ((12 + h) / 24.0f * 360) % 360 + (m / 60.0f) * 360 / 24.0f : ((12 + h) / 12.0f * 360) % 360 + (m / 60.0f) * 360 / 12.0f; + return CustomAnalogClock.is24 + ? ((12 + h) / 24.0f * 360) % 360 + (m / 60.0f) * 360 / 24.0f + : ((12 + h) / 12.0f * 360) % 360 + (m / 60.0f) * 360 / 12.0f; } @Override - public void onDraw(Canvas canvas, float cX, float cY, int w, int h, Calendar calendar, - boolean sizeChanged) { + public void onDraw(Canvas canvas, float cX, float cY, int w, int h, Calendar calendar, boolean sizeChanged) { updateHands(calendar); @@ -80,7 +77,6 @@ public class HandsOverlay implements DialOverlay { drawHours(canvas, cX, cY, w, h, calendar, sizeChanged); canvas.restore(); - canvas.save(); if (!CustomAnalogClock.hourOnTop) drawSec(canvas, cX, cY, w, h, calendar, sizeChanged); @@ -89,53 +85,42 @@ public class HandsOverlay implements DialOverlay { canvas.restore(); } - private void drawMinutes(Canvas canvas, float cX, float cY, int w, int h, Calendar calendar, - boolean sizeChanged) { + private void drawMinutes(Canvas canvas, float cX, float cY, int w, int h, Calendar calendar, boolean sizeChanged) { canvas.rotate(mMinRot, cX, cY); if (sizeChanged) { w = (int) (mMinute.getIntrinsicWidth() * scale); h = (int) (mMinute.getIntrinsicHeight() * scale); - mMinute.setBounds(Math.round(cX - (w / 2f)), - Math.round(cY - (h / 2f)), - Math.round(cX + (w / 2f)), + mMinute.setBounds(Math.round(cX - (w / 2f)), Math.round(cY - (h / 2f)), Math.round(cX + (w / 2f)), Math.round(cY + (h / 2f))); } mMinute.draw(canvas); } - private void drawHours(Canvas canvas, float cX, float cY, int w, int h, Calendar calendar, - boolean sizeChanged) { + private void drawHours(Canvas canvas, float cX, float cY, int w, int h, Calendar calendar, boolean sizeChanged) { canvas.rotate(mHourRot, cX, cY); if (sizeChanged) { - w = (int) (mHour.getIntrinsicWidth()* scale); - h = (int) (mHour.getIntrinsicHeight()* scale); - mHour.setBounds(Math.round(cX - (w / 2f)), - Math.round(cY - (h / 2f)), - Math.round(cX + (w / 2f)), + w = (int) (mHour.getIntrinsicWidth() * scale); + h = (int) (mHour.getIntrinsicHeight() * scale); + mHour.setBounds(Math.round(cX - (w / 2f)), Math.round(cY - (h / 2f)), Math.round(cX + (w / 2f)), Math.round(cY + (h / 2f))); } mHour.draw(canvas); } - private void drawSec(Canvas canvas, float cX, float cY, int w, int h, Calendar calendar, - boolean sizeChanged) { + private void drawSec(Canvas canvas, float cX, float cY, int w, int h, Calendar calendar, boolean sizeChanged) { canvas.rotate(mSecRot, cX, cY); if (sizeChanged) { w = (int) (mSecond.getIntrinsicWidth() * scale); h = (int) (mSecond.getIntrinsicHeight() * scale); - mSecond.setBounds(Math.round(cX - (w / 2f)), - Math.round(cY - (h / 2f)), - Math.round(cX + (w / 2f)), + mSecond.setBounds(Math.round(cX - (w / 2f)), Math.round(cY - (h / 2f)), Math.round(cX + (w / 2f)), Math.round(cY + (h / 2f))); } mSecond.draw(canvas); } - - public void setShowSeconds(boolean showSeconds) { mShowSeconds = showSeconds; } @@ -148,7 +133,6 @@ public class HandsOverlay implements DialOverlay { mHourRot = getHourHandAngle(h, m); mMinRot = (m / 60.0f) * 360 + (mShowSeconds ? ((s / 60.0f) * 360 / 60.0f) : 0); - mSecRot=(s* 6.0f); + mSecRot = (s * 6.0f); } - -} \ No newline at end of file +} diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/HorizontalPager.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/HorizontalPager.java index ce528caa3d4a10e4714fd764866760af257226ea..60a085c2aaf7f2bfce426342b93b986c4fda2748 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/HorizontalPager.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/HorizontalPager.java @@ -74,8 +74,7 @@ public class HorizontalPager extends ViewGroup implements Insettable { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.HorizontalPager); - pageWidthSpec = a.getDimensionPixelSize(R.styleable.HorizontalPager_pageWidth, - SPEC_UNDEFINED); + pageWidthSpec = a.getDimensionPixelSize(R.styleable.HorizontalPager_pageWidth, SPEC_UNDEFINED); a.recycle(); init(); @@ -124,9 +123,9 @@ public class HorizontalPager extends ViewGroup implements Insettable { } /** - * Gets the value that getScrollX() should return if the specified page is the current page (and - * no other scrolling is occurring). - * Use this to pass a value to scrollTo(), for example. + * Gets the value that getScrollX() should return if the specified page is the + * current page (and no other scrolling is occurring). Use this to pass a value + * to scrollTo(), for example. */ private int getScrollXForPage(int whichPage) { return (whichPage * pageWidth) - pageWidthPadding(); @@ -271,18 +270,17 @@ public class HorizontalPager extends ViewGroup implements Insettable { @Override public boolean onInterceptTouchEvent(MotionEvent ev) { - //Log.d(TAG, "onInterceptTouchEvent::action=" + ev.getAction()); + // Log.d(TAG, "onInterceptTouchEvent::action=" + ev.getAction()); /* - * This method JUST determines whether we want to intercept the motion. - * If we return true, onTouchEvent will be called and we do the actual - * scrolling there. + * This method JUST determines whether we want to intercept the motion. If we + * return true, onTouchEvent will be called and we do the actual scrolling + * there. */ /* - * Shortcut the most recurring case: the user is in the dragging - * state and he is moving his finger. We want to intercept this - * motion. + * Shortcut the most recurring case: the user is in the dragging state and he is + * moving his finger. We want to intercept this motion. */ final int action = ev.getAction(); if ((action == MotionEvent.ACTION_MOVE) && (mTouchState != TOUCH_STATE_REST)) { @@ -295,9 +293,8 @@ public class HorizontalPager extends ViewGroup implements Insettable { mLastMotionRawY = ev.getRawY(); - switch (action) { - case MotionEvent.ACTION_MOVE: + case MotionEvent.ACTION_MOVE : /* * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check * whether the user has moved far enough from his original down touch. @@ -308,38 +305,36 @@ public class HorizontalPager extends ViewGroup implements Insettable { break; - case MotionEvent.ACTION_DOWN: + case MotionEvent.ACTION_DOWN : // Remember location of down touch mLastMotionX = x; mLastMotionY = y; mAllowLongPress = true; /* - * If being flinged and user touches the screen, initiate drag; - * otherwise don't. mScroller.isFinished should be false when - * being flinged. + * If being flinged and user touches the screen, initiate drag; otherwise don't. + * mScroller.isFinished should be false when being flinged. */ - mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST - : TOUCH_STATE_HORIZONTAL_SCROLLING; + mTouchState = mScroller.isFinished() ? TOUCH_STATE_REST : TOUCH_STATE_HORIZONTAL_SCROLLING; break; - case MotionEvent.ACTION_CANCEL: - case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL : + case MotionEvent.ACTION_UP : mTouchState = TOUCH_STATE_REST; break; } /* - * The only time we want to intercept motion events is if we are in the - * drag mode. + * The only time we want to intercept motion events is if we are in the drag + * mode. */ return mTouchState != TOUCH_STATE_REST; } private void checkStartScroll(float x, float y) { /* - * Locally do absolute value. mLastMotionX is set to the y value - * of the down event. + * Locally do absolute value. mLastMotionX is set to the y value of the down + * event. */ final int xDiff = (int) Math.abs(x - mLastMotionX); final int yDiff = (int) Math.abs(y - mLastMotionY); @@ -372,7 +367,8 @@ public class HorizontalPager extends ViewGroup implements Insettable { } private boolean inThresholdRegion() { - return (mLastMotionRawY / BlissLauncher.getApplication(getContext()).getDeviceProfile().availableHeightPx) > (float) 1 / 5; + return (mLastMotionRawY + / BlissLauncher.getApplication(getContext()).getDeviceProfile().availableHeightPx) > (float) 1 / 5; } void enableChildrenCache() { @@ -386,11 +382,11 @@ public class HorizontalPager extends ViewGroup implements Insettable { @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouchEvent(MotionEvent ev) { - /*if (gestureDetectorCompat.onTouchEvent(ev)) { - return true; - } else { - - }*/ + /* + * if (gestureDetectorCompat.onTouchEvent(ev)) { return true; } else { + * + * } + */ if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } @@ -401,10 +397,10 @@ public class HorizontalPager extends ViewGroup implements Insettable { final float y = ev.getY(); if (mIsUiCreated) { switch (action) { - case MotionEvent.ACTION_DOWN: + case MotionEvent.ACTION_DOWN : /* - * If being flinged and user touches, stop the fling. isFinished - * will be false if being flinged. + * If being flinged and user touches, stop the fling. isFinished will be false + * if being flinged. */ if (!mScroller.isFinished()) { mScroller.abortAnimation(); @@ -414,7 +410,7 @@ public class HorizontalPager extends ViewGroup implements Insettable { mLastMotionX = x; mLastMotionY = y; break; - case MotionEvent.ACTION_MOVE: + case MotionEvent.ACTION_MOVE : if (mTouchState == TOUCH_STATE_REST) { checkStartScroll(x, y); } else if (mTouchState == TOUCH_STATE_VERTICAL_SCROLLING) { @@ -426,20 +422,19 @@ public class HorizontalPager extends ViewGroup implements Insettable { mLastMotionX = x; // Apply friction to scrolling past boundaries. - if (getScrollX() < 0 || getScrollX() > getChildAt( - getChildCount() - 1).getLeft()) { + if (getScrollX() < 0 || getScrollX() > getChildAt(getChildCount() - 1).getLeft()) { deltaX /= 2; } scrollBy(deltaX, 0); - /*if ((currentPage == 0 && deltaX > 0) || (currentPage == 1 && deltaX < - 0)) { - Log.i(TAG, "onTouchEvent: "+getChildAt(currentPage).getLeft()); - mDock.setTranslationX(getChildAt(currentPage).getLeft()); - }*/ + /* + * if ((currentPage == 0 && deltaX > 0) || (currentPage == 1 && deltaX < 0)) { + * Log.i(TAG, "onTouchEvent: "+getChildAt(currentPage).getLeft()); + * mDock.setTranslationX(getChildAt(currentPage).getLeft()); } + */ } break; - case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_UP : if (mTouchState == TOUCH_STATE_VERTICAL_SCROLLING) { ((OnSwipeDownListener) getContext()).onSwipeFinish(); } @@ -451,8 +446,7 @@ public class HorizontalPager extends ViewGroup implements Insettable { if (velocityX > SNAP_VELOCITY && currentPage > 0) { // Fling hard enough to move left snapToPage(currentPage - 1); - } else if (velocityX < -SNAP_VELOCITY - && currentPage < getChildCount() - 1) { + } else if (velocityX < -SNAP_VELOCITY && currentPage < getChildCount() - 1) { // Fling hard enough to move right snapToPage(currentPage + 1); } else { @@ -466,7 +460,7 @@ public class HorizontalPager extends ViewGroup implements Insettable { } mTouchState = TOUCH_STATE_REST; break; - case MotionEvent.ACTION_CANCEL: + case MotionEvent.ACTION_CANCEL : mTouchState = TOUCH_STATE_REST; } } @@ -529,8 +523,7 @@ public class HorizontalPager extends ViewGroup implements Insettable { } public void scrollRight(int duration) { - if (currentPage < getChildCount() - 1 - && mScroller.isFinished()) { + if (currentPage < getChildCount() - 1 && mScroller.isFinished()) { snapToPage(currentPage + 1, duration); } } @@ -558,7 +551,8 @@ public class HorizontalPager extends ViewGroup implements Insettable { @Override public void setInsets(Rect insets) { - if (insets == null) return; + if (insets == null) + return; updateInsetsForChildren(); this.insets = insets; postInvalidate(); @@ -603,16 +597,15 @@ public class HorizontalPager extends ViewGroup implements Insettable { out.writeInt(currentScreen); } - public static final Parcelable.Creator CREATOR = - new Parcelable.Creator() { - public SavedState createFromParcel(Parcel in) { - return new SavedState(in); - } + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public SavedState createFromParcel(Parcel in) { + return new SavedState(in); + } - public SavedState[] newArray(int size) { - return new SavedState[size]; - } - }; + public SavedState[] newArray(int size) { + return new SavedState[size]; + } + }; } public void addOnScrollListener(OnScrollListener listener) { @@ -628,20 +621,21 @@ public class HorizontalPager extends ViewGroup implements Insettable { */ public interface OnScrollListener { /** - * Receives the current scroll X value. This value will be adjusted to assume the left edge - * of the first - * page has a scroll position of 0. Note that values less than 0 and greater than the right - * edge of the - * last page are possible due to touch events scrolling beyond the edges. + * Receives the current scroll X value. This value will be adjusted to assume + * the left edge of the first page has a scroll position of 0. Note that values + * less than 0 and greater than the right edge of the last page are possible due + * to touch events scrolling beyond the edges. * - * @param scrollX Scroll X value + * @param scrollX + * Scroll X value */ void onScroll(int scrollX); /** * Invoked when scrolling is finished (settled on a page, centered). * - * @param currentPage The current page + * @param currentPage + * The current page */ void onViewScrollFinished(int currentPage); } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/InsettableFrameLayout.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/InsettableFrameLayout.java index af588399b5d76a0d968a9531e212ac573a206176..5287765da76a69b12c91e1e2566ddfa4b5d919a7 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/InsettableFrameLayout.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/InsettableFrameLayout.java @@ -8,7 +8,6 @@ import android.view.View; import android.view.ViewDebug; import android.view.ViewGroup; import android.widget.FrameLayout; - import foundation.e.blisslauncher.R; public class InsettableFrameLayout extends FrameLayout implements Insettable { @@ -74,10 +73,8 @@ public class InsettableFrameLayout extends FrameLayout implements Insettable { public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); - TypedArray a = c.obtainStyledAttributes(attrs, - R.styleable.InsettableFrameLayout_Layout); - ignoreInsets = a.getBoolean( - R.styleable.InsettableFrameLayout_Layout_layout_ignoreInsets, false); + TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.InsettableFrameLayout_Layout); + ignoreInsets = a.getBoolean(R.styleable.InsettableFrameLayout_Layout_layout_ignoreInsets, false); a.recycle(); } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/InsettableLinearLayout.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/InsettableLinearLayout.java index 5a37a6aa6ba35c3b18578924274ebc9d2854f9a8..0b7cb3a956b67cbe214307aa3d391800e444ccf6 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/InsettableLinearLayout.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/InsettableLinearLayout.java @@ -8,7 +8,6 @@ import android.view.View; import android.view.ViewDebug; import android.view.ViewGroup; import android.widget.LinearLayout; - import foundation.e.blisslauncher.R; public class InsettableLinearLayout extends LinearLayout implements Insettable { @@ -86,10 +85,8 @@ public class InsettableLinearLayout extends LinearLayout implements Insettable { public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); - TypedArray a = c.obtainStyledAttributes(attrs, - R.styleable.InsettableFrameLayout_Layout); - ignoreInsets = a.getBoolean( - R.styleable.InsettableFrameLayout_Layout_layout_ignoreInsets, false); + TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.InsettableFrameLayout_Layout); + ignoreInsets = a.getBoolean(R.styleable.InsettableFrameLayout_Layout_layout_ignoreInsets, false); a.recycle(); } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/InsettableRelativeLayout.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/InsettableRelativeLayout.java index 5337979aa5407e1eef21effeca4b15030bb182ca..605d9cc5d30ad6832dc08184e96ac80809c435f3 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/InsettableRelativeLayout.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/InsettableRelativeLayout.java @@ -8,7 +8,6 @@ import android.view.View; import android.view.ViewGroup; import android.view.WindowInsets; import android.widget.RelativeLayout; - import foundation.e.blisslauncher.BlissLauncher; import foundation.e.blisslauncher.R; @@ -17,7 +16,6 @@ public class InsettableRelativeLayout extends RelativeLayout { private final Context mContext; protected Rect mInsets = new Rect(); - public InsettableRelativeLayout(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; @@ -34,9 +32,9 @@ public class InsettableRelativeLayout extends RelativeLayout { private void updateChildInsets() { int childCount = getChildCount(); - for (int index = 0; index < childCount; ++index){ + for (int index = 0; index < childCount; ++index) { View child = getChildAt(index); - if(child instanceof Insettable) { + if (child instanceof Insettable) { ((Insettable) child).setInsets(mInsets); } } @@ -68,10 +66,8 @@ public class InsettableRelativeLayout extends RelativeLayout { public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); - TypedArray a = c.obtainStyledAttributes(attrs, - R.styleable.InsettableFrameLayout_Layout); - ignoreInsets = a.getBoolean( - R.styleable.InsettableFrameLayout_Layout_layout_ignoreInsets, false); + TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.InsettableFrameLayout_Layout); + ignoreInsets = a.getBoolean(R.styleable.InsettableFrameLayout_Layout_layout_ignoreInsets, false); a.recycle(); } @@ -89,4 +85,4 @@ public class InsettableRelativeLayout extends RelativeLayout { super.onViewAdded(child); updateChildInsets(); } -} \ No newline at end of file +} diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/InsettableScrollLayout.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/InsettableScrollLayout.java index 11fb75640a2a5d9225b202c98a77736bb9ccf682..d8cc2af405d67083456630b4e1a5444d21ae02e2 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/InsettableScrollLayout.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/InsettableScrollLayout.java @@ -9,7 +9,6 @@ import android.view.ViewDebug; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ScrollView; - import foundation.e.blisslauncher.R; public class InsettableScrollLayout extends ScrollView implements Insettable { @@ -75,10 +74,8 @@ public class InsettableScrollLayout extends ScrollView implements Insettable { public LayoutParams(Context c, AttributeSet attrs) { super(c, attrs); - TypedArray a = c.obtainStyledAttributes(attrs, - R.styleable.InsettableFrameLayout_Layout); - ignoreInsets = a.getBoolean( - R.styleable.InsettableFrameLayout_Layout_layout_ignoreInsets, false); + TypedArray a = c.obtainStyledAttributes(attrs, R.styleable.InsettableFrameLayout_Layout); + ignoreInsets = a.getBoolean(R.styleable.InsettableFrameLayout_Layout_layout_ignoreInsets, false); a.recycle(); } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/PageIndicatorLinearLayout.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/PageIndicatorLinearLayout.java index 25514bcb9348c7a33aee3f7fb4067c075472b0f1..b9f44e9f2791bd22511b379ec5b376574c1500ec 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/PageIndicatorLinearLayout.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/PageIndicatorLinearLayout.java @@ -3,13 +3,10 @@ package foundation.e.blisslauncher.core.customviews; import android.content.Context; import android.util.AttributeSet; import android.widget.LinearLayout; - import androidx.annotation.Nullable; - import foundation.e.blisslauncher.BlissLauncher; import foundation.e.blisslauncher.core.DeviceProfile; - public class PageIndicatorLinearLayout extends LinearLayout { private Context mContext; @@ -17,13 +14,11 @@ public class PageIndicatorLinearLayout extends LinearLayout { this(context, null); } - public PageIndicatorLinearLayout(Context context, - @Nullable AttributeSet attrs) { + public PageIndicatorLinearLayout(Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } - public PageIndicatorLinearLayout(Context context, @Nullable AttributeSet attrs, - int defStyleAttr) { + public PageIndicatorLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.mContext = context; } @@ -32,7 +27,6 @@ public class PageIndicatorLinearLayout extends LinearLayout { protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); DeviceProfile deviceProfile = BlissLauncher.getApplication(mContext).getDeviceProfile(); - setMeasuredDimension(deviceProfile.getAvailableWidthPx(), - deviceProfile.getPageIndicatorHeight()); + setMeasuredDimension(deviceProfile.getAvailableWidthPx(), deviceProfile.getPageIndicatorHeight()); } } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/PagedView.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/PagedView.java index 9ec64ffa76b0fbe2c0f0b8ebd6374facad71ed68..5ef838c892a128ffa61799b29f7b149f6ce05f2e 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/PagedView.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/PagedView.java @@ -39,13 +39,11 @@ import android.view.accessibility.AccessibilityNodeInfo; import android.view.animation.Interpolator; import android.widget.ScrollView; import android.widget.Scroller; - -import java.util.ArrayList; - import foundation.e.blisslauncher.R; import foundation.e.blisslauncher.core.Utilities; import foundation.e.blisslauncher.core.customviews.pageindicators.PageIndicator; import foundation.e.blisslauncher.core.touch.OverScroll; +import java.util.ArrayList; /** * An abstraction of the original Workspace which supports browsing through a @@ -62,15 +60,17 @@ public abstract class PagedView extends ViewGrou public static final int SLOW_PAGE_SNAP_ANIMATION_DURATION = 950; // OverScroll constants - private final static int OVERSCROLL_PAGE_SNAP_ANIMATION_DURATION = 270; + private static final int OVERSCROLL_PAGE_SNAP_ANIMATION_DURATION = 270; private static final float RETURN_TO_ORIGINAL_PAGE_THRESHOLD = 0.33f; - // The page is moved more than halfway, automatically move to the next page on touch up. + // The page is moved more than halfway, automatically move to the next page on + // touch up. private static final float SIGNIFICANT_MOVE_THRESHOLD = 0.4f; private static final float MAX_SCROLL_PROGRESS = 1.0f; - // The following constants need to be scaled based on density. The scaled versions will be + // The following constants need to be scaled based on density. The scaled + // versions will be // assigned to the corresponding member variables below. private static final int FLING_THRESHOLD_VELOCITY = 500; private static final int MIN_SNAP_VELOCITY = 1500; @@ -92,6 +92,7 @@ public abstract class PagedView extends ViewGrou @ViewDebug.ExportedProperty(category = "launcher") protected int mNextPage = INVALID_PAGE; + protected int mMaxScrollX; public Scroller mScroller; private Interpolator mDefaultInterpolator; @@ -106,10 +107,10 @@ public abstract class PagedView extends ViewGrou protected int[] mPageScrolls; - protected final static int TOUCH_STATE_REST = 0; - protected final static int TOUCH_STATE_SCROLLING = 1; - protected final static int TOUCH_STATE_PREV_PAGE = 2; - protected final static int TOUCH_STATE_NEXT_PAGE = 3; + protected static final int TOUCH_STATE_REST = 0; + protected static final int TOUCH_STATE_SCROLLING = 1; + protected static final int TOUCH_STATE_PREV_PAGE = 2; + protected static final int TOUCH_STATE_NEXT_PAGE = 3; protected int mTouchState = TOUCH_STATE_REST; @@ -125,8 +126,10 @@ public abstract class PagedView extends ViewGrou protected boolean mWasInOverscroll = false; - // mOverScrollX is equal to getScrollX() when we're within the normal scroll range. Otherwise - // it is equal to the scaled overscroll position. We use a separate value so as to prevent + // mOverScrollX is equal to getScrollX() when we're within the normal scroll + // range. Otherwise + // it is equal to the scaled overscroll position. We use a separate value so as + // to prevent // the screens from continuing to translate beyond the normal bounds. protected int mOverScrollX; @@ -158,8 +161,7 @@ public abstract class PagedView extends ViewGrou public PagedView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); - TypedArray a = context.obtainStyledAttributes(attrs, - R.styleable.PagedView, defStyle, 0); + TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PagedView, defStyle, 0); mPageIndicatorViewId = a.getResourceId(R.styleable.PagedView_pageIndicator, -1); a.recycle(); @@ -168,9 +170,7 @@ public abstract class PagedView extends ViewGrou init(); } - /** - * Initializes various states for this workspace. - */ + /** Initializes various states for this workspace. */ protected void init() { mScroller = new Scroller(getContext()); mCurrentPage = 0; @@ -201,18 +201,17 @@ public abstract class PagedView extends ViewGrou } /** - * Returns the index of the currently displayed page. When in free scroll mode, this is the page - * that the user was on before entering free scroll mode (e.g. the home screen page they - * long-pressed on to enter the overview). Try using {@link #getPageNearestToCenterOfScreen()} - * to get the page the user is currently scrolling over. + * Returns the index of the currently displayed page. When in free scroll mode, + * this is the page that the user was on before entering free scroll mode (e.g. + * the home screen page they long-pressed on to enter the overview). Try using + * {@link #getPageNearestToCenterOfScreen()} to get the page the user is + * currently scrolling over. */ public int getCurrentPage() { return mCurrentPage; } - /** - * Returns the index of page to be shown immediately afterwards. - */ + /** Returns the index of page to be shown immediately afterwards. */ public int getNextPage() { return (mNextPage != INVALID_PAGE) ? mNextPage : mCurrentPage; } @@ -230,9 +229,9 @@ public abstract class PagedView extends ViewGrou } /** - * Updates the scroll of the current page immediately to its final scroll position. We use this - * in CustomizePagedView to allow tabs to share the same PagedView while resetting the scroll of - * the previous tab page. + * Updates the scroll of the current page immediately to its final scroll + * position. We use this in CustomizePagedView to allow tabs to share the same + * PagedView while resetting the scroll of the previous tab page. */ protected void updateCurrentPageScroll() { // If the current page is invalid, just reset the scroll position to zero @@ -270,14 +269,13 @@ public abstract class PagedView extends ViewGrou return Utilities.boundToRange(newPage, 0, getPageCount() - 1); } - /** - * Sets the current page. - */ + /** Sets the current page. */ public void setCurrentPage(int currentPage) { if (!mScroller.isFinished()) { abortScrollerAnimation(true); } - // don't introduce any checks like mCurrentPage == currentPage here-- if we change the + // don't introduce any checks like mCurrentPage == currentPage here-- if we + // change the // the default if (getChildCount() == 0) { return; @@ -290,8 +288,8 @@ public abstract class PagedView extends ViewGrou } /** - * Should be called whenever the page changes. In the case of a scroll, we wait until the page - * has settled. + * Should be called whenever the page changes. In the case of a scroll, we wait + * until the page has settled. */ protected void notifyPageSwitchListener(int prevPage) { updatePageIndicator(); @@ -302,6 +300,7 @@ public abstract class PagedView extends ViewGrou mPageIndicator.setActiveMarker(getNextPage()); } } + protected void pageBeginTransition() { if (!mIsPageInTransition) { mIsPageInTransition = true; @@ -321,15 +320,15 @@ public abstract class PagedView extends ViewGrou } /** - * Called when the page starts moving as part of the scroll. Subclasses can override this - * to provide custom behavior during animation. + * Called when the page starts moving as part of the scroll. Subclasses can + * override this to provide custom behavior during animation. */ protected void onPageBeginTransition() { } /** - * Called when the page ends moving as part of the scroll. Subclasses can override this - * to provide custom behavior during animation. + * Called when the page ends moving as part of the scroll. Subclasses can + * override this to provide custom behavior during animation. */ protected void onPageEndTransition() { mWasInOverscroll = false; @@ -394,7 +393,8 @@ public abstract class PagedView extends ViewGrou private void sendScrollAccessibilityEvent() { } - // we moved this functionality to a helper function so SmoothPagedView can reuse it + // we moved this functionality to a helper function so SmoothPagedView can reuse + // it protected boolean computeScrollHelper() { return computeScrollHelper(true); } @@ -405,8 +405,7 @@ public abstract class PagedView extends ViewGrou protected boolean computeScrollHelper(boolean shouldInvalidate) { if (mScroller.computeScrollOffset()) { // Don't bother scrolling if the page does not need to be moved - if (getUnboundedScrollX() != mScroller.getCurrX() - || getScrollY() != mScroller.getCurrY() + if (getUnboundedScrollX() != mScroller.getCurrX() || getScrollY() != mScroller.getCurrY() || mOverScrollX != mScroller.getCurrX()) { scrollTo(mScroller.getCurrX(), mScroller.getCurrY()); } @@ -445,8 +444,7 @@ public abstract class PagedView extends ViewGrou } public int getNormalChildHeight() { - return getExpectedHeight() - getPaddingTop() - getPaddingBottom() - - mInsets.top - mInsets.bottom; + return getExpectedHeight() - getPaddingTop() - getPaddingBottom() - mInsets.top - mInsets.bottom; } public int getExpectedWidth() { @@ -454,8 +452,7 @@ public abstract class PagedView extends ViewGrou } public int getNormalChildWidth() { - return getExpectedWidth() - getPaddingLeft() - getPaddingRight() - - mInsets.left - mInsets.right; + return getExpectedWidth() - getPaddingLeft() - getPaddingRight() - mInsets.left - mInsets.right; } @Override @@ -477,7 +474,8 @@ public abstract class PagedView extends ViewGrou return; } - // We measure the dimensions of the PagedView to be larger than the pages so that when we + // We measure the dimensions of the PagedView to be larger than the pages so + // that when we // zoom out (and scale down), the view is still contained in the parent int widthMode = MeasureSpec.getMode(widthMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); @@ -497,14 +495,14 @@ public abstract class PagedView extends ViewGrou // The children are given the same width and height as the workspace // unless they were set to WRAP_CONTENT - if (DEBUG) Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize); + if (DEBUG) + Log.d(TAG, "PagedView.onMeasure(): " + widthSize + ", " + heightSize); - int myWidthSpec = MeasureSpec.makeMeasureSpec( - widthSize - mInsets.left - mInsets.right, MeasureSpec.EXACTLY); - int myHeightSpec = MeasureSpec.makeMeasureSpec( - heightSize - mInsets.top - mInsets.bottom, MeasureSpec.EXACTLY); + int myWidthSpec = MeasureSpec.makeMeasureSpec(widthSize - mInsets.left - mInsets.right, MeasureSpec.EXACTLY); + int myHeightSpec = MeasureSpec.makeMeasureSpec(heightSize - mInsets.top - mInsets.bottom, MeasureSpec.EXACTLY); - // measureChildren takes accounts for content padding, we only need to care about extra + // measureChildren takes accounts for content padding, we only need to care + // about extra // space due to insets. measureChildren(myWidthSpec, myHeightSpec); setMeasuredDimension(widthSize, heightSize); @@ -525,25 +523,28 @@ public abstract class PagedView extends ViewGrou return; } - if (DEBUG) Log.d(TAG, "PagedView.onLayout()"); + if (DEBUG) + Log.d(TAG, "PagedView.onLayout()"); if (getPageScrolls(mPageScrolls, true, SIMPLE_SCROLL_LOGIC)) { pageScrollChanged = true; } final LayoutTransition transition = getLayoutTransition(); - // If the transition is running defer updating max scroll, as some empty pages could + // If the transition is running defer updating max scroll, as some empty pages + // could // still be present, and a max scroll change could cause sudden jumps in scroll. if (transition != null && transition.isRunning()) { transition.addTransitionListener(new LayoutTransition.TransitionListener() { @Override - public void startTransition(LayoutTransition transition, ViewGroup container, - View view, int transitionType) { } + public void startTransition(LayoutTransition transition, ViewGroup container, View view, + int transitionType) { + } @Override - public void endTransition(LayoutTransition transition, ViewGroup container, - View view, int transitionType) { + public void endTransition(LayoutTransition transition, ViewGroup container, View view, + int transitionType) { // Wait until all transitions are complete. if (!transition.isRunning()) { transition.removeTransitionListener(this); @@ -566,20 +567,20 @@ public abstract class PagedView extends ViewGrou } /** - * Initializes {@code outPageScrolls} with scroll positions for view at that index. The length - * of {@code outPageScrolls} should be same as the the childCount - * + * Initializes {@code outPageScrolls} with scroll positions for view at that + * index. The length of {@code outPageScrolls} should be same as the the + * childCount */ protected boolean getPageScrolls(int[] outPageScrolls, boolean layoutChildren, - ComputePageScrollsLogic scrollLogic) { + ComputePageScrollsLogic scrollLogic) { final int childCount = getChildCount(); final int startIndex = mIsRtl ? childCount - 1 : 0; final int endIndex = mIsRtl ? -1 : childCount; final int delta = mIsRtl ? -1 : 1; - final int verticalCenter = (getPaddingTop() + getMeasuredHeight() + mInsets.top - - mInsets.bottom - getPaddingBottom()) / 2; + final int verticalCenter = (getPaddingTop() + getMeasuredHeight() + mInsets.top - mInsets.bottom + - getPaddingBottom()) / 2; final int scrollOffsetLeft = mInsets.left + getPaddingLeft(); final int scrollOffsetRight = getWidth() - getPaddingRight() - mInsets.right; @@ -597,11 +598,12 @@ public abstract class PagedView extends ViewGrou child.layout(childLeft, childTop, childRight, childTop + childHeight); } - // In case the pages are of different width, align the page to left or right edge + // In case the pages are of different width, align the page to left or right + // edge // based on the orientation. final int pageScroll = mIsRtl ? (childLeft - scrollOffsetLeft) - : Math.max(0, childRight - scrollOffsetRight); + : Math.max(0, childRight - scrollOffsetRight); if (outPageScrolls[i] != pageScroll) { pageScrollChanged = true; outPageScrolls[i] = pageScroll; @@ -640,7 +642,8 @@ public abstract class PagedView extends ViewGrou if (mPageIndicator != null) { mPageIndicator.setMarkersCount(getChildCount()); } - // This ensures that when children are added, they get the correct transforms / alphas + // This ensures that when children are added, they get the correct transforms / + // alphas // in accordance with any scroll effects. invalidate(); } @@ -659,7 +662,8 @@ public abstract class PagedView extends ViewGrou } protected int getChildOffset(int index) { - if (index < 0 || index > getChildCount() - 1) return 0; + if (index < 0 || index > getChildCount() - 1) + return 0; return getPageAt(index).getLeft(); } @@ -735,7 +739,7 @@ public abstract class PagedView extends ViewGrou if (mCurrentPage > 0) { getPageAt(mCurrentPage - 1).addFocusables(views, direction, focusableMode); } - } else if (direction == View.FOCUS_RIGHT){ + } else if (direction == View.FOCUS_RIGHT) { if (mCurrentPage < getPageCount() - 1) { getPageAt(mCurrentPage + 1).addFocusables(views, direction, focusableMode); } @@ -746,8 +750,9 @@ public abstract class PagedView extends ViewGrou * If one of our descendant views decides that it could be focused now, only * pass that along if it's on the current page. * - * This happens when live folders requery, and if they're off page, they - * end up calling requestFocus, which pulls it on page. + *

+ * This happens when live folders requery, and if they're off page, they end up + * calling requestFocus, which pulls it on page. */ @Override public void focusableViewAvailable(View focused) { @@ -763,23 +768,21 @@ public abstract class PagedView extends ViewGrou } ViewParent parent = v.getParent(); if (parent instanceof View) { - v = (View)v.getParent(); + v = (View) v.getParent(); } else { return; } } } - /** - * {@inheritDoc} - */ + /** {@inheritDoc} */ @Override public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { if (disallowIntercept) { // We need to make sure to cancel our long press if // a scrollable widget takes over touch events final View currentPage = getPageAt(mCurrentPage); - if(currentPage != null) { + if (currentPage != null) { currentPage.cancelLongPress(); } } @@ -795,28 +798,27 @@ public abstract class PagedView extends ViewGrou @Override public boolean onInterceptTouchEvent(MotionEvent ev) { /* - * This method JUST determines whether we want to intercept the motion. - * If we return true, onTouchEvent will be called and we do the actual - * scrolling there. + * This method JUST determines whether we want to intercept the motion. If we + * return true, onTouchEvent will be called and we do the actual scrolling + * there. */ acquireVelocityTrackerAndAddMovement(ev); // Skip touch handling if there are no pages to swipe - if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev); + if (getChildCount() <= 0) + return super.onInterceptTouchEvent(ev); /* - * Shortcut the most recurring case: the user is in the dragging - * state and he is moving his finger. We want to intercept this - * motion. + * Shortcut the most recurring case: the user is in the dragging state and he is + * moving his finger. We want to intercept this motion. */ final int action = ev.getAction(); - if ((action == MotionEvent.ACTION_MOVE) && - (mTouchState == TOUCH_STATE_SCROLLING)) { + if ((action == MotionEvent.ACTION_MOVE) && (mTouchState == TOUCH_STATE_SCROLLING)) { return true; } switch (action & MotionEvent.ACTION_MASK) { - case MotionEvent.ACTION_MOVE: { + case MotionEvent.ACTION_MOVE : { /* * mIsBeingDragged == false, otherwise the shortcut would have caught it. Check * whether the user has moved far enough from his original down touch. @@ -824,15 +826,19 @@ public abstract class PagedView extends ViewGrou if (mActivePointerId != INVALID_POINTER) { determineScrollingStart(ev); } - // if mActivePointerId is INVALID_POINTER, then we must have missed an ACTION_DOWN - // event. in that case, treat the first occurence of a move event as a ACTION_DOWN + // if mActivePointerId is INVALID_POINTER, then we must have missed an + // ACTION_DOWN + // event. in that case, treat the first occurence of a move event as a + // ACTION_DOWN // i.e. fall through to the next case (don't break) - // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all events - // while it's small- this was causing a crash before we checked for INVALID_POINTER) + // (We sometimes miss ACTION_DOWN events in Workspace because it ignores all + // events + // while it's small- this was causing a crash before we checked for + // INVALID_POINTER) break; } - case MotionEvent.ACTION_DOWN: { + case MotionEvent.ACTION_DOWN : { final float x = ev.getX(); final float y = ev.getY(); // Remember location of down touch @@ -844,9 +850,8 @@ public abstract class PagedView extends ViewGrou mActivePointerId = ev.getPointerId(0); /* - * If being flinged and user touches the screen, initiate drag; - * otherwise don't. mScroller.isFinished should be false when - * being flinged. + * If being flinged and user touches the screen, initiate drag; otherwise don't. + * mScroller.isFinished should be false when being flinged. */ final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX()); final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop / 3); @@ -868,20 +873,20 @@ public abstract class PagedView extends ViewGrou break; } - case MotionEvent.ACTION_UP: - case MotionEvent.ACTION_CANCEL: + case MotionEvent.ACTION_UP : + case MotionEvent.ACTION_CANCEL : resetTouchState(); break; - case MotionEvent.ACTION_POINTER_UP: + case MotionEvent.ACTION_POINTER_UP : onSecondaryPointerUp(ev); releaseVelocityTracker(); break; } /* - * The only time we want to intercept motion events is if we are in the - * drag mode. + * The only time we want to intercept motion events is if we are in the drag + * mode. */ return mTouchState != TOUCH_STATE_REST; } @@ -901,12 +906,14 @@ public abstract class PagedView extends ViewGrou protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) { // Disallow scrolling if we don't have a valid pointer index final int pointerIndex = ev.findPointerIndex(mActivePointerId); - if (pointerIndex == -1) return; + if (pointerIndex == -1) + return; // Disallow scrolling if we started the gesture from outside the viewport final float x = ev.getX(pointerIndex); final float y = ev.getY(pointerIndex); - if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return; + if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) + return; final int xDiff = (int) Math.abs(x - mLastMotionX); @@ -957,7 +964,7 @@ public abstract class PagedView extends ViewGrou float scrollProgress = delta / (totalDistance * 1.0f); scrollProgress = Math.min(scrollProgress, MAX_SCROLL_PROGRESS); - scrollProgress = Math.max(scrollProgress, - MAX_SCROLL_PROGRESS); + scrollProgress = Math.max(scrollProgress, -MAX_SCROLL_PROGRESS); return scrollProgress; } @@ -969,7 +976,8 @@ public abstract class PagedView extends ViewGrou } } - // While layout transitions are occurring, a child's position may stray from its baseline + // While layout transitions are occurring, a child's position may stray from its + // baseline // position. This method returns the magnitude of this stray at any given time. public int getLayoutTransitionOffsetForPage(int index) { if (mPageScrolls == null || index >= mPageScrolls.length || index < 0) { @@ -984,7 +992,8 @@ public abstract class PagedView extends ViewGrou } protected void dampedOverScroll(float amount) { - if (Float.compare(amount, 0f) == 0) return; + if (Float.compare(amount, 0f) == 0) + return; int overScrollAmount = OverScroll.dampedScroll(amount, getMeasuredWidth()); if (amount < 0) { @@ -1001,7 +1010,6 @@ public abstract class PagedView extends ViewGrou dampedOverScroll(amount); } - protected void enableFreeScroll(boolean settleOnPageInFreeScroll) { setEnableFreeScroll(true); mSettleOnPageInFreeScroll = settleOnPageInFreeScroll; @@ -1029,17 +1037,18 @@ public abstract class PagedView extends ViewGrou super.onTouchEvent(ev); // Skip touch handling if there are no pages to swipe - if (getChildCount() <= 0) return super.onTouchEvent(ev); + if (getChildCount() <= 0) + return super.onTouchEvent(ev); acquireVelocityTrackerAndAddMovement(ev); final int action = ev.getAction(); switch (action & MotionEvent.ACTION_MASK) { - case MotionEvent.ACTION_DOWN: + case MotionEvent.ACTION_DOWN : /* - * If being flinged and user touches, stop the fling. isFinished - * will be false if being flinged. + * If being flinged and user touches, stop the fling. isFinished will be false + * if being flinged. */ if (!mScroller.isFinished()) { abortScrollerAnimation(false); @@ -1058,20 +1067,22 @@ public abstract class PagedView extends ViewGrou } break; - case MotionEvent.ACTION_MOVE: + case MotionEvent.ACTION_MOVE : if (mTouchState == TOUCH_STATE_SCROLLING) { // Scroll to follow the motion event final int pointerIndex = ev.findPointerIndex(mActivePointerId); - if (pointerIndex == -1) return true; + if (pointerIndex == -1) + return true; final float x = ev.getX(pointerIndex); final float deltaX = mLastMotionX + mLastMotionXRemainder - x; mTotalMotionX += Math.abs(deltaX); - // Only scroll and update mLastMotionX if we have moved some discrete amount. We - // keep the remainder because we are actually testing if we've moved from the last + // Only scroll and update mLastMotionX if we have moved some discrete amount. We + // keep the remainder because we are actually testing if we've moved from the + // last // scrolled position (which is discrete). if (Math.abs(deltaX) >= 1.0f) { scrollBy((int) deltaX, 0); @@ -1085,7 +1096,7 @@ public abstract class PagedView extends ViewGrou } break; - case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_UP : if (mTouchState == TOUCH_STATE_SCROLLING) { final int activePointerId = mActivePointerId; final int pointerIndex = ev.findPointerIndex(activePointerId); @@ -1095,8 +1106,7 @@ public abstract class PagedView extends ViewGrou int velocityX = (int) velocityTracker.getXVelocity(activePointerId); final int deltaX = (int) (x - mDownMotionX); final int pageWidth = getPageAt(mCurrentPage).getMeasuredWidth(); - boolean isSignificantMove = Math.abs(deltaX) > pageWidth * - SIGNIFICANT_MOVE_THRESHOLD; + boolean isSignificantMove = Math.abs(deltaX) > pageWidth * SIGNIFICANT_MOVE_THRESHOLD; mTotalMotionX += Math.abs(mLastMotionX + mLastMotionXRemainder - x); boolean isFling = mTotalMotionX > mTouchSlop && shouldFlingForVelocity(velocityX); @@ -1106,24 +1116,24 @@ public abstract class PagedView extends ViewGrou // in the opposite direction, we use a threshold to determine whether we should // just return to the starting page, or if we should skip one further. boolean returnToOriginalPage = false; - if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD && - Math.signum(velocityX) != Math.signum(deltaX) && isFling) { + if (Math.abs(deltaX) > pageWidth * RETURN_TO_ORIGINAL_PAGE_THRESHOLD + && Math.signum(velocityX) != Math.signum(deltaX) && isFling) { returnToOriginalPage = true; } int finalPage; // We give flings precedence over large moves, which is why we short-circuit our // test for a large move if a fling has been registered. That is, a large - // move to the left and fling to the right will register as a fling to the right. + // move to the left and fling to the right will register as a fling to the + // right. boolean isDeltaXLeft = mIsRtl ? deltaX > 0 : deltaX < 0; boolean isVelocityXLeft = mIsRtl ? velocityX > 0 : velocityX < 0; - if (((isSignificantMove && !isDeltaXLeft && !isFling) || - (isFling && !isVelocityXLeft)) && mCurrentPage > 0) { + if (((isSignificantMove && !isDeltaXLeft && !isFling) || (isFling && !isVelocityXLeft)) + && mCurrentPage > 0) { finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage - 1; snapToPageWithVelocity(finalPage, velocityX); - } else if (((isSignificantMove && isDeltaXLeft && !isFling) || - (isFling && isVelocityXLeft)) && - mCurrentPage < getChildCount() - 1) { + } else if (((isSignificantMove && isDeltaXLeft && !isFling) || (isFling && isVelocityXLeft)) + && mCurrentPage < getChildCount() - 1) { finalPage = returnToOriginalPage ? mCurrentPage : mCurrentPage + 1; snapToPageWithVelocity(finalPage, velocityX); } else { @@ -1138,28 +1148,26 @@ public abstract class PagedView extends ViewGrou int vX = (int) (-velocityX * scaleX); int initialScrollX = (int) (getScrollX() * scaleX); - mScroller.fling(initialScrollX, - getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, 0); + mScroller.fling(initialScrollX, getScrollY(), vX, 0, Integer.MIN_VALUE, Integer.MAX_VALUE, 0, + 0); int unscaledScrollX = (int) (mScroller.getFinalX() / scaleX); mNextPage = getPageNearestToCenterOfScreen(unscaledScrollX); int firstPageScroll = getScrollForPage(!mIsRtl ? 0 : getPageCount() - 1); int lastPageScroll = getScrollForPage(!mIsRtl ? getPageCount() - 1 : 0); - if (mSettleOnPageInFreeScroll && unscaledScrollX > 0 - && unscaledScrollX < mMaxScrollX) { + if (mSettleOnPageInFreeScroll && unscaledScrollX > 0 && unscaledScrollX < mMaxScrollX) { // If scrolling ends in the half of the added space that is closer to the // end, settle to the end. Otherwise snap to the nearest page. // If flinging past one of the ends, don't change the velocity as it will // get stopped at the end anyway. - final int finalX = unscaledScrollX < firstPageScroll / 2 ? - 0 : - unscaledScrollX > (lastPageScroll + mMaxScrollX) / 2 ? - mMaxScrollX : - getScrollForPage(mNextPage); + final int finalX = unscaledScrollX < firstPageScroll / 2 + ? 0 + : unscaledScrollX > (lastPageScroll + mMaxScrollX) / 2 + ? mMaxScrollX + : getScrollForPage(mNextPage); mScroller.setFinalX((int) (finalX * getScaleX())); // Ensure the scroll/snap doesn't happen too fast; - int extraScrollDuration = OVERSCROLL_PAGE_SNAP_ANIMATION_DURATION - - mScroller.getDuration(); + int extraScrollDuration = OVERSCROLL_PAGE_SNAP_ANIMATION_DURATION - mScroller.getDuration(); if (extraScrollDuration > 0) { mScroller.extendDuration(extraScrollDuration); } @@ -1193,7 +1201,7 @@ public abstract class PagedView extends ViewGrou resetTouchState(); break; - case MotionEvent.ACTION_CANCEL: + case MotionEvent.ACTION_CANCEL : if (mTouchState == TOUCH_STATE_SCROLLING) { snapToDestination(); onScrollInteractionEnd(); @@ -1201,7 +1209,7 @@ public abstract class PagedView extends ViewGrou resetTouchState(); break; - case MotionEvent.ACTION_POINTER_UP: + case MotionEvent.ACTION_POINTER_UP : onSecondaryPointerUp(ev); releaseVelocityTracker(); break; @@ -1220,9 +1228,7 @@ public abstract class PagedView extends ViewGrou mActivePointerId = INVALID_POINTER; } - /** - * Triggered by scrolling via touch - */ + /** Triggered by scrolling via touch */ protected void onScrollInteractionBegin() { } @@ -1233,7 +1239,7 @@ public abstract class PagedView extends ViewGrou public boolean onGenericMotionEvent(MotionEvent event) { if ((event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) { switch (event.getAction()) { - case MotionEvent.ACTION_SCROLL: { + case MotionEvent.ACTION_SCROLL : { // Handle mouse (or ext. device) by shifting the page depending on the scroll final float vscroll; final float hscroll; @@ -1245,8 +1251,7 @@ public abstract class PagedView extends ViewGrou hscroll = event.getAxisValue(MotionEvent.AXIS_HSCROLL); } if (hscroll != 0 || vscroll != 0) { - boolean isForwardScroll = mIsRtl ? (hscroll < 0 || vscroll < 0) - : (hscroll > 0 || vscroll > 0); + boolean isForwardScroll = mIsRtl ? (hscroll < 0 || vscroll < 0) : (hscroll > 0 || vscroll > 0); if (isForwardScroll) { scrollRight(); } else { @@ -1276,8 +1281,8 @@ public abstract class PagedView extends ViewGrou } private void onSecondaryPointerUp(MotionEvent ev) { - final int pointerIndex = (ev.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> - MotionEvent.ACTION_POINTER_INDEX_SHIFT; + final int pointerIndex = (ev.getAction() + & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT; final int pointerId = ev.getPointerId(pointerIndex); if (pointerId == mActivePointerId) { // This was our active pointer going up. Choose a new @@ -1340,9 +1345,12 @@ public abstract class PagedView extends ViewGrou return PAGE_SNAP_ANIMATION_DURATION; } - // We want the duration of the page snap animation to be influenced by the distance that - // the screen has to travel, however, we don't want this duration to be effected in a - // purely linear fashion. Instead, we use this method to moderate the effect that the distance + // We want the duration of the page snap animation to be influenced by the + // distance that + // the screen has to travel, however, we don't want this duration to be effected + // in a + // purely linear fashion. Instead, we use this method to moderate the effect + // that the distance // of travel has on the overall snap duration. private float distanceInfluenceForSnapDuration(float f) { f -= 0.5f; // center the values about 0. @@ -1359,24 +1367,29 @@ public abstract class PagedView extends ViewGrou int duration = 0; if (Math.abs(velocity) < mMinFlingVelocity) { - // If the velocity is low enough, then treat this more as an automatic page advance + // If the velocity is low enough, then treat this more as an automatic page + // advance // as opposed to an apparent physical response to flinging return snapToPage(whichPage, PAGE_SNAP_ANIMATION_DURATION); } - // Here we compute a "distance" that will be used in the computation of the overall - // snap duration. This is a function of the actual distance that needs to be traveled; - // we keep this value close to half screen size in order to reduce the variance in snap + // Here we compute a "distance" that will be used in the computation of the + // overall + // snap duration. This is a function of the actual distance that needs to be + // traveled; + // we keep this value close to half screen size in order to reduce the variance + // in snap // duration as a function of the distance the page needs to travel. float distanceRatio = Math.min(1f, 1.0f * Math.abs(delta) / (2 * halfScreenSize)); - float distance = halfScreenSize + halfScreenSize * - distanceInfluenceForSnapDuration(distanceRatio); + float distance = halfScreenSize + halfScreenSize * distanceInfluenceForSnapDuration(distanceRatio); velocity = Math.abs(velocity); velocity = Math.max(mMinSnapVelocity, velocity); - // we want the page's snap velocity to approximately match the velocity at which the - // user flings, so we scale the duration by a value near to the derivative of the scroll + // we want the page's snap velocity to approximately match the velocity at which + // the + // user flings, so we scale the duration by a value near to the derivative of + // the scroll // interpolator at zero, ie. 5. We use 4 to make it a little slower. duration = 4 * Math.round(1000 * Math.abs(distance / velocity)); @@ -1399,8 +1412,7 @@ public abstract class PagedView extends ViewGrou return snapToPage(whichPage, duration, false, interpolator); } - protected boolean snapToPage(int whichPage, int duration, boolean immediate, - TimeInterpolator interpolator) { + protected boolean snapToPage(int whichPage, int duration, boolean immediate, TimeInterpolator interpolator) { whichPage = validateNewPage(whichPage); int newX = getScrollForPage(whichPage); @@ -1413,7 +1425,7 @@ public abstract class PagedView extends ViewGrou } protected boolean snapToPage(int whichPage, int delta, int duration, boolean immediate, - TimeInterpolator interpolator) { + TimeInterpolator interpolator) { if (mFirstLayout) { setCurrentPage(whichPage); return false; @@ -1470,8 +1482,10 @@ public abstract class PagedView extends ViewGrou @Override public CharSequence getAccessibilityClassName() { - // Some accessibility services have special logic for ScrollView. Since we provide same - // accessibility info as ScrollView, inform the service to handle use the same way. + // Some accessibility services have special logic for ScrollView. Since we + // provide same + // accessibility info as ScrollView, inform the service to handle use the same + // way. return ScrollView.class.getName(); } @@ -1487,16 +1501,19 @@ public abstract class PagedView extends ViewGrou final boolean pagesFlipped = isPageOrderFlipped(); info.setScrollable(getPageCount() > 1); if (getCurrentPage() < getPageCount() - 1) { - info.addAction(pagesFlipped ? AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD + info.addAction(pagesFlipped + ? AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD : AccessibilityNodeInfo.ACTION_SCROLL_FORWARD); } if (getCurrentPage() > 0) { - info.addAction(pagesFlipped ? AccessibilityNodeInfo.ACTION_SCROLL_FORWARD + info.addAction(pagesFlipped + ? AccessibilityNodeInfo.ACTION_SCROLL_FORWARD : AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD); } // Accessibility-wise, PagedView doesn't support long click, so disabling it. - // Besides disabling the accessibility long-click, this also prevents this view from getting + // Besides disabling the accessibility long-click, this also prevents this view + // from getting // accessibility focus. info.setLongClickable(false); info.removeAction(AccessibilityNodeInfo.AccessibilityAction.ACTION_LONG_CLICK); @@ -1523,17 +1540,18 @@ public abstract class PagedView extends ViewGrou } final boolean pagesFlipped = isPageOrderFlipped(); switch (action) { - case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD: { + case AccessibilityNodeInfo.ACTION_SCROLL_FORWARD : { if (pagesFlipped ? scrollLeft() : scrollRight()) { return true; } - } break; - case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD: { + } + break; + case AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD : { if (pagesFlipped ? scrollRight() : scrollLeft()) { return true; } } - break; + break; } return false; } @@ -1543,8 +1561,7 @@ public abstract class PagedView extends ViewGrou } protected String getCurrentPageDescription() { - return getContext().getString(R.string.default_scroll_format, - getNextPage() + 1, getChildCount()); + return getContext().getString(R.string.default_scroll_format, getNextPage() + 1, getChildCount()); } protected float getDownMotionX() { diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/PathParser.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/PathParser.java index 7a00f3e63fa7bb904c8642935936bf85a757562c..3b0358bf854a9fe32b7f3456183504c5bfe080b0 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/PathParser.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/PathParser.java @@ -2,14 +2,15 @@ package foundation.e.blisslauncher.core.customviews; import android.graphics.Path; import android.util.Log; - import java.util.ArrayList; import java.util.Arrays; public class PathParser { static final String LOGTAG = PathParser.class.getSimpleName(); /** - * @param pathData The string representing a path, the same as "d" string in svg file. + * @param pathData + * The string representing a path, the same as "d" string in svg + * file. * @return the generated Path object. */ public static Path createPathFromPathData(String pathData) { @@ -19,7 +20,9 @@ public class PathParser { return path; } /** - * @param pathData The string representing a path, the same as "d" string in svg file. + * @param pathData + * The string representing a path, the same as "d" string in svg + * file. * @return an array of the PathDataNode. */ private static PathDataNode[] createNodesFromPathData(String pathData) { @@ -39,6 +42,7 @@ public class PathParser { } return list.toArray(new PathDataNode[list.size()]); } + private static int nextStart(String s, int end) { char c; while (end < s.length()) { @@ -50,14 +54,16 @@ public class PathParser { } return end; } + private static void addNode(ArrayList list, char cmd, float[] val) { list.add(new PathDataNode(cmd, val)); } /** - * Parse the floats in the string. - * This is an optimized version of parseFloat(s.split(",|\\s")); + * Parse the floats in the string. This is an optimized version of + * parseFloat(s.split(",|\\s")); * - * @param s the string containing a command and list of floats + * @param s + * the string containing a command and list of floats * @return array of floats */ private static float[] getFloats(String s) { @@ -79,15 +85,18 @@ public class PathParser { tmp[count++] = Float.parseFloat(s.substring(pos, s.length())); } return Arrays.copyOf(tmp, count); - } catch (NumberFormatException e){ - Log.e(LOGTAG,"error in parsing \""+s+"\""); + } catch (NumberFormatException e) { + Log.e(LOGTAG, "error in parsing \"" + s + "\""); throw e; } } /** * Calculate the position of the next comma or space - * @param s the string to search - * @param start the position to start searching + * + * @param s + * the string to search + * @param start + * the position to start searching * @return the position of the next comma or space or -1 if none found */ private static int extract(String s, int start) { @@ -101,9 +110,11 @@ public class PathParser { } return (comma > space) ? space : comma; } + static class PathDataNode { private char mType; private float[] mParams; + private PathDataNode(char type, float[] params) { mType = type; mParams = params; @@ -117,8 +128,8 @@ public class PathParser { previousCommand = aNode.mType; } } - private static void addCommand(Path path, float[] current, - char previousCmd, char cmd, float[] val) { + + private static void addCommand(Path path, float[] current, char previousCmd, char cmd, float[] val) { int incr = 2; float currentX = current[0]; float currentY = current[1]; @@ -127,200 +138,175 @@ public class PathParser { float reflectiveCtrlPointX; float reflectiveCtrlPointY; switch (cmd) { - case 'z': - case 'Z': + case 'z' : + case 'Z' : path.close(); return; - case 'm': - case 'M': - case 'l': - case 'L': - case 't': - case 'T': + case 'm' : + case 'M' : + case 'l' : + case 'L' : + case 't' : + case 'T' : incr = 2; break; - case 'h': - case 'H': - case 'v': - case 'V': + case 'h' : + case 'H' : + case 'v' : + case 'V' : incr = 1; break; - case 'c': - case 'C': + case 'c' : + case 'C' : incr = 6; break; - case 's': - case 'S': - case 'q': - case 'Q': + case 's' : + case 'S' : + case 'q' : + case 'Q' : incr = 4; break; - case 'a': - case 'A': + case 'a' : + case 'A' : incr = 7; break; } for (int k = 0; k < val.length; k += incr) { switch (cmd) { - case 'm': // moveto - Start a new sub-path (relative) + case 'm' : // moveto - Start a new sub-path (relative) path.rMoveTo(val[k], val[k + 1]); currentX += val[k]; currentY += val[k + 1]; break; - case 'M': // moveto - Start a new sub-path + case 'M' : // moveto - Start a new sub-path path.moveTo(val[k], val[k + 1]); currentX = val[k]; currentY = val[k + 1]; break; - case 'l': // lineto - Draw a line from the current point (relative) + case 'l' : // lineto - Draw a line from the current point (relative) path.rLineTo(val[k], val[k + 1]); currentX += val[k]; currentY += val[k + 1]; break; - case 'L': // lineto - Draw a line from the current point + case 'L' : // lineto - Draw a line from the current point path.lineTo(val[k], val[k + 1]); currentX = val[k]; currentY = val[k + 1]; break; - case 'z': // closepath - Close the current subpath - case 'Z': // closepath - Close the current subpath + case 'z' : // closepath - Close the current subpath + case 'Z' : // closepath - Close the current subpath path.close(); break; - case 'h': // horizontal lineto - Draws a horizontal line (relative) + case 'h' : // horizontal lineto - Draws a horizontal line (relative) path.rLineTo(val[k], 0); currentX += val[k]; break; - case 'H': // horizontal lineto - Draws a horizontal line + case 'H' : // horizontal lineto - Draws a horizontal line path.lineTo(val[k], currentY); currentX = val[k]; break; - case 'v': // vertical lineto - Draws a vertical line from the current point (r) + case 'v' : // vertical lineto - Draws a vertical line from the current point (r) path.rLineTo(0, val[k]); currentY += val[k]; break; - case 'V': // vertical lineto - Draws a vertical line from the current point + case 'V' : // vertical lineto - Draws a vertical line from the current point path.lineTo(currentX, val[k]); currentY = val[k]; break; - case 'c': // curveto - Draws a cubic Bézier curve (relative) - path.rCubicTo(val[k], val[k + 1], val[k + 2], val[k + 3], - val[k + 4], val[k + 5]); + case 'c' : // curveto - Draws a cubic Bézier curve (relative) + path.rCubicTo(val[k], val[k + 1], val[k + 2], val[k + 3], val[k + 4], val[k + 5]); ctrlPointX = currentX + val[k + 2]; ctrlPointY = currentY + val[k + 3]; currentX += val[k + 4]; currentY += val[k + 5]; break; - case 'C': // curveto - Draws a cubic Bézier curve - path.cubicTo(val[k], val[k + 1], val[k + 2], val[k + 3], - val[k + 4], val[k + 5]); + case 'C' : // curveto - Draws a cubic Bézier curve + path.cubicTo(val[k], val[k + 1], val[k + 2], val[k + 3], val[k + 4], val[k + 5]); currentX = val[k + 4]; currentY = val[k + 5]; ctrlPointX = val[k + 2]; ctrlPointY = val[k + 3]; break; - case 's': // smooth curveto - Draws a cubic Bézier curve (reflective cp) + case 's' : // smooth curveto - Draws a cubic Bézier curve (reflective cp) reflectiveCtrlPointX = 0; reflectiveCtrlPointY = 0; - if (previousCmd == 'c' || previousCmd == 's' - || previousCmd == 'C' || previousCmd == 'S') { + if (previousCmd == 'c' || previousCmd == 's' || previousCmd == 'C' || previousCmd == 'S') { reflectiveCtrlPointX = currentX - ctrlPointX; reflectiveCtrlPointY = currentY - ctrlPointY; } - path.rCubicTo(reflectiveCtrlPointX, reflectiveCtrlPointY, - val[k], val[k + 1], - val[k + 2], val[k + 3]); + path.rCubicTo(reflectiveCtrlPointX, reflectiveCtrlPointY, val[k], val[k + 1], val[k + 2], + val[k + 3]); ctrlPointX = currentX + val[k]; ctrlPointY = currentY + val[k + 1]; currentX += val[k + 2]; currentY += val[k + 3]; break; - case 'S': // shorthand/smooth curveto Draws a cubic Bézier curve(reflective cp) + case 'S' : // shorthand/smooth curveto Draws a cubic Bézier curve(reflective cp) reflectiveCtrlPointX = currentX; reflectiveCtrlPointY = currentY; - if (previousCmd == 'c' || previousCmd == 's' - || previousCmd == 'C' || previousCmd == 'S') { + if (previousCmd == 'c' || previousCmd == 's' || previousCmd == 'C' || previousCmd == 'S') { reflectiveCtrlPointX = 2 * currentX - ctrlPointX; reflectiveCtrlPointY = 2 * currentY - ctrlPointY; } - path.cubicTo(reflectiveCtrlPointX, reflectiveCtrlPointY, - val[k], val[k + 1], val[k + 2], val[k + 3]); + path.cubicTo(reflectiveCtrlPointX, reflectiveCtrlPointY, val[k], val[k + 1], val[k + 2], + val[k + 3]); ctrlPointX = val[k]; ctrlPointY = val[k + 1]; currentX = val[k + 2]; currentY = val[k + 3]; break; - case 'q': // Draws a quadratic Bézier (relative) + case 'q' : // Draws a quadratic Bézier (relative) path.rQuadTo(val[k], val[k + 1], val[k + 2], val[k + 3]); ctrlPointX = currentX + val[k]; ctrlPointY = currentY + val[k + 1]; currentX += val[k + 2]; currentY += val[k + 3]; break; - case 'Q': // Draws a quadratic Bézier + case 'Q' : // Draws a quadratic Bézier path.quadTo(val[k], val[k + 1], val[k + 2], val[k + 3]); ctrlPointX = val[k]; ctrlPointY = val[k + 1]; currentX = val[k + 2]; currentY = val[k + 3]; break; - case 't': // Draws a quadratic Bézier curve(reflective control point)(relative) + case 't' : // Draws a quadratic Bézier curve(reflective control point)(relative) reflectiveCtrlPointX = 0; reflectiveCtrlPointY = 0; - if (previousCmd == 'q' || previousCmd == 't' - || previousCmd == 'Q' || previousCmd == 'T') { + if (previousCmd == 'q' || previousCmd == 't' || previousCmd == 'Q' || previousCmd == 'T') { reflectiveCtrlPointX = currentX - ctrlPointX; reflectiveCtrlPointY = currentY - ctrlPointY; } - path.rQuadTo(reflectiveCtrlPointX, reflectiveCtrlPointY, - val[k], val[k + 1]); + path.rQuadTo(reflectiveCtrlPointX, reflectiveCtrlPointY, val[k], val[k + 1]); ctrlPointX = currentX + reflectiveCtrlPointX; ctrlPointY = currentY + reflectiveCtrlPointY; currentX += val[k]; currentY += val[k + 1]; break; - case 'T': // Draws a quadratic Bézier curve (reflective control point) + case 'T' : // Draws a quadratic Bézier curve (reflective control point) reflectiveCtrlPointX = currentX; reflectiveCtrlPointY = currentY; - if (previousCmd == 'q' || previousCmd == 't' - || previousCmd == 'Q' || previousCmd == 'T') { + if (previousCmd == 'q' || previousCmd == 't' || previousCmd == 'Q' || previousCmd == 'T') { reflectiveCtrlPointX = 2 * currentX - ctrlPointX; reflectiveCtrlPointY = 2 * currentY - ctrlPointY; } - path.quadTo(reflectiveCtrlPointX, reflectiveCtrlPointY, - val[k], val[k + 1]); + path.quadTo(reflectiveCtrlPointX, reflectiveCtrlPointY, val[k], val[k + 1]); ctrlPointX = reflectiveCtrlPointX; ctrlPointY = reflectiveCtrlPointY; currentX = val[k]; currentY = val[k + 1]; break; - case 'a': // Draws an elliptical arc + case 'a' : // Draws an elliptical arc // (rx ry x-axis-rotation large-arc-flag sweep-flag x y) - drawArc(path, - currentX, - currentY, - val[k + 5] + currentX, - val[k + 6] + currentY, - val[k], - val[k + 1], - val[k + 2], - val[k + 3] != 0, - val[k + 4] != 0); + drawArc(path, currentX, currentY, val[k + 5] + currentX, val[k + 6] + currentY, val[k], + val[k + 1], val[k + 2], val[k + 3] != 0, val[k + 4] != 0); currentX += val[k + 5]; currentY += val[k + 6]; ctrlPointX = currentX; ctrlPointY = currentY; break; - case 'A': // Draws an elliptical arc - drawArc(path, - currentX, - currentY, - val[k + 5], - val[k + 6], - val[k], - val[k + 1], - val[k + 2], - val[k + 3] != 0, - val[k + 4] != 0); + case 'A' : // Draws an elliptical arc + drawArc(path, currentX, currentY, val[k + 5], val[k + 6], val[k], val[k + 1], val[k + 2], + val[k + 3] != 0, val[k + 4] != 0); currentX = val[k + 5]; currentY = val[k + 6]; ctrlPointX = currentX; @@ -334,16 +320,9 @@ public class PathParser { current[2] = ctrlPointX; current[3] = ctrlPointY; } - private static void drawArc(Path p, - float x0, - float y0, - float x1, - float y1, - float a, - float b, - float theta, - boolean isMoreThanHalf, - boolean isPositiveArc) { + + private static void drawArc(Path p, float x0, float y0, float x1, float y1, float a, float b, float theta, + boolean isMoreThanHalf, boolean isPositiveArc) { /* Convert rotation angle from degrees to radians */ double thetaD = Math.toRadians(theta); /* Pre-compute rotation matrix entries */ @@ -370,8 +349,7 @@ public class PathParser { if (disc < 0.0) { Log.w(LOGTAG, "Points are too far apart " + dsq); float adjust = (float) (Math.sqrt(dsq) / 1.99999); - drawArc(p, x0, y0, x1, y1, a * adjust, - b * adjust, theta, isMoreThanHalf, isPositiveArc); + drawArc(p, x0, y0, x1, y1, a * adjust, b * adjust, theta, isMoreThanHalf, isPositiveArc); return; /* Points are too far apart */ } double s = Math.sqrt(disc); @@ -406,27 +384,31 @@ public class PathParser { /** * Converts an arc to cubic Bezier segments and records them in p. * - * @param p The target for the cubic Bezier segments - * @param cx The x coordinate center of the ellipse - * @param cy The y coordinate center of the ellipse - * @param a The radius of the ellipse in the horizontal direction - * @param b The radius of the ellipse in the vertical direction - * @param e1x E(eta1) x coordinate of the starting point of the arc - * @param e1y E(eta2) y coordinate of the starting point of the arc - * @param theta The angle that the ellipse bounding rectangle makes with horizontal plane - * @param start The start angle of the arc on the ellipse - * @param sweep The angle (positive or negative) of the sweep of the arc on the ellipse + * @param p + * The target for the cubic Bezier segments + * @param cx + * The x coordinate center of the ellipse + * @param cy + * The y coordinate center of the ellipse + * @param a + * The radius of the ellipse in the horizontal direction + * @param b + * The radius of the ellipse in the vertical direction + * @param e1x + * E(eta1) x coordinate of the starting point of the arc + * @param e1y + * E(eta2) y coordinate of the starting point of the arc + * @param theta + * The angle that the ellipse bounding rectangle makes with + * horizontal plane + * @param start + * The start angle of the arc on the ellipse + * @param sweep + * The angle (positive or negative) of the sweep of the arc on the + * ellipse */ - private static void arcToBezier(Path p, - double cx, - double cy, - double a, - double b, - double e1x, - double e1y, - double theta, - double start, - double sweep) { + private static void arcToBezier(Path p, double cx, double cy, double a, double b, double e1x, double e1y, + double theta, double start, double sweep) { // Taken from equations at: http://spaceroots.org/documents/ellipse/node8.html // and http://www.spaceroots.org/documents/ellipse/node22.html // Maximum of 45 degrees per cubic Bezier segment @@ -448,18 +430,12 @@ public class PathParser { double ep2x = -a * cosTheta * sinEta2 - b * sinTheta * cosEta2; double ep2y = -a * sinTheta * sinEta2 + b * cosTheta * cosEta2; double tanDiff2 = Math.tan((eta2 - eta1) / 2); - double alpha = - Math.sin(eta2 - eta1) * (Math.sqrt(4 + (3 * tanDiff2 * tanDiff2)) - 1) / 3; + double alpha = Math.sin(eta2 - eta1) * (Math.sqrt(4 + (3 * tanDiff2 * tanDiff2)) - 1) / 3; double q1x = e1x + alpha * ep1x; double q1y = e1y + alpha * ep1y; double q2x = e2x - alpha * ep2x; double q2y = e2y - alpha * ep2y; - p.cubicTo((float) q1x, - (float) q1y, - (float) q2x, - (float) q2y, - (float) e2x, - (float) e2y); + p.cubicTo((float) q1x, (float) q1y, (float) q2x, (float) q2y, (float) e2x, (float) e2y); eta1 = eta2; e1x = e2x; e1y = e2y; diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/RoundedWidgetView.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/RoundedWidgetView.java index 69d69f3e581253b94bb99fa233ff52a0c60d1f1a..b53a81a1cb716a48835ffbb1fc4705dc86d73d65 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/RoundedWidgetView.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/RoundedWidgetView.java @@ -11,9 +11,7 @@ import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; - import androidx.annotation.Nullable; - import foundation.e.blisslauncher.R; import foundation.e.blisslauncher.core.blur.BlurViewDelegate; import foundation.e.blisslauncher.features.widgets.CheckLongPressHelper; @@ -64,7 +62,6 @@ public class RoundedWidgetView extends AppWidgetHostView { stencilPath.reset(); stencilPath.addRoundRect(0, 0, w, h, cornerRadius, cornerRadius, Path.Direction.CW); stencilPath.close(); - } @Override @@ -104,13 +101,11 @@ public class RoundedWidgetView extends AppWidgetHostView { @Override public int getDescendantFocusability() { - return mChildrenFocused ? ViewGroup.FOCUS_BEFORE_DESCENDANTS - : ViewGroup.FOCUS_BLOCK_DESCENDANTS; + return mChildrenFocused ? ViewGroup.FOCUS_BEFORE_DESCENDANTS : ViewGroup.FOCUS_BLOCK_DESCENDANTS; } @Override - protected void onFocusChanged(boolean gainFocus, int direction, - @Nullable Rect previouslyFocusedRect) { + protected void onFocusChanged(boolean gainFocus, int direction, @Nullable Rect previouslyFocusedRect) { if (gainFocus) { mChildrenFocused = false; dispatchChildFocus(false); @@ -133,7 +128,8 @@ public class RoundedWidgetView extends AppWidgetHostView { } private void dispatchChildFocus(boolean childIsFocused) { - // The host view's background changes when selected, to indicate the focus is inside. + // The host view's background changes when selected, to indicate the focus is + // inside. setSelected(childIsFocused); } @@ -143,8 +139,8 @@ public class RoundedWidgetView extends AppWidgetHostView { } resizeBorder = new ImageView(mContext); resizeBorder.setImageResource(R.drawable.widget_resize_frame); - FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams( - ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); + FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, + ViewGroup.LayoutParams.MATCH_PARENT); resizeBorder.setLayoutParams(layoutParams); addView(resizeBorder); activated = true; diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/SquareFrameLayout.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/SquareFrameLayout.java index 468abdcf52954b42506e4c276353e39a75cdf2e9..54a028dd96280d7ec987211e82c86bbe22af7314 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/SquareFrameLayout.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/SquareFrameLayout.java @@ -4,17 +4,12 @@ import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.widget.FrameLayout; - import androidx.annotation.NonNull; import androidx.annotation.Nullable; - import foundation.e.blisslauncher.core.DeviceProfile; import foundation.e.blisslauncher.core.blur.BlurViewDelegate; -/** - * Created by falcon on 9/3/18. - */ - +/** Created by falcon on 9/3/18. */ public class SquareFrameLayout extends FrameLayout { private BlurViewDelegate mBlurDelegate = null; @@ -23,13 +18,11 @@ public class SquareFrameLayout extends FrameLayout { this(context, null); } - public SquareFrameLayout(@NonNull Context context, - @Nullable AttributeSet attrs) { + public SquareFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs) { this(context, attrs, 0); } - public SquareFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, - int defStyleAttr) { + public SquareFrameLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); setWillNotDraw(false); } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/SquareImageView.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/SquareImageView.java index ce90e78fbcb879ab16e06dd74f0b2267e818a0d1..22048641397e2136b4d0cac55e46ab31f4b34093 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/SquareImageView.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/SquareImageView.java @@ -2,13 +2,9 @@ package foundation.e.blisslauncher.core.customviews; import android.content.Context; import android.util.AttributeSet; - import androidx.appcompat.widget.AppCompatImageView; -/** - * Created by falcon on 16/2/18. - */ - +/** Created by falcon on 16/2/18. */ public class SquareImageView extends AppCompatImageView { public SquareImageView(Context context) { @@ -27,4 +23,4 @@ public class SquareImageView extends AppCompatImageView { int size = width < height ? width : height; setMeasuredDimension(size, size); } -} \ No newline at end of file +} diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/SquareLinearLayout.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/SquareLinearLayout.java index 6bbbb781e2f501ff625f5390d4a1831da49d8fcc..ad4a0e5bc7fcbe299976ba75ec55a86f225e959c 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/SquareLinearLayout.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/SquareLinearLayout.java @@ -4,22 +4,17 @@ import android.content.Context; import android.util.AttributeSet; import android.widget.LinearLayout; -/** - * Created by falcon on 9/3/18. - */ - +/** Created by falcon on 9/3/18. */ public class SquareLinearLayout extends LinearLayout { public SquareLinearLayout(Context context) { super(context); } - public SquareLinearLayout(Context context, - AttributeSet attrs) { + public SquareLinearLayout(Context context, AttributeSet attrs) { super(context, attrs); } - public SquareLinearLayout(Context context, AttributeSet attrs, - int defStyleAttr) { + public SquareLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/WidgetHost.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/WidgetHost.java index 6d03fea9adc414a7906b243826c18c52578283bd..4039c74fd2dd3e0b707227ccea6d6a47a21c0c90 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/WidgetHost.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/WidgetHost.java @@ -6,7 +6,6 @@ import android.appwidget.AppWidgetProviderInfo; import android.content.ComponentName; import android.content.Context; import android.view.ContextThemeWrapper; - import foundation.e.blisslauncher.core.utils.ThemesKt; import foundation.e.blisslauncher.features.weather.WeatherAppWidgetProvider; import foundation.e.blisslauncher.features.weather.WeatherWidgetHostView; diff --git a/app/src/main/java/foundation/e/blisslauncher/core/customviews/Workspace.java b/app/src/main/java/foundation/e/blisslauncher/core/customviews/Workspace.java index 934693cd08c245b8ec0c1e3810c751c1bc8a53a9..0dea01aad376222da32d20509e76d26372c7bc3a 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/customviews/Workspace.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/customviews/Workspace.java @@ -5,11 +5,10 @@ import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; - import foundation.e.blisslauncher.core.customviews.pageindicators.PageIndicatorDots; import foundation.e.blisslauncher.features.launcher.LauncherActivity; -public class Workspace extends PagedView implements View.OnTouchListener{ +public class Workspace extends PagedView implements View.OnTouchListener { private static final String TAG = "Workspace"; private static final int DEFAULT_PAGE = 0; @@ -40,7 +39,7 @@ public class Workspace extends PagedView implements View.OnTo setClipToPadding(false); setupLayoutTransition(); - //setWallpaperDimension(); + // setWallpaperDimension(); } private void setupLayoutTransition() { @@ -56,6 +55,7 @@ public class Workspace extends PagedView implements View.OnTo void enableLayoutTransitions() { setLayoutTransition(mLayoutTransition); } + void disableLayoutTransitions() { setLayoutTransition(null); } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/database/DatabaseManager.java b/app/src/main/java/foundation/e/blisslauncher/core/database/DatabaseManager.java index 4c890cfd3f1c843672f97ad4b65cdf6449330dcd..81acab13c9c9d9cce9e1fd6c49f066ee926855a3 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/database/DatabaseManager.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/database/DatabaseManager.java @@ -2,13 +2,6 @@ package foundation.e.blisslauncher.core.database; import android.content.Context; import android.widget.GridLayout; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - import foundation.e.blisslauncher.core.customviews.BlissFrameLayout; import foundation.e.blisslauncher.core.database.daos.WidgetDao; import foundation.e.blisslauncher.core.database.model.FolderItem; @@ -17,6 +10,11 @@ import foundation.e.blisslauncher.core.database.model.WidgetItem; import foundation.e.blisslauncher.core.executors.AppExecutors; import foundation.e.blisslauncher.core.utils.Constants; import io.reactivex.Single; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Set; public class DatabaseManager { @@ -44,8 +42,7 @@ public class DatabaseManager { } public void removeLauncherItem(String itemId) { - mAppExecutors.diskIO().execute( - () -> LauncherDB.getDatabase(mContext).launcherDao().delete(itemId)); + mAppExecutors.diskIO().execute(() -> LauncherDB.getDatabase(mContext).launcherDao().delete(itemId)); } public void saveLayouts(List pages, GridLayout dock) { @@ -83,8 +80,7 @@ public class DatabaseManager { for (int i = 0; i < pages.size(); i++) { GridLayout gridLayout = pages.get(i); for (int j = 0; j < gridLayout.getChildCount(); j++) { - LauncherItem launcherItem = ((BlissFrameLayout) gridLayout.getChildAt( - j)).getLauncherItem(); + LauncherItem launcherItem = ((BlissFrameLayout) gridLayout.getChildAt(j)).getLauncherItem(); if (launcherItem.itemType == Constants.ITEM_TYPE_FOLDER) { FolderItem folderItem = (FolderItem) launcherItem; folderItem.screenId = i; @@ -110,25 +106,22 @@ public class DatabaseManager { } public void removeShortcut(String name) { - mAppExecutors.diskIO().execute( - () -> LauncherDB.getDatabase(mContext).launcherDao().deleteShortcut(name)); + mAppExecutors.diskIO().execute(() -> LauncherDB.getDatabase(mContext).launcherDao().deleteShortcut(name)); } - // Already invoked in a disk io thread, so no need to execute in separate thread here. + // Already invoked in a disk io thread, so no need to execute in separate thread + // here. public void migrateComponent(String old_component_name, String new_component_name) { LauncherDB.getDatabase(mContext).launcherDao().delete(new_component_name); - LauncherDB.getDatabase(mContext).launcherDao().updateComponent(old_component_name, - new_component_name); + LauncherDB.getDatabase(mContext).launcherDao().updateComponent(old_component_name, new_component_name); } public void insertWidget(WidgetItem widgetItem) { - mAppExecutors.diskIO().execute( - () -> LauncherDB.getDatabase(mContext).widgetDao().insert(widgetItem)); + mAppExecutors.diskIO().execute(() -> LauncherDB.getDatabase(mContext).widgetDao().insert(widgetItem)); } public void saveWidgetHeight(int id, int height) { - mAppExecutors.diskIO().execute( - () -> LauncherDB.getDatabase(mContext).widgetDao().updateHeight(id, height)); + mAppExecutors.diskIO().execute(() -> LauncherDB.getDatabase(mContext).widgetDao().updateHeight(id, height)); } public void removeWidget(int id) { @@ -151,7 +144,8 @@ public class DatabaseManager { widgets.add(item); widgetDao.insert(item); } - widgets.sort(Comparator.comparingInt(widget -> widget.order).thenComparingInt(widget -> widget.id)); + widgets.sort( + Comparator.comparingInt(widget -> widget.order).thenComparingInt(widget -> widget.id)); return Single.just(widgets); }); } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/database/LauncherDB.java b/app/src/main/java/foundation/e/blisslauncher/core/database/LauncherDB.java index 6c6b7700ba9e49c28bdeaf7b4076e78e457e4165..f85605f5e737efa92fc0645676a181cbf310afde 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/database/LauncherDB.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/database/LauncherDB.java @@ -1,8 +1,6 @@ package foundation.e.blisslauncher.core.database; - import android.content.Context; - import androidx.annotation.NonNull; import androidx.room.Database; import androidx.room.Room; @@ -10,18 +8,13 @@ import androidx.room.RoomDatabase; import androidx.room.TypeConverters; import androidx.room.migration.Migration; import androidx.sqlite.db.SupportSQLiteDatabase; - import foundation.e.blisslauncher.core.database.converters.CharSequenceConverter; import foundation.e.blisslauncher.core.database.daos.LauncherDao; import foundation.e.blisslauncher.core.database.daos.WidgetDao; import foundation.e.blisslauncher.core.database.model.LauncherItem; import foundation.e.blisslauncher.core.database.model.WidgetItem; -@Database( - entities = {LauncherItem.class, WidgetItem.class}, - version = 5, - exportSchema = false -) +@Database(entities = {LauncherItem.class, WidgetItem.class}, version = 5, exportSchema = false) @TypeConverters({CharSequenceConverter.class}) public abstract class LauncherDB extends RoomDatabase { @@ -34,7 +27,8 @@ public abstract class LauncherDB extends RoomDatabase { private static final Migration MIGRATION_3_4 = new Migration(3, 4) { @Override public void migrate(SupportSQLiteDatabase database) { - database.execSQL("CREATE TABLE IF NOT EXISTS `widget_items` (`id` INTEGER NOT NULL, `height` INTEGER NOT NULL, PRIMARY KEY(`id`))"); + database.execSQL( + "CREATE TABLE IF NOT EXISTS `widget_items` (`id` INTEGER NOT NULL, `height` INTEGER NOT NULL, PRIMARY KEY(`id`))"); } }; @@ -42,12 +36,11 @@ public abstract class LauncherDB extends RoomDatabase { @Override public void migrate(@NonNull SupportSQLiteDatabase database) { database.execSQL("ALTER TABLE `widget_items` RENAME TO `widget_items_old`"); - database.execSQL("CREATE TABLE IF NOT EXISTS `widget_items` (" + - "`id` INTEGER NOT NULL, " + - "`height` INTEGER NOT NULL DEFAULT 0, " + - "`order` INTEGER NOT NULL DEFAULT 99999, " + - "PRIMARY KEY(`id`))"); - database.execSQL("INSERT INTO `widget_items` (`id`, `height`) SELECT `id`, `height` FROM `widget_items_old`"); + database.execSQL("CREATE TABLE IF NOT EXISTS `widget_items` (" + "`id` INTEGER NOT NULL, " + + "`height` INTEGER NOT NULL DEFAULT 0, " + "`order` INTEGER NOT NULL DEFAULT 99999, " + + "PRIMARY KEY(`id`))"); + database.execSQL( + "INSERT INTO `widget_items` (`id`, `height`) SELECT `id`, `height` FROM `widget_items_old`"); database.execSQL("DROP TABLE `widget_items_old`"); } }; @@ -56,10 +49,8 @@ public abstract class LauncherDB extends RoomDatabase { if (INSTANCE == null) { synchronized (LauncherDB.class) { if (INSTANCE == null) { - INSTANCE = Room.databaseBuilder(context.getApplicationContext(), - LauncherDB.class, "launcher_db") - .addMigrations(MIGRATION_3_4, MIGRATION_4_5) - .build(); + INSTANCE = Room.databaseBuilder(context.getApplicationContext(), LauncherDB.class, "launcher_db") + .addMigrations(MIGRATION_3_4, MIGRATION_4_5).build(); } } } @@ -76,8 +67,8 @@ public abstract class LauncherDB extends RoomDatabase { @Override public void migrate(@NonNull SupportSQLiteDatabase database) { - String suffix = "\"/" + userSerialNumber +"\""; - String query = "UPDATE launcher_items set item_id=item_id || " + suffix + "WHERE item_type <> 2"; + String suffix = "\"/" + userSerialNumber + "\""; + String query = "UPDATE launcher_items set item_id=item_id || " + suffix + "WHERE item_type <> 2"; database.execSQL(query); } } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/database/daos/LauncherDao.java b/app/src/main/java/foundation/e/blisslauncher/core/database/daos/LauncherDao.java index 9eb659dc8cfed6d827307bb19a50485f9db07967..c2944a07b3313cd5cd755cb7959e54dae1adf91a 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/database/daos/LauncherDao.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/database/daos/LauncherDao.java @@ -1,15 +1,12 @@ package foundation.e.blisslauncher.core.database.daos; - import androidx.room.Dao; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; - -import java.util.List; - import foundation.e.blisslauncher.core.database.model.LauncherItem; import foundation.e.blisslauncher.core.utils.Constants; +import java.util.List; @Dao public interface LauncherDao { @@ -29,8 +26,7 @@ public interface LauncherDao { @Query("DELETE FROM launcher_items WHERE item_id = :id") void delete(String id); - @Query("DELETE FROM launcher_items WHERE title = :name and item_type = " - + Constants.ITEM_TYPE_SHORTCUT) + @Query("DELETE FROM launcher_items WHERE title = :name and item_type = " + Constants.ITEM_TYPE_SHORTCUT) void deleteShortcut(String name); @Query("UPDATE launcher_items SET item_id = :newComponentName WHERE item_id = :id") diff --git a/app/src/main/java/foundation/e/blisslauncher/core/database/daos/WidgetDao.java b/app/src/main/java/foundation/e/blisslauncher/core/database/daos/WidgetDao.java index f85fbff6aeab103b85add48bf605b5f1a581b691..3e590eea3cdb6d8436b5ea262a944beb6a1d5769 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/database/daos/WidgetDao.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/database/daos/WidgetDao.java @@ -4,10 +4,8 @@ import androidx.room.Dao; import androidx.room.Insert; import androidx.room.OnConflictStrategy; import androidx.room.Query; - -import java.util.List; - import foundation.e.blisslauncher.core.database.model.WidgetItem; +import java.util.List; @Dao public interface WidgetDao { diff --git a/app/src/main/java/foundation/e/blisslauncher/core/database/model/ApplicationItem.java b/app/src/main/java/foundation/e/blisslauncher/core/database/model/ApplicationItem.java index d2730485b9bad1d80792db946a4a251b745704f6..a3d9e01caa09bce60285ef65eaf39f9e33bb7eca 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/database/model/ApplicationItem.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/database/model/ApplicationItem.java @@ -4,7 +4,6 @@ import android.content.ComponentName; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.LauncherActivityInfo; - import foundation.e.blisslauncher.core.utils.Constants; import foundation.e.blisslauncher.core.utils.UserHandle; @@ -16,9 +15,7 @@ public class ApplicationItem extends LauncherItem { public ComponentName componentName; - /** - * Indicates if the app is a system app or not. - */ + /** Indicates if the app is a system app or not. */ public int isSystemApp; public static final int TYPE_CLOCK = 745; @@ -28,17 +25,16 @@ public class ApplicationItem extends LauncherItem { public boolean isDisabled = false; /** - * Indicates the type of app item ie. Clock or Calendar (in case of none, It will be ) + * Indicates the type of app item ie. Clock or Calendar (in case of none, It + * will be ) */ public int appType; - public ApplicationItem(){ + public ApplicationItem() { itemType = Constants.ITEM_TYPE_APPLICATION; } - /** - * Must not hold the Context. - */ + /** Must not hold the Context. */ public ApplicationItem(LauncherActivityInfo info, UserHandle user) { itemType = Constants.ITEM_TYPE_APPLICATION; this.componentName = info.getComponentName(); @@ -49,7 +45,8 @@ public class ApplicationItem extends LauncherItem { launchIntent = makeLaunchIntent(info); isSystemApp = (info.getApplicationInfo().flags & ApplicationInfo.FLAG_SYSTEM) == 0 - ? FLAG_SYSTEM_NO : FLAG_SYSTEM_YES; + ? FLAG_SYSTEM_NO + : FLAG_SYSTEM_YES; } public static Intent makeLaunchIntent(LauncherActivityInfo info) { @@ -57,9 +54,7 @@ public class ApplicationItem extends LauncherItem { } public static Intent makeLaunchIntent(ComponentName cn) { - return new Intent(Intent.ACTION_MAIN) - .addCategory(Intent.CATEGORY_LAUNCHER) - .setComponent(cn) + return new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER).setComponent(cn) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); } } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/database/model/CalendarIcon.java b/app/src/main/java/foundation/e/blisslauncher/core/database/model/CalendarIcon.java index e0ac91cbb49a21f49986fcb3761183e1fe8e05f0..92df0af07ed92d432ff154528cf6f534c9ad0a12 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/database/model/CalendarIcon.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/database/model/CalendarIcon.java @@ -2,10 +2,7 @@ package foundation.e.blisslauncher.core.database.model; import android.widget.TextView; -/** - * Created by falcon on 17/3/18. - */ - +/** Created by falcon on 17/3/18. */ public class CalendarIcon { public TextView monthTextView; public TextView dayTextView; diff --git a/app/src/main/java/foundation/e/blisslauncher/core/database/model/FolderItem.java b/app/src/main/java/foundation/e/blisslauncher/core/database/model/FolderItem.java index 8f1ac50867568081b51cf6622f6bc72615edba7c..043aefeb7a90202d20c9c709a34bb234636b6961 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/database/model/FolderItem.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/database/model/FolderItem.java @@ -1,18 +1,14 @@ package foundation.e.blisslauncher.core.database.model; -import java.util.List; - import foundation.e.blisslauncher.core.utils.Constants; +import java.util.List; public class FolderItem extends LauncherItem { - /** - * Stores networkItems that user saved in this folder. - */ + /** Stores networkItems that user saved in this folder. */ public List items; public FolderItem() { itemType = Constants.ITEM_TYPE_FOLDER; } - } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/database/model/LauncherItem.java b/app/src/main/java/foundation/e/blisslauncher/core/database/model/LauncherItem.java index 6c4ca0d5448a17ef03703f26c0784e19e13aa25e..ca7687b48ffdcfde78db18354eafb0a4c20d76a4 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/database/model/LauncherItem.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/database/model/LauncherItem.java @@ -3,22 +3,17 @@ package foundation.e.blisslauncher.core.database.model; import android.content.ComponentName; import android.content.Intent; import android.graphics.drawable.Drawable; - import androidx.annotation.NonNull; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.Ignore; import androidx.room.Index; import androidx.room.PrimaryKey; - -import java.net.URISyntaxException; - import foundation.e.blisslauncher.core.utils.Constants; import foundation.e.blisslauncher.core.utils.UserHandle; +import java.net.URISyntaxException; - -@Entity(tableName = "launcher_items", indices = {@Index(value = {"item_id"}, - unique = true)}) +@Entity(tableName = "launcher_items", indices = {@Index(value = {"item_id"}, unique = true)}) public class LauncherItem { @Ignore @@ -32,10 +27,10 @@ public class LauncherItem { /** * The id in the database for this item. For - * {@link Constants#ITEM_TYPE_APPLICATION} this - * would be Component name as it is unique across all application networkItems. If it is one of - * {@link Constants#ITEM_TYPE_SHORTCUT} and {@link Constants#ITEM_TYPE_FOLDER}, it will be - * the id of that. + * {@link Constants#ITEM_TYPE_APPLICATION} this would be Component name as it is + * unique across all application networkItems. If it is one of + * {@link Constants#ITEM_TYPE_SHORTCUT} and {@link Constants#ITEM_TYPE_FOLDER}, + * it will be the id of that. */ @NonNull @ColumnInfo(name = "item_id") @@ -43,17 +38,15 @@ public class LauncherItem { /** * One of {@link Constants#ITEM_TYPE_APPLICATION} - * {@link Constants#ITEM_TYPE_SHORTCUT} - * {@link Constants#ITEM_TYPE_FOLDER} + * {@link Constants#ITEM_TYPE_SHORTCUT} {@link Constants#ITEM_TYPE_FOLDER} */ @ColumnInfo(name = "item_type") public int itemType; /** * The id of the container that holds this item. For the desktop, this will be - * {@link Constants#CONTAINER_DESKTOP}. For the all - * applications folder it will be {@link #NO_ID}. - * For user folders it will be the id of the folder. + * {@link Constants#CONTAINER_DESKTOP}. For the all applications folder it will + * be {@link #NO_ID}. For user folders it will be the id of the folder. */ @NonNull @ColumnInfo(name = "container") @@ -61,43 +54,32 @@ public class LauncherItem { /** * Indicates the screen in which the shortcut appears if the container types is - * {@link Constants#CONTAINER_DESKTOP}. (i.e., - * ignore if the container type is + * {@link Constants#CONTAINER_DESKTOP}. (i.e., ignore if the container type is * {@link Constants#CONTAINER_HOTSEAT}) */ @ColumnInfo(name = "screen_id") public long screenId = -1; - /** - * Indicates the position of the associated cell. - */ + /** Indicates the position of the associated cell. */ @ColumnInfo(name = "cell") public int cell = INVALID_CELL; - /** - * Title of the item - */ + /** Title of the item */ @ColumnInfo(name = "title") public CharSequence title; @Ignore public UserHandle user; - /** - * Icon of the item - */ + /** Icon of the item */ @Ignore public Drawable icon; - /** - * Used for shortcuts on api lower than oreo. - */ + /** Used for shortcuts on api lower than oreo. */ @ColumnInfo(name = "icon", typeAffinity = ColumnInfo.BLOB) public byte[] icon_blob; - /** - * Intent used to launch this shortcut. - */ + /** Intent used to launch this shortcut. */ @Ignore public Intent launchIntent; @@ -105,7 +87,8 @@ public class LauncherItem { public String launchIntentUri; /** - * Package name of the respective launcher item. For folders it would be "FOLDER". + * Package name of the respective launcher item. For folders it would be + * "FOLDER". */ @ColumnInfo(name = "package") public String packageName; @@ -146,7 +129,8 @@ public class LauncherItem { @Override public boolean equals(Object obj) { - if (this == obj) return true; + if (this == obj) + return true; if (!(obj instanceof LauncherItem)) { return false; diff --git a/app/src/main/java/foundation/e/blisslauncher/core/database/model/ShortcutItem.java b/app/src/main/java/foundation/e/blisslauncher/core/database/model/ShortcutItem.java index 5db545ec30dfab652b83464e66888c88bb7ee623..a0e4830726a35ae797827076b088f5b8c7207ff5 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/database/model/ShortcutItem.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/database/model/ShortcutItem.java @@ -4,7 +4,7 @@ import foundation.e.blisslauncher.core.utils.Constants; public class ShortcutItem extends LauncherItem { - public ShortcutItem(){ + public ShortcutItem() { itemType = Constants.ITEM_TYPE_SHORTCUT; } } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/database/model/WidgetItem.java b/app/src/main/java/foundation/e/blisslauncher/core/database/model/WidgetItem.java index 645d142d08e8ae0ed7e6a962e7b325cc8524b091..138a399a4be712c0ae925f0543417f29b50f7b12 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/database/model/WidgetItem.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/database/model/WidgetItem.java @@ -19,7 +19,6 @@ public class WidgetItem { public int order = DEFAULT_ORDER; public WidgetItem() { - } public WidgetItem(int id) { diff --git a/app/src/main/java/foundation/e/blisslauncher/core/events/AppAddEvent.java b/app/src/main/java/foundation/e/blisslauncher/core/events/AppAddEvent.java index 229b56345cb405cce9229db11343a43f2dc7d55a..ef12fc0401895ee182e206f41d51841616db683c 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/events/AppAddEvent.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/events/AppAddEvent.java @@ -2,7 +2,7 @@ package foundation.e.blisslauncher.core.events; import foundation.e.blisslauncher.core.utils.UserHandle; -public class AppAddEvent extends Event{ +public class AppAddEvent extends Event { private String packageName; private UserHandle userHandle; @@ -25,9 +25,6 @@ public class AppAddEvent extends Event{ @Override public String toString() { - return "AppAddEvent{" + - "packageName='" + packageName + '\'' + - ", userHandle=" + userHandle + - '}'; + return "AppAddEvent{" + "packageName='" + packageName + '\'' + ", userHandle=" + userHandle + '}'; } } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/events/AppChangeEvent.java b/app/src/main/java/foundation/e/blisslauncher/core/events/AppChangeEvent.java index 55916dece29f7ee11b3d58dc206060af9585c1cf..35f3bd605dfcd1803f3a7c4cda6d75c6f3b5470e 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/events/AppChangeEvent.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/events/AppChangeEvent.java @@ -2,7 +2,7 @@ package foundation.e.blisslauncher.core.events; import foundation.e.blisslauncher.core.utils.UserHandle; -public class AppChangeEvent extends Event{ +public class AppChangeEvent extends Event { private String packageName; private UserHandle userHandle; diff --git a/app/src/main/java/foundation/e/blisslauncher/core/events/Event.java b/app/src/main/java/foundation/e/blisslauncher/core/events/Event.java index ac2e5fd701d9463e71039a4009761d975a487d64..ce0482d21ba042bb27e8d10e24212548fea5d09c 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/events/Event.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/events/Event.java @@ -1,8 +1,6 @@ package foundation.e.blisslauncher.core.events; -/** - * All event classes must inherit from this class. - */ +/** All event classes must inherit from this class. */ public class Event { private final int eventType; diff --git a/app/src/main/java/foundation/e/blisslauncher/core/events/EventRelay.java b/app/src/main/java/foundation/e/blisslauncher/core/events/EventRelay.java index 4587951ab8091d903939a14e523233f752e91a51..11e9368d22f9bfc33761cde7589bb9dffc18cfed 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/events/EventRelay.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/events/EventRelay.java @@ -7,7 +7,8 @@ public class EventRelay { private static volatile EventRelay sInstance; - // Queue to store actions if no observer is currently subscribed to listen for events. + // Queue to store actions if no observer is currently subscribed to listen for + // events. private Queue events; private EventsObserver observer; @@ -48,7 +49,8 @@ public class EventRelay { event = events.poll(); } - if (shouldInvokeComplete) this.observer.complete(); + if (shouldInvokeComplete) + this.observer.complete(); } public void unsubscribe() { diff --git a/app/src/main/java/foundation/e/blisslauncher/core/events/ForceReloadEvent.java b/app/src/main/java/foundation/e/blisslauncher/core/events/ForceReloadEvent.java index 79b25d78917e41615dcc6592f2dacf101af0cfc3..83a5db41016e5129651bd171a53293d6ccc0a6d8 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/events/ForceReloadEvent.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/events/ForceReloadEvent.java @@ -1,6 +1,6 @@ package foundation.e.blisslauncher.core.events; -public class ForceReloadEvent extends Event{ +public class ForceReloadEvent extends Event { public static final int TYPE = 801; public ForceReloadEvent() { diff --git a/app/src/main/java/foundation/e/blisslauncher/core/executors/AppExecutors.java b/app/src/main/java/foundation/e/blisslauncher/core/executors/AppExecutors.java index be58e20827435c8ad5ecf9bd701f3e6531ba4b86..81e28eed6408ed4c10a8e87814d1e9a578e52312 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/executors/AppExecutors.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/executors/AppExecutors.java @@ -21,11 +21,11 @@ public class AppExecutors { shortcutExecutor = Executors.newSingleThreadExecutor(); } - public ExecutorService diskIO(){ + public ExecutorService diskIO() { return diskExecutor; } - public ExecutorService appIO(){ + public ExecutorService appIO() { return appExecutor; } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/executors/MainThreadExecutor.java b/app/src/main/java/foundation/e/blisslauncher/core/executors/MainThreadExecutor.java index 1088b1c02d725227458563cee90d926b7f171cdd..058a839f7b48a34da9c92e91bef879bdbcc22c82 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/executors/MainThreadExecutor.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/executors/MainThreadExecutor.java @@ -2,9 +2,7 @@ package foundation.e.blisslauncher.core.executors; import android.os.Handler; import android.os.Looper; - import androidx.annotation.NonNull; - import java.util.List; import java.util.concurrent.AbstractExecutorService; import java.util.concurrent.TimeUnit; @@ -16,6 +14,7 @@ public class MainThreadExecutor extends AbstractExecutorService { public MainThreadExecutor() { mHandler = new Handler(Looper.getMainLooper()); } + @Override public void shutdown() { throw new UnsupportedOperationException(); diff --git a/app/src/main/java/foundation/e/blisslauncher/core/migrate/MigrateComponentInfo.java b/app/src/main/java/foundation/e/blisslauncher/core/migrate/MigrateComponentInfo.java index 749b68b9e120a88def8249f1fadb79a33055e44a..bd29bcb192ff10715ebfeef94c14169f2e1026a7 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/migrate/MigrateComponentInfo.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/migrate/MigrateComponentInfo.java @@ -4,4 +4,3 @@ class MigrateComponentInfo { String old_component_name; String new_component_name; } - diff --git a/app/src/main/java/foundation/e/blisslauncher/core/migrate/Migration.java b/app/src/main/java/foundation/e/blisslauncher/core/migrate/Migration.java index 937799abfe1682bb90f3ef20ba4e391bca67c68e..e2ef0253efb51dd3d36e16376aa3625ebb336a10 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/migrate/Migration.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/migrate/Migration.java @@ -3,9 +3,10 @@ package foundation.e.blisslauncher.core.migrate; import android.content.Context; import android.os.Build; import android.util.Log; - import com.google.gson.Gson; - +import foundation.e.blisslauncher.core.Preferences; +import foundation.e.blisslauncher.core.database.DatabaseManager; +import foundation.e.blisslauncher.core.database.LauncherDB; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; @@ -13,10 +14,6 @@ import java.util.Collections; import java.util.List; import java.util.stream.Collectors; -import foundation.e.blisslauncher.core.Preferences; -import foundation.e.blisslauncher.core.database.DatabaseManager; -import foundation.e.blisslauncher.core.database.LauncherDB; - public class Migration { public static volatile Migration instance; @@ -39,38 +36,32 @@ public class Migration { List dialerComponentList = Arrays.asList( "com.android.dialer/com.android.dialer.main.impl.MainActivity", "com.android.dialer/com.android.dialer.app.DialtactsActivity", - "com.android.dialer/com.android.dialer.DialtactsActivity" - ); + "com.android.dialer/com.android.dialer.DialtactsActivity"); String currentComponent = dialerComponentList.get(0); - String dialerComponent = LauncherDB - .getDatabase(context) - .launcherDao() + String dialerComponent = LauncherDB.getDatabase(context).launcherDao() .getComponentName("com.android.dialer"); - if (dialerComponent != null && dialerComponentList.contains(dialerComponent) - && !dialerComponent.equals(currentComponent)) { + if (dialerComponent != null && dialerComponentList.contains(dialerComponent) + && !dialerComponent.equals(currentComponent)) { Log.d(TAG, "migrateSafely: Migrating dialer component!"); - DatabaseManager.getManager(context).migrateComponent( - dialerComponent, currentComponent); + DatabaseManager.getManager(context).migrateComponent(dialerComponent, currentComponent); } } String migrationInfo = instance.readJSONFromAsset(context); - CurrentMigration currentMigration = new Gson().fromJson(migrationInfo, - CurrentMigration.class); + CurrentMigration currentMigration = new Gson().fromJson(migrationInfo, CurrentMigration.class); int oldVersion = Preferences.getCurrentMigrationVersion(context); if (oldVersion < currentMigration.currentVersion) { - List infos = currentMigration.migrate_infos.parallelStream().filter( - migrationInfo1 -> migrationInfo1.startVersion >= oldVersion).collect( - Collectors.toList()); - Log.i(TAG, "migrateSafely: "+infos.size()); + List infos = currentMigration.migrate_infos.parallelStream() + .filter(migrationInfo1 -> migrationInfo1.startVersion >= oldVersion).collect(Collectors.toList()); + Log.i(TAG, "migrateSafely: " + infos.size()); Collections.sort(infos); for (MigrationInfo info : infos) { List components = info.components; for (MigrateComponentInfo component : components) { - DatabaseManager.getManager(context).migrateComponent( - component.old_component_name, component.new_component_name); + DatabaseManager.getManager(context).migrateComponent(component.old_component_name, + component.new_component_name); } } Preferences.setCurrentMigrationVersion(context, currentMigration.currentVersion); diff --git a/app/src/main/java/foundation/e/blisslauncher/core/mvp/MvpContract.java b/app/src/main/java/foundation/e/blisslauncher/core/mvp/MvpContract.java index dc62b3efd86f69b86aadf67a64273727194cf9ca..b6b9edbc0543332d60f1e1a3bba7722c3ed47770 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/mvp/MvpContract.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/mvp/MvpContract.java @@ -7,8 +7,11 @@ public interface MvpContract { interface Presenter { void attachView(V view); + void resume(); + void pause(); + void detachView(); } } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/mvp/MvpPresenter.java b/app/src/main/java/foundation/e/blisslauncher/core/mvp/MvpPresenter.java index ebe7112bda0bdab4128ebc2b3499da9c36012e86..c8826c4f9e6474e0904d6ed99ec77e82dc049edf 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/mvp/MvpPresenter.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/mvp/MvpPresenter.java @@ -1,6 +1,6 @@ package foundation.e.blisslauncher.core.mvp; -public class MvpPresenter implements MvpContract.Presenter{ +public class MvpPresenter implements MvpContract.Presenter { private V mView; private boolean isPaused; @@ -29,18 +29,18 @@ public class MvpPresenter implements MvpContract.Pre return mView; } - public boolean isViewAttached(){ + public boolean isViewAttached() { return this.mView != null; } public void checkViewAttached() { - if (!isViewAttached()) throw new ViewNotAttachedException(); + if (!isViewAttached()) + throw new ViewNotAttachedException(); } public static class ViewNotAttachedException extends RuntimeException { public ViewNotAttachedException() { - super("Call Presenter.attachView(BaseView)before" + - " requesting data to the Presenter"); + super("Call Presenter.attachView(BaseView)before" + " requesting data to the Presenter"); } } } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/network/RetrofitService.java b/app/src/main/java/foundation/e/blisslauncher/core/network/RetrofitService.java index 7072f65f2ec5d9a925f29040b602d117d70423ea..56adce1be1b2852ff8f84dcd33468359c3ba921c 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/network/RetrofitService.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/network/RetrofitService.java @@ -10,20 +10,15 @@ public class RetrofitService { private static OkHttpClient sOkHttpClient; private static GsonConverterFactory sGsonConverterFactory = GsonConverterFactory.create(); private static RxJava2CallAdapterFactory sRxJava2CallAdapterFactory = RxJava2CallAdapterFactory.create(); + static { HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); - sOkHttpClient = new OkHttpClient.Builder() - .addInterceptor(logging) - .build(); + sOkHttpClient = new OkHttpClient.Builder().addInterceptor(logging).build(); } public static Retrofit getInstance(String url) { - return new Retrofit.Builder() - .baseUrl(url) - .client(sOkHttpClient) - .addCallAdapterFactory(sRxJava2CallAdapterFactory) - .addConverterFactory(sGsonConverterFactory).build(); - + return new Retrofit.Builder().baseUrl(url).client(sOkHttpClient) + .addCallAdapterFactory(sRxJava2CallAdapterFactory).addConverterFactory(sGsonConverterFactory).build(); } } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/network/duckduckgo/DuckDuckGoResult.java b/app/src/main/java/foundation/e/blisslauncher/core/network/duckduckgo/DuckDuckGoResult.java index f8ff6d3fb995f9ea6a31f8e71356a7e8c3158201..522407c6f8e4b7dafaaa86027d76630156c6e7da 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/network/duckduckgo/DuckDuckGoResult.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/network/duckduckgo/DuckDuckGoResult.java @@ -4,7 +4,7 @@ public class DuckDuckGoResult { private String phrase; - public DuckDuckGoResult(String phrase){ + public DuckDuckGoResult(String phrase) { this.phrase = phrase; } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/network/duckduckgo/DuckDuckGoSuggestionService.java b/app/src/main/java/foundation/e/blisslauncher/core/network/duckduckgo/DuckDuckGoSuggestionService.java index 49e2929e198d60af5c61647f1dda29f7860e1bfc..482efa1f7694b65855e701bb0031f98a557fc87a 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/network/duckduckgo/DuckDuckGoSuggestionService.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/network/duckduckgo/DuckDuckGoSuggestionService.java @@ -1,8 +1,7 @@ package foundation.e.blisslauncher.core.network.duckduckgo; -import java.util.List; - import io.reactivex.Observable; +import java.util.List; import retrofit2.http.GET; import retrofit2.http.Query; diff --git a/app/src/main/java/foundation/e/blisslauncher/core/network/qwant/QwantData.java b/app/src/main/java/foundation/e/blisslauncher/core/network/qwant/QwantData.java index 949511a3f1660c02d27dc9dc999c020e203ef97e..27a39969e8a754fb430016915864fbf43a6f7e3f 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/network/qwant/QwantData.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/network/qwant/QwantData.java @@ -2,7 +2,6 @@ package foundation.e.blisslauncher.core.network.qwant; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; - import java.util.List; public class QwantData { diff --git a/app/src/main/java/foundation/e/blisslauncher/core/network/qwant/QwantItem.java b/app/src/main/java/foundation/e/blisslauncher/core/network/qwant/QwantItem.java index f576ae7915d5aa81c698a4265159e643a911c0dd..96bf1772825878d1d864ebe99a649176ec1b53c5 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/network/qwant/QwantItem.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/network/qwant/QwantItem.java @@ -7,6 +7,7 @@ public class QwantItem { @SerializedName("value") @Expose private String value; + @SerializedName("suggestType") @Expose private Integer suggestType; diff --git a/app/src/main/java/foundation/e/blisslauncher/core/network/qwant/QwantResult.java b/app/src/main/java/foundation/e/blisslauncher/core/network/qwant/QwantResult.java index 80c3a599b3759162ef400d10c0b862c302067f9b..e784243da1ec6c98a64fd85453b4f7762a42f67d 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/network/qwant/QwantResult.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/network/qwant/QwantResult.java @@ -7,6 +7,7 @@ public class QwantResult { @SerializedName("status") @Expose private String status; + @SerializedName("data") @Expose private QwantData data; diff --git a/app/src/main/java/foundation/e/blisslauncher/core/touch/OverScroll.java b/app/src/main/java/foundation/e/blisslauncher/core/touch/OverScroll.java index 1a89c0bef8a4d9cd4b03c84b403917e0df2fe0b8..5ee63fc04d6eb16fd7fcaecea4206156929140f2 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/touch/OverScroll.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/touch/OverScroll.java @@ -1,17 +1,16 @@ package foundation.e.blisslauncher.core.touch; -/** - * Utility methods for overscroll damping and related effect. - */ +/** Utility methods for overscroll damping and related effect. */ public class OverScroll { private static final float OVERSCROLL_DAMP_FACTOR = 0.07f; /** - * This curve determines how the effect of scrolling over the limits of the page diminishes - * as the user pulls further and further from the bounds + * This curve determines how the effect of scrolling over the limits of the page + * diminishes as the user pulls further and further from the bounds * - * @param f The percentage of how much the user has overscrolled. + * @param f + * The percentage of how much the user has overscrolled. * @return A transformed percentage based on the influence curve. */ private static float overScrollInfluenceCurve(float f) { @@ -20,12 +19,15 @@ public class OverScroll { } /** - * @param amount The original amount overscrolled. - * @param max The maximum amount that the View can overscroll. + * @param amount + * The original amount overscrolled. + * @param max + * The maximum amount that the View can overscroll. * @return The dampened overscroll amount. */ public static int dampedScroll(float amount, int max) { - if (Float.compare(amount, 0) == 0) return 0; + if (Float.compare(amount, 0) == 0) + return 0; float f = amount / max; f = f / (Math.abs(f)) * (overScrollInfluenceCurve(Math.abs(f))); diff --git a/app/src/main/java/foundation/e/blisslauncher/core/utils/AppUtils.java b/app/src/main/java/foundation/e/blisslauncher/core/utils/AppUtils.java index 4021797f424f70dde82ed4f7294697732a540edf..449764afb2f023a520d55f5ddc939b4a68bd7c8d 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/utils/AppUtils.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/utils/AppUtils.java @@ -26,35 +26,29 @@ import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.UserManager; import android.util.Log; - import androidx.annotation.Nullable; - -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - import foundation.e.blisslauncher.BlissLauncher; import foundation.e.blisslauncher.R; import foundation.e.blisslauncher.core.IconsHandler; import foundation.e.blisslauncher.core.database.model.ApplicationItem; import foundation.e.blisslauncher.features.launcher.AppProvider; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; public class AppUtils { private static final String TAG = "AppUtils"; private static volatile LauncherApps sLauncherApps; - /** - * Uses the PackageManager to find all launchable apps. - */ + /** Uses the PackageManager to find all launchable apps. */ @SuppressLint("CheckResult") public static Map loadAll(Context context) { UserManager manager = (UserManager) context.getSystemService(Context.USER_SERVICE); if (sLauncherApps == null) { - sLauncherApps = (LauncherApps) context.getSystemService( - Context.LAUNCHER_APPS_SERVICE); + sLauncherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE); } IconsHandler iconsHandler = BlissLauncher.getApplication(context).getIconsHandler(); Map appArrayMap = new LinkedHashMap<>(); @@ -62,22 +56,21 @@ public class AppUtils { // Handle multi-profile support introduced in Android 5 (#542) for (android.os.UserHandle profile : manager.getUserProfiles()) { UserHandle user = new UserHandle(manager.getSerialNumberForUser(profile), profile); - Log.i(TAG, "totalAppsBefore: "+sLauncherApps.getActivityList(null, profile).size()); + Log.i(TAG, "totalAppsBefore: " + sLauncherApps.getActivityList(null, profile).size()); List infos = sLauncherApps.getActivityList(null, profile); for (LauncherActivityInfo activityInfo : infos) { ApplicationInfo appInfo = activityInfo.getApplicationInfo(); - if(AppProvider.DISABLED_PACKAGES.contains(appInfo.packageName)){ + if (AppProvider.DISABLED_PACKAGES.contains(appInfo.packageName)) { continue; } - ApplicationItem applicationItem = new ApplicationItem(activityInfo, - user); - applicationItem.icon = iconsHandler.getDrawableIconForPackage( - activityInfo, user); + ApplicationItem applicationItem = new ApplicationItem(activityInfo, user); + applicationItem.icon = iconsHandler.getDrawableIconForPackage(activityInfo, user); String componentName = activityInfo.getComponentName().toString(); applicationItem.appType = iconsHandler.isClock(componentName) - ? ApplicationItem.TYPE_CLOCK : (iconsHandler.isCalendar( - componentName) - ? ApplicationItem.TYPE_CALENDAR : ApplicationItem.TYPE_DEFAULT); + ? ApplicationItem.TYPE_CLOCK + : (iconsHandler.isCalendar(componentName) + ? ApplicationItem.TYPE_CALENDAR + : ApplicationItem.TYPE_DEFAULT); applicationItem.title = activityInfo.getLabel().toString(); applicationItem.container = Constants.CONTAINER_DESKTOP; if (appInfo.packageName.equalsIgnoreCase("com.generalmagic.magicearth")) { @@ -87,15 +80,15 @@ public class AppUtils { appArrayMap.put(applicationItem.id, applicationItem); } } - Log.i(TAG, "Total Apps Loaded: "+appArrayMap.size()); + Log.i(TAG, "Total Apps Loaded: " + appArrayMap.size()); return appArrayMap; } @Nullable public static String getPackageNameForIntent(Intent intent, PackageManager pm) { - List activities = pm.queryIntentActivities(intent, - 0); - if (activities.size() == 0) return null; + List activities = pm.queryIntentActivities(intent, 0); + if (activities.size() == 0) + return null; ActivityInfo activity = activities.get(0).activityInfo; return activity.applicationInfo.packageName; } @@ -105,14 +98,12 @@ public class AppUtils { return null; } if (sLauncherApps == null) { - sLauncherApps = (LauncherApps) context.getSystemService( - Context.LAUNCHER_APPS_SERVICE); + sLauncherApps = (LauncherApps) context.getSystemService(Context.LAUNCHER_APPS_SERVICE); } IconsHandler iconsHandler = BlissLauncher.getApplication(context).getIconsHandler(); - List launcherActivityInfos = sLauncherApps.getActivityList( - packageName, + List launcherActivityInfos = sLauncherApps.getActivityList(packageName, userHandle.getRealHandle()); if (launcherActivityInfos == null || launcherActivityInfos.size() == 0) { return null; @@ -120,16 +111,15 @@ public class AppUtils { LauncherActivityInfo launcherActivityInfo = launcherActivityInfos.get(0); if (launcherActivityInfo != null) { - ApplicationItem applicationItem = new ApplicationItem(launcherActivityInfo, - userHandle); + ApplicationItem applicationItem = new ApplicationItem(launcherActivityInfo, userHandle); ApplicationInfo appInfo = launcherActivityInfo.getApplicationInfo(); - applicationItem.icon = iconsHandler.getDrawableIconForPackage( - launcherActivityInfo, userHandle); + applicationItem.icon = iconsHandler.getDrawableIconForPackage(launcherActivityInfo, userHandle); String componentName = launcherActivityInfo.getComponentName().toString(); applicationItem.appType = iconsHandler.isClock(componentName) - ? ApplicationItem.TYPE_CLOCK : (iconsHandler.isCalendar( - componentName) - ? ApplicationItem.TYPE_CALENDAR : ApplicationItem.TYPE_DEFAULT); + ? ApplicationItem.TYPE_CLOCK + : (iconsHandler.isCalendar(componentName) + ? ApplicationItem.TYPE_CALENDAR + : ApplicationItem.TYPE_DEFAULT); applicationItem.title = launcherActivityInfo.getLabel().toString(); applicationItem.container = Constants.CONTAINER_DESKTOP; if (appInfo.packageName.equalsIgnoreCase("com.generalmagic.magicearth")) { @@ -141,4 +131,4 @@ public class AppUtils { return null; } -} \ No newline at end of file +} diff --git a/app/src/main/java/foundation/e/blisslauncher/core/utils/BitmapUtils.java b/app/src/main/java/foundation/e/blisslauncher/core/utils/BitmapUtils.java index 7d8550bd1eea7b64eb64a852d81b20116fb0f6e3..ce7595ffef6b28a23554fe45ffde517a434d2980 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/utils/BitmapUtils.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/utils/BitmapUtils.java @@ -24,7 +24,7 @@ import android.graphics.PorterDuffXfermode; public class BitmapUtils { - public static Bitmap getCroppedBitmap(Bitmap src, Path path){ + public static Bitmap getCroppedBitmap(Bitmap src, Path path) { Bitmap output = Bitmap.createBitmap(src.getWidth(), src.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(output); diff --git a/app/src/main/java/foundation/e/blisslauncher/core/utils/ComponentKey.java b/app/src/main/java/foundation/e/blisslauncher/core/utils/ComponentKey.java index e769ad1a2f8b12bd8945b2fa15871fa9e56ac13e..564c1b8518d8d35e3e6425cbe5fc967a606e6319 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/utils/ComponentKey.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/utils/ComponentKey.java @@ -3,27 +3,22 @@ package foundation.e.blisslauncher.core.utils; /** * Copyright (C) 2015 The Android Open Source Project * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + *

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file + * except in compliance with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + *

http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and + *

Unless required by applicable law or agreed to in writing, software distributed under the + * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ - import android.content.ComponentName; import android.content.Context; import android.os.Process; import android.os.UserHandle; - -import java.util.Arrays; - import foundation.e.blisslauncher.core.UserManagerCompat; +import java.util.Arrays; public class ComponentKey { @@ -37,14 +32,13 @@ public class ComponentKey { Preconditions.assertNotNull(user); this.componentName = componentName; this.user = user; - mHashCode = Arrays.hashCode(new Object[] {componentName, user}); - + mHashCode = Arrays.hashCode(new Object[]{componentName, user}); } /** - * Creates a new component key from an encoded component key string in the form of - * [flattenedComponentString#userId]. If the userId is not present, then it defaults - * to the current user. + * Creates a new component key from an encoded component key string in the form + * of [flattenedComponentString#userId]. If the userId is not present, then it + * defaults to the current user. */ public ComponentKey(Context context, String componentKeyStr) { int userDelimiterIndex = componentKeyStr.indexOf("#"); @@ -52,8 +46,7 @@ public class ComponentKey { String componentStr = componentKeyStr.substring(0, userDelimiterIndex); Long componentUser = Long.valueOf(componentKeyStr.substring(userDelimiterIndex + 1)); componentName = ComponentName.unflattenFromString(componentStr); - user = UserManagerCompat.getInstance(context) - .getUserForSerialNumber(componentUser.longValue()); + user = UserManagerCompat.getInstance(context).getUserForSerialNumber(componentUser.longValue()); } else { // No user provided, default to the current user componentName = ComponentName.unflattenFromString(componentKeyStr); @@ -61,7 +54,7 @@ public class ComponentKey { } Preconditions.assertNotNull(componentName); Preconditions.assertNotNull(user); - mHashCode = Arrays.hashCode(new Object[] {componentName, user}); + mHashCode = Arrays.hashCode(new Object[]{componentName, user}); } @Override @@ -76,10 +69,11 @@ public class ComponentKey { } /** - * Encodes a component key as a string of the form [flattenedComponentString#userId]. + * Encodes a component key as a string of the form + * [flattenedComponentString#userId]. */ @Override public String toString() { return componentName.flattenToString() + "#" + user; } -} \ No newline at end of file +} diff --git a/app/src/main/java/foundation/e/blisslauncher/core/utils/Constants.java b/app/src/main/java/foundation/e/blisslauncher/core/utils/Constants.java index 2f84a08e332bd29eb556196656406be0c57fbc9e..0399bfdc1083aad1ee7ab88e70a9463a76b6e31d 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/utils/Constants.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/utils/Constants.java @@ -17,10 +17,7 @@ package foundation.e.blisslauncher.core.utils; import foundation.e.blisslauncher.BuildConfig; -/** - * Created by falcon on 8/3/18. - */ - +/** Created by falcon on 8/3/18. */ public class Constants { public static final boolean DEBUG = BuildConfig.DEBUG; public static final String PREF_NAME = "foundation.e.blisslauncher.prefs"; @@ -49,17 +46,14 @@ public class Constants { public static final String USER_CREATION_TIME_KEY = "user_creation_time_"; - /** - * Represents types of item displayed in Launcher. - */ + /** Represents types of item displayed in Launcher. */ public static final int ITEM_TYPE_APPLICATION = 0; + public static final int ITEM_TYPE_SHORTCUT = 1; public static final int ITEM_TYPE_FOLDER = 2; - /** - * Represents types of container. - */ + /** Represents types of container. */ public static final int CONTAINER_DESKTOP = -100; - public static final int CONTAINER_HOTSEAT = -101; + public static final int CONTAINER_HOTSEAT = -101; } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/utils/GraphicsUtil.java b/app/src/main/java/foundation/e/blisslauncher/core/utils/GraphicsUtil.java index 305d123981458f81344f681759b7f42058e14d79..47d965efcdf13ab309debd24881c58fe3535b9ae 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/utils/GraphicsUtil.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/utils/GraphicsUtil.java @@ -24,14 +24,12 @@ import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.Log; - -import java.util.HashMap; -import java.util.Map; - import foundation.e.blisslauncher.BlissLauncher; import foundation.e.blisslauncher.R; import foundation.e.blisslauncher.core.DeviceProfile; import foundation.e.blisslauncher.core.database.model.FolderItem; +import java.util.HashMap; +import java.util.Map; public class GraphicsUtil { @@ -48,8 +46,8 @@ public class GraphicsUtil { } /** - * Takes 1 or more drawables and merges them to form a single Drawable. - * However, if more than 4 drawables are provided, only the first 4 are used. + * Takes 1 or more drawables and merges them to form a single Drawable. However, + * if more than 4 drawables are provided, only the first 4 are used. */ public Drawable generateFolderIcon(Context context, Drawable... sources) { int width = appIconWidth; @@ -88,8 +86,8 @@ public class GraphicsUtil { } /** - * A utility method that simplifies calls to the generateFolderIcon() method that - * expects an array of Drawables. + * A utility method that simplifies calls to the generateFolderIcon() method + * that expects an array of Drawables. */ public Drawable generateFolderIcon(Context context, FolderItem app) { Drawable[] drawables = new Drawable[app.items.size()]; @@ -99,9 +97,7 @@ public class GraphicsUtil { return generateFolderIcon(context, drawables); } - /** - * Scales icons to match the icon pack - */ + /** Scales icons to match the icon pack */ public Drawable scaleImage(Context context, Drawable image, float scaleFactor) { if ((image == null) || !(image instanceof BitmapDrawable)) { return image; @@ -117,27 +113,22 @@ public class GraphicsUtil { public Bitmap addBackground(Bitmap bitmap, boolean isFolder) { if (!hasTransparency(bitmap)) { bitmap = Bitmap.createScaledBitmap(bitmap, appIconWidth, - (appIconWidth * bitmap.getHeight() / bitmap.getWidth()), - true); + (appIconWidth * bitmap.getHeight() / bitmap.getWidth()), true); return bitmap; } if (bitmap.getWidth() >= appIconWidth) { bitmap = Bitmap.createScaledBitmap(bitmap, appIconWidth, - (appIconWidth * bitmap.getHeight() / bitmap.getWidth()), - true); + (appIconWidth * bitmap.getHeight() / bitmap.getWidth()), true); } int width = appIconWidth; int height = width; - Bitmap mergedBitmap = Bitmap.createBitmap(width, height, Bitmap - .Config.ARGB_8888); + Bitmap mergedBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(mergedBitmap); canvas.drawColor(isFolder ? mFolderPreviewBackgroundColor : getDominantColor(bitmap)); - Paint paint = new Paint( - Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG); - canvas.drawBitmap(bitmap, (width - bitmap.getWidth()) / 2, - (height - bitmap.getHeight()) / 2, paint); + Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG); + canvas.drawBitmap(bitmap, (width - bitmap.getWidth()) / 2, (height - bitmap.getHeight()) / 2, paint); return mergedBitmap; } @@ -146,8 +137,8 @@ public class GraphicsUtil { if (appIcon instanceof BitmapDrawable) { bitmap = ((BitmapDrawable) appIcon).getBitmap(); } else { - bitmap = Bitmap.createBitmap(appIcon.getIntrinsicWidth(), - appIcon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); + bitmap = Bitmap.createBitmap(appIcon.getIntrinsicWidth(), appIcon.getIntrinsicHeight(), + Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); appIcon.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); appIcon.draw(canvas); @@ -156,8 +147,7 @@ public class GraphicsUtil { } public BitmapDrawable convertToRoundedCorner(Context context, Bitmap src) { - return new BitmapDrawable(context.getResources(), - BitmapUtils.getCroppedBitmap(src, DeviceProfile.path)); + return new BitmapDrawable(context.getResources(), BitmapUtils.getCroppedBitmap(src, DeviceProfile.path)); } public boolean hasTransparency(Bitmap bitmap) { @@ -172,11 +162,11 @@ public class GraphicsUtil { return false; } - /** * Finds the color with the most occurrences inside of a bitmap. * - * @param drawable to get the dominant color of + * @param drawable + * to get the dominant color of * @return the dominant color */ public int getDominantColor(Drawable drawable) { @@ -186,7 +176,8 @@ public class GraphicsUtil { /** * Finds the color with the most occurrences inside of a bitmap. * - * @param bitmap the bitmap to get the dominant color of + * @param bitmap + * the bitmap to get the dominant color of * @return the dominant color */ private int getDominantColor(Bitmap bitmap) { @@ -220,5 +211,4 @@ public class GraphicsUtil { return Color.WHITE; } } - -} \ No newline at end of file +} diff --git a/app/src/main/java/foundation/e/blisslauncher/core/utils/IOUtils.java b/app/src/main/java/foundation/e/blisslauncher/core/utils/IOUtils.java index 62f6a60133b4f54cb47d082c9748903f2f635a41..cfa187c35c9a908d2387432f8c2de615c92427cb 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/utils/IOUtils.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/utils/IOUtils.java @@ -22,9 +22,7 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -/** - * Supports various IO utility functions - */ +/** Supports various IO utility functions */ public class IOUtils { private static final int BUF_SIZE = 0x1000; // 4K diff --git a/app/src/main/java/foundation/e/blisslauncher/core/utils/LauncherConstants.java b/app/src/main/java/foundation/e/blisslauncher/core/utils/LauncherConstants.java index df11b15d7fb32693b140ded77171fd925b4fb8c3..5efc72c044ce8c3f529c3eb16a86405976e9ced1 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/utils/LauncherConstants.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/utils/LauncherConstants.java @@ -16,5 +16,4 @@ package foundation.e.blisslauncher.core.utils; public class LauncherConstants { - } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/utils/ListUtil.java b/app/src/main/java/foundation/e/blisslauncher/core/utils/ListUtil.java index 9c9bf65311ea2cefea92caf2af17e3ca534a3c00..2ed4d029fc1a653c567463878909964ac8cffca0 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/utils/ListUtil.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/utils/ListUtil.java @@ -16,18 +16,13 @@ package foundation.e.blisslauncher.core.utils; import android.app.usage.UsageStats; - import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; -/** - * Created by Amit Kumar - * Email : mr.doc10jl96@gmail.com - */ - +/** Created by Amit Kumar Email : mr.doc10jl96@gmail.com */ public class ListUtil { @SafeVarargs public static List asSafeList(T... tArr) { @@ -35,7 +30,8 @@ public class ListUtil { } /** - * To compare if two lists of {@link android.app.usage.UsageStats} contain same packages or not. + * To compare if two lists of {@link android.app.usage.UsageStats} contain same + * packages or not. * * @return true if both the lists contain the same packages otherwise false. */ diff --git a/app/src/main/java/foundation/e/blisslauncher/core/utils/LongArrayMap.java b/app/src/main/java/foundation/e/blisslauncher/core/utils/LongArrayMap.java index 415f07892f73b09ef4ebbb755e6fb1087cb6c259..f546e589cd081263b8b3be27d795c544f4eb9d64 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/utils/LongArrayMap.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/utils/LongArrayMap.java @@ -16,14 +16,10 @@ package foundation.e.blisslauncher.core.utils; import android.util.LongSparseArray; - import androidx.annotation.NonNull; - import java.util.Iterator; -/** - * Extension of {@link LongSparseArray} with some utility methods. - */ +/** Extension of {@link LongSparseArray} with some utility methods. */ public class LongArrayMap extends LongSparseArray implements Iterable { public boolean containsKey(long key) { diff --git a/app/src/main/java/foundation/e/blisslauncher/core/utils/MultiHashMap.java b/app/src/main/java/foundation/e/blisslauncher/core/utils/MultiHashMap.java index 7e036299b1ee5f2b8038c2af3aee41dfbc597fff..b3dfb9250fd01c1e24da3eeffb47b596f03a9b03 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/utils/MultiHashMap.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/utils/MultiHashMap.java @@ -5,7 +5,8 @@ import java.util.HashMap; public class MultiHashMap extends HashMap> { - public MultiHashMap() { } + public MultiHashMap() { + } public MultiHashMap(int size) { super(size); diff --git a/app/src/main/java/foundation/e/blisslauncher/core/utils/PackageManagerUtils.java b/app/src/main/java/foundation/e/blisslauncher/core/utils/PackageManagerUtils.java index 2ee5484bde32b533e8f90eb962763d6621bdc911..ae252fe615c92addce3067a15fefd40ae3b2eaf8 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/utils/PackageManagerUtils.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/utils/PackageManagerUtils.java @@ -45,8 +45,7 @@ public final class PackageManagerUtils { * @param flags * @return true if the package is enabled */ - public static boolean isAppEnabled(final Context context, - final String packageName, final int flags) { + public static boolean isAppEnabled(final Context context, final String packageName, final int flags) { final ApplicationInfo info = getApplicationInfo(context, packageName, flags); return info != null && info.enabled; } @@ -63,8 +62,8 @@ public final class PackageManagerUtils { } /** - * Check if a package can possibly be on the SDCard - * This is just a workaround and doesn't guarantee that the app is on SD card + * Check if a package can possibly be on the SDCard This is just a workaround + * and doesn't guarantee that the app is on SD card * * @param context * @param packageName @@ -103,8 +102,7 @@ public final class PackageManagerUtils { * @param flags * @return null if the package cannot be found or the ApplicationInfo is null */ - public static ApplicationInfo getApplicationInfo(final Context context, - final String packageName, final int flags) { + public static ApplicationInfo getApplicationInfo(final Context context, final String packageName, final int flags) { final PackageManager packageManager = context.getPackageManager(); ApplicationInfo info; try { diff --git a/app/src/main/java/foundation/e/blisslauncher/core/utils/Preconditions.java b/app/src/main/java/foundation/e/blisslauncher/core/utils/Preconditions.java index d412d2d3a870b6c978b231078e58202b4baa6f8b..4987d9acfee85b1221ccf8eb5370ee98c10fde1b 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/utils/Preconditions.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/utils/Preconditions.java @@ -29,10 +29,11 @@ public class Preconditions { } public static void assertWorkerThread() { - //TODO: Uncommnet after LauncherModel - /*if (!isSameLooper(LauncherModel.getWorkerLooper())) { - throw new IllegalStateException(); - }*/ + // TODO: Uncommnet after LauncherModel + /* + * if (!isSameLooper(LauncherModel.getWorkerLooper())) { throw new + * IllegalStateException(); } + */ } public static void assertUIThread() { diff --git a/app/src/main/java/foundation/e/blisslauncher/core/utils/Provider.java b/app/src/main/java/foundation/e/blisslauncher/core/utils/Provider.java index 2df9077a3e829f92594ebc6d129a74418790ceae..4ae2df8db3833a45ab246ce358e9619f969ecc92 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/utils/Provider.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/utils/Provider.java @@ -16,18 +16,16 @@ package foundation.e.blisslauncher.core.utils; -/** - * Utility class to allow lazy initialization of objects. - */ +/** Utility class to allow lazy initialization of objects. */ public abstract class Provider { /** - * Initializes and returns the object. This may contain expensive operations not suitable - * to UI thread. + * Initializes and returns the object. This may contain expensive operations not + * suitable to UI thread. */ public abstract T get(); - public static Provider of (final T value) { + public static Provider of(final T value) { return new Provider() { @Override public T get() { diff --git a/app/src/main/java/foundation/e/blisslauncher/core/utils/ResourceUtils.java b/app/src/main/java/foundation/e/blisslauncher/core/utils/ResourceUtils.java index 3ccdbad4ac6d2664ed2c19f29d89bc06e8c93251..3930558f88da2480450163053b3a56fe4a216699 100755 --- a/app/src/main/java/foundation/e/blisslauncher/core/utils/ResourceUtils.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/utils/ResourceUtils.java @@ -20,28 +20,30 @@ import android.content.res.AssetManager; import android.content.res.Configuration; import android.content.res.Resources; import android.util.DisplayMetrics; - -import java.lang.reflect.InvocationTargetException; - import foundation.e.blisslauncher.core.Utilities; +import java.lang.reflect.InvocationTargetException; public class ResourceUtils { /** - * Sets a fake configuration to the passed Resources to allow access to resources - * accessible to a sdk level. Used to backport adaptive icon support to different - * devices. + * Sets a fake configuration to the passed Resources to allow access to + * resources accessible to a sdk level. Used to backport adaptive icon support + * to different devices. * - * @param resources the resources to set the configuration to - * @param sdk the sdk level to become accessible - * @throws NoSuchMethodException if something is wrong - * @throws IllegalAccessException if something is very wrong - * @throws InvocationTargetException if something is really very extremely wrong + * @param resources + * the resources to set the configuration to + * @param sdk + * the sdk level to become accessible + * @throws NoSuchMethodException + * if something is wrong + * @throws IllegalAccessException + * if something is very wrong + * @throws InvocationTargetException + * if something is really very extremely wrong */ @SuppressLint("PrivateApi") public static void setFakeConfig(Resources resources, int sdk) - throws NoSuchMethodException, IllegalAccessException, - InvocationTargetException { + throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { int width, height; DisplayMetrics metrics = resources.getDisplayMetrics(); if (metrics.widthPixels >= metrics.heightPixels) { @@ -55,38 +57,24 @@ public class ResourceUtils { Configuration configuration = resources.getConfiguration(); if (Utilities.ATLEAST_OREO) { - AssetManager.class.getDeclaredMethod("setConfiguration", int.class, int.class, - String.class, int.class, int.class, - int.class, int.class, int.class, int.class, int.class, int.class, int.class, - int.class, int.class, - int.class, int.class, int.class, int.class) - .invoke(resources.getAssets(), configuration.mcc, configuration.mnc, - configuration.locale.toLanguageTag(), - configuration.orientation, configuration.touchscreen, - configuration.densityDpi, - configuration.keyboard, configuration.keyboardHidden, - configuration.navigation, - width, height, configuration.smallestScreenWidthDp, - configuration.screenWidthDp, configuration.screenHeightDp, - configuration.screenLayout, - configuration.uiMode, configuration.colorMode, sdk); + AssetManager.class.getDeclaredMethod("setConfiguration", int.class, int.class, String.class, int.class, + int.class, int.class, int.class, int.class, int.class, int.class, int.class, int.class, int.class, + int.class, int.class, int.class, int.class, int.class).invoke(resources.getAssets(), + configuration.mcc, configuration.mnc, configuration.locale.toLanguageTag(), + configuration.orientation, configuration.touchscreen, configuration.densityDpi, + configuration.keyboard, configuration.keyboardHidden, configuration.navigation, width, + height, configuration.smallestScreenWidthDp, configuration.screenWidthDp, + configuration.screenHeightDp, configuration.screenLayout, configuration.uiMode, + configuration.colorMode, sdk); } else { - AssetManager.class.getDeclaredMethod("setConfiguration", int.class, int.class, - String.class, int.class, int.class, - int.class, int.class, int.class, int.class, int.class, int.class, int.class, - int.class, int.class, - int.class, int.class, int.class) - .invoke(resources.getAssets(), configuration.mcc, configuration.mnc, - configuration.locale.toLanguageTag(), - configuration.orientation, configuration.touchscreen, - configuration.densityDpi, - configuration.keyboard, configuration.keyboardHidden, - configuration.navigation, - width, height, configuration.smallestScreenWidthDp, - configuration.screenWidthDp, configuration.screenHeightDp, - configuration.screenLayout, - configuration.uiMode, sdk); + AssetManager.class.getDeclaredMethod("setConfiguration", int.class, int.class, String.class, int.class, + int.class, int.class, int.class, int.class, int.class, int.class, int.class, int.class, int.class, + int.class, int.class, int.class, int.class).invoke(resources.getAssets(), configuration.mcc, + configuration.mnc, configuration.locale.toLanguageTag(), configuration.orientation, + configuration.touchscreen, configuration.densityDpi, configuration.keyboard, + configuration.keyboardHidden, configuration.navigation, width, height, + configuration.smallestScreenWidthDp, configuration.screenWidthDp, + configuration.screenHeightDp, configuration.screenLayout, configuration.uiMode, sdk); } } - } diff --git a/app/src/main/java/foundation/e/blisslauncher/core/utils/UserHandle.java b/app/src/main/java/foundation/e/blisslauncher/core/utils/UserHandle.java index 9c7a668112a72d7a4712401469b3866f673ba9b7..1a04c29c22480eba2384193fb1fe1415706861e2 100644 --- a/app/src/main/java/foundation/e/blisslauncher/core/utils/UserHandle.java +++ b/app/src/main/java/foundation/e/blisslauncher/core/utils/UserHandle.java @@ -20,7 +20,8 @@ import android.os.Build; import android.os.Process; /** - * Wrapper class for `android.os.UserHandle` that works with all Android versions + * Wrapper class for `android.os.UserHandle` that works with all Android + * versions */ public class UserHandle { private final long serial; @@ -81,7 +82,7 @@ public class UserHandle { return (serial == this.serial); } - public boolean isSameUser(UserHandle userHandle){ + public boolean isSameUser(UserHandle userHandle) { return userHandle.serial == this.serial; } } diff --git a/app/src/main/java/foundation/e/blisslauncher/features/launcher/AppProvider.java b/app/src/main/java/foundation/e/blisslauncher/features/launcher/AppProvider.java index 4762b38e23b9db6e69d62b00e6514cbcb6c40cf3..ff011c80a89586d7f921071c1b2b6f69f49af255 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/launcher/AppProvider.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/launcher/AppProvider.java @@ -17,15 +17,6 @@ import android.os.UserManager; import android.provider.MediaStore; import android.util.Log; import android.util.LongSparseArray; - -import java.text.Collator; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; - import foundation.e.blisslauncher.BlissLauncher; import foundation.e.blisslauncher.R; import foundation.e.blisslauncher.core.Utilities; @@ -46,30 +37,28 @@ import foundation.e.blisslauncher.features.launcher.tasks.LoadDatabaseTask; import foundation.e.blisslauncher.features.launcher.tasks.LoadShortcutTask; import foundation.e.blisslauncher.features.shortcuts.DeepShortcutManager; import foundation.e.blisslauncher.features.shortcuts.ShortcutInfoCompat; - +import java.text.Collator; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Map; // TODO: Find better solution instead of excessively using volatile and synchronized. // - and use RxJava instead of bad async tasks. public class AppProvider { - /** - * Represents all applications that is to be shown in Launcher - */ + /** Represents all applications that is to be shown in Launcher */ List mLauncherItems; - /** - * Represents networkItems stored in database. - */ + /** Represents networkItems stored in database. */ private List mDatabaseItems; - /** - * Represents all applications installed in device. - */ + /** Represents all applications installed in device. */ private Map mApplicationItems; - /** - * Represents all shortcuts which user has created. - */ + /** Represents all shortcuts which user has created. */ private Map mShortcutInfoCompats; private boolean appsLoaded = false; @@ -118,84 +107,69 @@ public class AppProvider { final UserManager manager = (UserManager) mContext.getSystemService(Context.USER_SERVICE); assert manager != null; - final LauncherApps launcher = (LauncherApps) mContext.getSystemService( - Context.LAUNCHER_APPS_SERVICE); + final LauncherApps launcher = (LauncherApps) mContext.getSystemService(Context.LAUNCHER_APPS_SERVICE); assert launcher != null; launcher.registerCallback(new LauncherApps.Callback() { @Override public void onPackageRemoved(String packageName, android.os.UserHandle user) { - if (packageName.equalsIgnoreCase(MICROG_PACKAGE) || packageName.equalsIgnoreCase( - MUPDF_PACKAGE)) { + if (packageName.equalsIgnoreCase(MICROG_PACKAGE) || packageName.equalsIgnoreCase(MUPDF_PACKAGE)) { return; } - PackageAddedRemovedHandler.handleEvent(mContext, - "android.intent.action.PACKAGE_REMOVED", - packageName, new UserHandle(manager.getSerialNumberForUser(user), user), - false - ); + PackageAddedRemovedHandler.handleEvent(mContext, "android.intent.action.PACKAGE_REMOVED", packageName, + new UserHandle(manager.getSerialNumberForUser(user), user), false); } @Override public void onPackageAdded(String packageName, android.os.UserHandle user) { - if (packageName.equalsIgnoreCase(MICROG_PACKAGE) || packageName.equalsIgnoreCase( - MUPDF_PACKAGE)) { + if (packageName.equalsIgnoreCase(MICROG_PACKAGE) || packageName.equalsIgnoreCase(MUPDF_PACKAGE)) { return; } - PackageAddedRemovedHandler.handleEvent(mContext, - "android.intent.action.PACKAGE_ADDED", - packageName, new UserHandle(manager.getSerialNumberForUser(user), user), - false - ); + PackageAddedRemovedHandler.handleEvent(mContext, "android.intent.action.PACKAGE_ADDED", packageName, + new UserHandle(manager.getSerialNumberForUser(user), user), false); } @Override public void onPackageChanged(String packageName, android.os.UserHandle user) { - if (packageName.equalsIgnoreCase(MICROG_PACKAGE) || packageName.equalsIgnoreCase( - MUPDF_PACKAGE)) { + if (packageName.equalsIgnoreCase(MICROG_PACKAGE) || packageName.equalsIgnoreCase(MUPDF_PACKAGE)) { return; } - PackageAddedRemovedHandler.handleEvent(mContext, - "android.intent.action.PACKAGE_CHANGED", - packageName, new UserHandle(manager.getSerialNumberForUser(user), user), - true - ); + PackageAddedRemovedHandler.handleEvent(mContext, "android.intent.action.PACKAGE_CHANGED", packageName, + new UserHandle(manager.getSerialNumberForUser(user), user), true); } @Override - public void onPackagesAvailable(String[] packageNames, android.os.UserHandle user, - boolean replacing) { - Log.d(TAG, "onPackagesAvailable() called with: packageNames = [" + packageNames + "], user = [" + user + "], replacing = [" + replacing + "]"); + public void onPackagesAvailable(String[] packageNames, android.os.UserHandle user, boolean replacing) { + Log.d(TAG, "onPackagesAvailable() called with: packageNames = [" + packageNames + "], user = [" + user + + "], replacing = [" + replacing + "]"); for (String packageName : packageNames) { - PackageAddedRemovedHandler.handleEvent(mContext, - "android.intent.action.MEDIA_MOUNTED", - packageName, new UserHandle(manager.getSerialNumberForUser(user), user), false - ); + PackageAddedRemovedHandler.handleEvent(mContext, "android.intent.action.MEDIA_MOUNTED", packageName, + new UserHandle(manager.getSerialNumberForUser(user), user), false); } } @Override - public void onPackagesUnavailable(String[] packageNames, android.os.UserHandle user, - boolean replacing) { - Log.d(TAG, "onPackagesUnavailable() called with: packageNames = [" + packageNames + "], user = [" + user + "], replacing = [" + replacing + "]"); - PackageAddedRemovedHandler.handleEvent(mContext, - "android.intent.action.MEDIA_UNMOUNTED", - null, new UserHandle(manager.getSerialNumberForUser(user), user), false - ); + public void onPackagesUnavailable(String[] packageNames, android.os.UserHandle user, boolean replacing) { + Log.d(TAG, "onPackagesUnavailable() called with: packageNames = [" + packageNames + "], user = [" + user + + "], replacing = [" + replacing + "]"); + PackageAddedRemovedHandler.handleEvent(mContext, "android.intent.action.MEDIA_UNMOUNTED", null, + new UserHandle(manager.getSerialNumberForUser(user), user), false); } @Override public void onPackagesSuspended(String[] packageNames, android.os.UserHandle user) { - Log.d(TAG, "onPackagesSuspended() called with: packageNames = [" + packageNames + "], user = [" + user + "]"); + Log.d(TAG, "onPackagesSuspended() called with: packageNames = [" + packageNames + "], user = [" + user + + "]"); } @Override public void onPackagesUnsuspended(String[] packageNames, android.os.UserHandle user) { super.onPackagesUnsuspended(packageNames, user); - Log.d(TAG, "onPackagesUnsuspended() called with: packageNames = [" + packageNames + "], user = [" + user + "]"); + Log.d(TAG, "onPackagesUnsuspended() called with: packageNames = [" + packageNames + "], user = [" + user + + "]"); } }); @@ -272,7 +246,8 @@ public class AppProvider { } public synchronized void loadDatabaseOver(List databaseItems) { - Log.d(TAG, "loadDatabaseOver() called with: databaseItems = [" + Thread.currentThread().getName() + "]" + mStopped); + Log.d(TAG, "loadDatabaseOver() called with: databaseItems = [" + Thread.currentThread().getName() + "]" + + mStopped); this.mDatabaseItems = databaseItems; databaseLoaded = true; handleAllProviderLoaded(); @@ -292,9 +267,7 @@ public class AppProvider { private List prepareLauncherItems() { Log.d(TAG, "prepareLauncherItems() called"); - /** - * Indices of folder in {@link #mLauncherItems}. - */ + /** Indices of folder in {@link #mLauncherItems}. */ LongSparseArray foldersIndex = new LongSparseArray<>(); List mLauncherItems = new ArrayList<>(); Collection applicationItems = mApplicationItems.values(); @@ -306,8 +279,8 @@ public class AppProvider { ApplicationItem applicationItem = mApplicationItems.get(databaseItem.id); if (applicationItem == null) { UserHandle userHandle = new UserHandle(); - if ((isAppOnSdcard(databaseItem.packageName, userHandle) || !isSdCardReady - ) && !DISABLED_PACKAGES.contains(databaseItem.packageName)) { + if ((isAppOnSdcard(databaseItem.packageName, userHandle) || !isSdCardReady) + && !DISABLED_PACKAGES.contains(databaseItem.packageName)) { Log.d(TAG, "Missing package: " + databaseItem.packageName); Log.d(TAG, "Is App on Sdcard " + isAppOnSdcard(databaseItem.packageName, userHandle)); Log.d(TAG, "Is Sdcard ready " + isSdCardReady); @@ -360,9 +333,7 @@ public class AppProvider { || shortcutItem.container == Constants.CONTAINER_HOTSEAT) { mLauncherItems.add(shortcutItem); } else { - FolderItem folderItem = - (FolderItem) mLauncherItems.get( - foldersIndex.get(shortcutItem.container)); + FolderItem folderItem = (FolderItem) mLauncherItems.get(foldersIndex.get(shortcutItem.container)); if (folderItem.items == null) { folderItem.items = new ArrayList<>(); } @@ -389,14 +360,12 @@ public class AppProvider { Collections.sort(folderItemsIndex); for (int i = folderItemsIndex.size() - 1; i >= 0; i--) { int itemIndex = folderItemsIndex.get(i); - FolderItem folderItem = - (FolderItem) mLauncherItems.get(itemIndex); + FolderItem folderItem = (FolderItem) mLauncherItems.get(itemIndex); if (folderItem.items == null || folderItem.items.size() == 0) { DatabaseManager.getManager(mContext).removeLauncherItem(folderItem.id); mLauncherItems.remove(itemIndex); } else { - folderItem.icon = new GraphicsUtil(mContext).generateFolderIcon(mContext, - folderItem); + folderItem.icon = new GraphicsUtil(mContext).generateFolderIcon(mContext, folderItem); } } @@ -414,13 +383,12 @@ public class AppProvider { ApplicationInfo info = null; try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { - info = ((LauncherApps) mContext.getSystemService( - Context.LAUNCHER_APPS_SERVICE)).getApplicationInfo( + info = ((LauncherApps) mContext.getSystemService(Context.LAUNCHER_APPS_SERVICE)).getApplicationInfo( packageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, userHandle.getRealHandle()); return info != null && (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; } else { - info = getContext().getPackageManager() - .getApplicationInfo(packageName, PackageManager.MATCH_UNINSTALLED_PACKAGES); + info = getContext().getPackageManager().getApplicationInfo(packageName, + PackageManager.MATCH_UNINSTALLED_PACKAGES); return info != null && info.enabled; } } catch (PackageManager.NameNotFoundException e) { @@ -435,8 +403,7 @@ public class AppProvider { shortcutItem.packageName = databaseItem.packageName; shortcutItem.title = databaseItem.title.toString(); shortcutItem.icon_blob = databaseItem.icon_blob; - Bitmap bitmap = BitmapFactory.decodeByteArray(databaseItem.icon_blob, 0, - databaseItem.icon_blob.length); + Bitmap bitmap = BitmapFactory.decodeByteArray(databaseItem.icon_blob, 0, databaseItem.icon_blob.length); shortcutItem.icon = new BitmapDrawable(mContext.getResources(), bitmap); shortcutItem.launchIntent = databaseItem.getIntent(); shortcutItem.launchIntentUri = databaseItem.launchIntentUri; @@ -450,8 +417,7 @@ public class AppProvider { private ShortcutItem prepareShortcutForOreo(LauncherItem databaseItem) { ShortcutInfoCompat info = mShortcutInfoCompats.get(databaseItem.id); if (info == null) { - Log.d(TAG, - "prepareShortcutForOreo() called with: databaseItem = [" + databaseItem + "]"); + Log.d(TAG, "prepareShortcutForOreo() called with: databaseItem = [" + databaseItem + "]"); return null; } @@ -461,8 +427,7 @@ public class AppProvider { shortcutItem.title = info.getShortLabel().toString(); Drawable icon = DeepShortcutManager.getInstance(mContext).getShortcutIconDrawable(info, mContext.getResources().getDisplayMetrics().densityDpi); - shortcutItem.icon = BlissLauncher.getApplication( - mContext).getIconsHandler().convertIcon(icon); + shortcutItem.icon = BlissLauncher.getApplication(mContext).getIconsHandler().convertIcon(icon); shortcutItem.launchIntent = info.makeIntent(); shortcutItem.container = databaseItem.container; shortcutItem.screenId = databaseItem.screenId; @@ -475,21 +440,15 @@ public class AppProvider { List mLauncherItems = new ArrayList<>(); List pinnedItems = new ArrayList<>(); PackageManager pm = mContext.getPackageManager(); - Intent[] intents = { - new Intent(Intent.ACTION_DIAL), - new Intent(Intent.ACTION_VIEW, Uri.parse("sms:")), - new Intent(Intent.ACTION_VIEW, Uri.parse("http:")), - new Intent(MediaStore.ACTION_IMAGE_CAPTURE) - }; + Intent[] intents = {new Intent(Intent.ACTION_DIAL), new Intent(Intent.ACTION_VIEW, Uri.parse("sms:")), + new Intent(Intent.ACTION_VIEW, Uri.parse("http:")), new Intent(MediaStore.ACTION_IMAGE_CAPTURE)}; for (int i = 0; i < intents.length; i++) { String packageName = AppUtils.getPackageNameForIntent(intents[i], pm); - LauncherApps launcherApps = (LauncherApps) mContext.getSystemService( - Context.LAUNCHER_APPS_SERVICE); - List list = launcherApps.getActivityList(packageName, - Process.myUserHandle()); + LauncherApps launcherApps = (LauncherApps) mContext.getSystemService(Context.LAUNCHER_APPS_SERVICE); + List list = launcherApps.getActivityList(packageName, Process.myUserHandle()); for (LauncherActivityInfo launcherActivityInfo : list) { - ApplicationItem applicationItem = mApplicationItems.get( - launcherActivityInfo.getComponentName().flattenToString()); + ApplicationItem applicationItem = mApplicationItems + .get(launcherActivityInfo.getComponentName().flattenToString()); if (applicationItem != null) { applicationItem.container = Constants.CONTAINER_HOTSEAT; applicationItem.cell = i; @@ -499,8 +458,7 @@ public class AppProvider { } } - for (Map.Entry stringApplicationItemEntry : mApplicationItems - .entrySet()) { + for (Map.Entry stringApplicationItemEntry : mApplicationItems.entrySet()) { if (!pinnedItems.contains(stringApplicationItemEntry.getValue())) { mLauncherItems.add(stringApplicationItemEntry.getValue()); } diff --git a/app/src/main/java/foundation/e/blisslauncher/features/launcher/AppsRepository.java b/app/src/main/java/foundation/e/blisslauncher/features/launcher/AppsRepository.java index c4262dff5a7b42c17f968ff7657a6fd8514e75c0..a6db8124c74cb76c6f7fc6b614d84cc0d8a964d8 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/launcher/AppsRepository.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/launcher/AppsRepository.java @@ -1,10 +1,8 @@ package foundation.e.blisslauncher.features.launcher; import com.jakewharton.rxrelay2.BehaviorRelay; - -import java.util.List; - import foundation.e.blisslauncher.core.database.model.LauncherItem; +import java.util.List; public class AppsRepository { @@ -24,7 +22,7 @@ public class AppsRepository { return sAppsRepository; } - public void clearAll(){ + public void clearAll() { appsRelay = BehaviorRelay.create(); } diff --git a/app/src/main/java/foundation/e/blisslauncher/features/launcher/DetectSwipeGestureListener.java b/app/src/main/java/foundation/e/blisslauncher/features/launcher/DetectSwipeGestureListener.java index afef40622ebc1f4f086048c4fe4d5259a644e6ae..df554540b3d1c09901b865f2ad5de53df73e9d82 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/launcher/DetectSwipeGestureListener.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/launcher/DetectSwipeGestureListener.java @@ -59,5 +59,4 @@ public class DetectSwipeGestureListener extends GestureDetector.SimpleOnGestureL public boolean onDoubleTap(MotionEvent e) { return false; } - } diff --git a/app/src/main/java/foundation/e/blisslauncher/features/launcher/EventsObserverImpl.java b/app/src/main/java/foundation/e/blisslauncher/features/launcher/EventsObserverImpl.java index d1253e3a7da1d33d488d9af6dc5c8bb3a88939dc..171cf1cade3924a21bb0d907b2464448eb88548b 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/launcher/EventsObserverImpl.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/launcher/EventsObserverImpl.java @@ -1,9 +1,6 @@ package foundation.e.blisslauncher.features.launcher; import android.util.Log; - -import java.util.Calendar; - import foundation.e.blisslauncher.core.events.AppAddEvent; import foundation.e.blisslauncher.core.events.AppChangeEvent; import foundation.e.blisslauncher.core.events.AppRemoveEvent; @@ -12,6 +9,7 @@ import foundation.e.blisslauncher.core.events.EventRelay; import foundation.e.blisslauncher.core.events.ForceReloadEvent; import foundation.e.blisslauncher.core.events.ShortcutAddEvent; import foundation.e.blisslauncher.core.events.TimeChangedEvent; +import java.util.Calendar; public class EventsObserverImpl implements EventRelay.EventsObserver { @@ -25,24 +23,24 @@ public class EventsObserverImpl implements EventRelay.EventsObserver { @Override public void accept(Event event) { - Log.i(TAG, "accept: "+event.getEventType()); + Log.i(TAG, "accept: " + event.getEventType()); switch (event.getEventType()) { - case AppAddEvent.TYPE: + case AppAddEvent.TYPE : launcherActivity.onAppAddEvent((AppAddEvent) event); break; - case AppChangeEvent.TYPE: + case AppChangeEvent.TYPE : launcherActivity.onAppChangeEvent((AppChangeEvent) event); break; - case AppRemoveEvent.TYPE: + case AppRemoveEvent.TYPE : launcherActivity.onAppRemoveEvent((AppRemoveEvent) event); break; - case ShortcutAddEvent.TYPE: + case ShortcutAddEvent.TYPE : launcherActivity.onShortcutAddEvent((ShortcutAddEvent) event); break; - case TimeChangedEvent.TYPE: + case TimeChangedEvent.TYPE : launcherActivity.updateAllCalendarIcons(Calendar.getInstance()); break; - case ForceReloadEvent.TYPE: + case ForceReloadEvent.TYPE : launcherActivity.forceReload(); break; } @@ -50,7 +48,7 @@ public class EventsObserverImpl implements EventRelay.EventsObserver { @Override public void complete() { - //BlissLauncher.getApplication(launcherActivity).getAppProvider().reload(); + // BlissLauncher.getApplication(launcherActivity).getAppProvider().reload(); } @Override diff --git a/app/src/main/java/foundation/e/blisslauncher/features/launcher/LauncherActivity.java b/app/src/main/java/foundation/e/blisslauncher/features/launcher/LauncherActivity.java index d3f6b44f90608f3b62486f48c3bc77b4f6cbcf33..939f68730da9e2685cec6fda3155cd7791045ad2 100755 --- a/app/src/main/java/foundation/e/blisslauncher/features/launcher/LauncherActivity.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/launcher/LauncherActivity.java @@ -160,9 +160,11 @@ import io.reactivex.observers.DisposableObserver; import io.reactivex.schedulers.Schedulers; import me.relex.circleindicator.CircleIndicator; -public class LauncherActivity extends AppCompatActivity implements - AutoCompleteAdapter.OnSuggestionClickListener, - OnSwipeDownListener, WallpaperManagerCompat.OnColorsChangedListener { +public class LauncherActivity extends AppCompatActivity + implements + AutoCompleteAdapter.OnSuggestionClickListener, + OnSwipeDownListener, + WallpaperManagerCompat.OnColorsChangedListener { public static final int REORDER_TIMEOUT = 350; private final static int EMPTY_LOCATION_DRAG = -999; @@ -210,7 +212,6 @@ public class LauncherActivity extends AppCompatActivity implements private boolean allAppsDisplayed; private boolean forceRefreshSuggestedApps = false; - private List mSuggestedApps = new ArrayList<>(); private FrameLayout swipeSearchContainer; private InsettableRelativeLayout workspace; @@ -234,7 +235,8 @@ public class LauncherActivity extends AppCompatActivity implements private boolean showSwipeSearch; private RoundedWidgetView activeRoundedWidgetView; - // EventRelay to handle pass events related to app addition, deletion or changed. + // EventRelay to handle pass events related to app addition, deletion or + // changed. private EventRelay events; private ManagedProfileBroadcastReceiver managedProfileReceiver; @@ -277,10 +279,9 @@ public class LauncherActivity extends AppCompatActivity implements mAppWidgetManager = BlissLauncher.getApplication(this).getAppWidgetManager(); mAppWidgetHost = BlissLauncher.getApplication(this).getAppWidgetHost(); - mLauncherView = LayoutInflater.from(this).inflate( - foundation.e.blisslauncher.R.layout.activity_main, null); + mLauncherView = LayoutInflater.from(this).inflate(foundation.e.blisslauncher.R.layout.activity_main, null); - //BlissLauncher.getApplication(LauncherActivity.this).getAppProvider().reload(); + // BlissLauncher.getApplication(LauncherActivity.this).getAppProvider().reload(); setContentView(mLauncherView); setupViews(); @@ -296,8 +297,7 @@ public class LauncherActivity extends AppCompatActivity implements String permissionString = Settings.Secure.getString(cr, setting); if (permissionString == null || !permissionString.contains(getPackageName())) { if (BuildConfig.DEBUG) { - startActivity( - new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS")); + startActivity(new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS")); } else if (!Preferences.shouldAskForNotificationAccess(this)) { ComponentName cn = new ComponentName(this, NotificationService.class); if (permissionString == null) { @@ -314,8 +314,10 @@ public class LauncherActivity extends AppCompatActivity implements } } - if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { - requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_REQUEST_CODE); + if (ActivityCompat.checkSelfPermission(this, + Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { + requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, + STORAGE_PERMISSION_REQUEST_CODE); } // Start NotificationService to add count badge to Icons @@ -364,8 +366,7 @@ public class LauncherActivity extends AppCompatActivity implements mDock = mLauncherView.findViewById(R.id.dock); mIndicator = mLauncherView.findViewById(R.id.page_indicator); - mFolderWindowContainer = mLauncherView.findViewById( - R.id.folder_window_container); + mFolderWindowContainer = mLauncherView.findViewById(R.id.folder_window_container); mFolderAppsViewPager = mLauncherView.findViewById(R.id.folder_apps); mFolderTitleInput = mLauncherView.findViewById(R.id.folder_title); mProgressBar = mLauncherView.findViewById(R.id.progressbar); @@ -376,10 +377,8 @@ public class LauncherActivity extends AppCompatActivity implements wobbleAnimation = AnimationUtils.loadAnimation(this, R.anim.wobble); wobbleReverseAnimation = AnimationUtils.loadAnimation(this, R.anim.wobble_reverse); - getWindow().getDecorView().setSystemUiVisibility( - View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | - View.SYSTEM_UI_FLAG_LAYOUT_STABLE - | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); + getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION + | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); workspace.setOnClickListener(v -> { if (swipeSearchContainer.getVisibility() == VISIBLE) { hideSwipeSearchContainer(); @@ -388,34 +387,28 @@ public class LauncherActivity extends AppCompatActivity implements } private void createOrUpdateIconGrid() { - getCompositeDisposable().add( - BlissLauncher.getApplication(this) - .getAppProvider() - .getAppsRepository() - .getAppsRelay() - .distinctUntilChanged() - .observeOn(AndroidSchedulers.mainThread()) - .subscribeWith(new DisposableObserver>() { - @Override - public void onNext(List launcherItems) { - if (launcherItems == null || launcherItems.size() <= 0) { - BlissLauncher.getApplication(LauncherActivity.this).getAppProvider().reload(true); - } else if (!allAppsDisplayed) { - showApps(launcherItems); - } - } + getCompositeDisposable().add(BlissLauncher.getApplication(this).getAppProvider().getAppsRepository() + .getAppsRelay().distinctUntilChanged().observeOn(AndroidSchedulers.mainThread()) + .subscribeWith(new DisposableObserver>() { + @Override + public void onNext(List launcherItems) { + if (launcherItems == null || launcherItems.size() <= 0) { + BlissLauncher.getApplication(LauncherActivity.this).getAppProvider().reload(true); + } else if (!allAppsDisplayed) { + showApps(launcherItems); + } + } - @Override - public void onError(Throwable e) { - e.printStackTrace(); - } + @Override + public void onError(Throwable e) { + e.printStackTrace(); + } - @Override - public void onComplete() { + @Override + public void onComplete() { - } - }) - ); + } + })); } private void addDefaultWidgets() { @@ -423,7 +416,8 @@ public class LauncherActivity extends AppCompatActivity implements Set existingProviders = new HashSet<>(); for (int widgetId : widgetIds) { AppWidgetProviderInfo info = mAppWidgetManager.getAppWidgetInfo(widgetId); - if (info == null) continue; + if (info == null) + continue; existingProviders.add(info.provider); } @@ -475,18 +469,15 @@ public class LauncherActivity extends AppCompatActivity implements public void updateAllCalendarIcons(Calendar calendar) { for (BlissFrameLayout blissIcon : mCalendarIcons) { - CalendarIcon calendarIcon = new CalendarIcon( - blissIcon.findViewById(R.id.calendar_month_textview), + CalendarIcon calendarIcon = new CalendarIcon(blissIcon.findViewById(R.id.calendar_month_textview), blissIcon.findViewById(R.id.calendar_date_textview)); updateCalendarIcon(calendarIcon, calendar); } } private void updateCalendarIcon(CalendarIcon calendarIcon, Calendar calendar) { - calendarIcon.monthTextView.setText( - Utilities.convertMonthToString()); - calendarIcon.dayTextView.setText( - String.valueOf(calendar.get(Calendar.DAY_OF_MONTH))); + calendarIcon.monthTextView.setText(Utilities.convertMonthToString()); + calendarIcon.dayTextView.setText(String.valueOf(calendar.get(Calendar.DAY_OF_MONTH))); } @Override @@ -515,8 +506,7 @@ public class LauncherActivity extends AppCompatActivity implements while (id != null) { for (int i = 0; i < widgetContainer.getChildCount(); i++) { if (widgetContainer.getChildAt(i) instanceof RoundedWidgetView) { - RoundedWidgetView appWidgetHostView = - (RoundedWidgetView) widgetContainer.getChildAt(i); + RoundedWidgetView appWidgetHostView = (RoundedWidgetView) widgetContainer.getChildAt(i); if (appWidgetHostView.getAppWidgetId() == id) { widgetContainer.removeViewAt(i); DatabaseManager.getManager(this).removeWidget(id); @@ -537,8 +527,7 @@ public class LauncherActivity extends AppCompatActivity implements } } - private void addWidgetToContainer( - RoundedWidgetView widgetView) { + private void addWidgetToContainer(RoundedWidgetView widgetView) { widgetContainer.addView(widgetView); } @@ -597,7 +586,7 @@ public class LauncherActivity extends AppCompatActivity implements public void onAppAddEvent(AppAddEvent appAddEvent) { updateOrAddApp(appAddEvent.getPackageName(), appAddEvent.getUserHandle()); - //DatabaseManager.getManager(this).saveLayouts(pages, mDock); + // DatabaseManager.getManager(this).saveLayouts(pages, mDock); if (moveTo != -1) { mHorizontalPager.setCurrentPage(moveTo); moveTo = -1; @@ -635,8 +624,7 @@ public class LauncherActivity extends AppCompatActivity implements BlissFrameLayout view = prepareLauncherItem(launcherItem); int current = 0; - while ((current < pages.size() && pages.get(current).getChildCount() - == mDeviceProfile.maxAppsPerPage)) { + while ((current < pages.size() && pages.get(current).getChildCount() == mDeviceProfile.maxAppsPerPage)) { current++; } @@ -646,8 +634,7 @@ public class LauncherActivity extends AppCompatActivity implements dot.setImageDrawable(getDrawable(R.drawable.dot_off)); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( getResources().getDimensionPixelSize(R.dimen.dotSize), - getResources().getDimensionPixelSize(R.dimen.dotSize) - ); + getResources().getDimensionPixelSize(R.dimen.dotSize)); dot.setLayoutParams(params); mIndicator.addView(dot); mHorizontalPager.addView(pages.get(current)); @@ -665,15 +652,13 @@ public class LauncherActivity extends AppCompatActivity implements for (int i = 0; i < mFolderAppsViewPager.getChildCount(); i++) { GridLayout gridLayout = (GridLayout) mFolderAppsViewPager.getChildAt(i); for (int j = 0; j < gridLayout.getChildCount(); j++) { - BlissFrameLayout viewGroup = - (BlissFrameLayout) gridLayout.getChildAt(j); + BlissFrameLayout viewGroup = (BlissFrameLayout) gridLayout.getChildAt(j); final LauncherItem existingItem = getAppDetails(viewGroup); if (existingItem.itemType == Constants.ITEM_TYPE_SHORTCUT) { ShortcutItem existingShortcutItem = (ShortcutItem) existingItem; if (existingShortcutItem.id.equalsIgnoreCase(shortcutItem.id)) { BlissFrameLayout blissFrameLayout = prepareLauncherItem(shortcutItem); - GridLayout.LayoutParams iconLayoutParams = - new GridLayout.LayoutParams(); + GridLayout.LayoutParams iconLayoutParams = new GridLayout.LayoutParams(); iconLayoutParams.height = mDeviceProfile.cellHeightPx; iconLayoutParams.width = mDeviceProfile.cellWidthPx; gridLayout.removeViewAt(j); @@ -686,21 +671,17 @@ public class LauncherActivity extends AppCompatActivity implements } for (int i = 0; i < mDock.getChildCount(); i++) { - BlissFrameLayout viewGroup = - (BlissFrameLayout) mDock.getChildAt(i); + BlissFrameLayout viewGroup = (BlissFrameLayout) mDock.getChildAt(i); LauncherItem launcherItem = getAppDetails(viewGroup); if (launcherItem.itemType == Constants.ITEM_TYPE_FOLDER) { FolderItem folderItem = (FolderItem) launcherItem; for (int k = 0; k < folderItem.items.size(); k++) { if (folderItem.items.get(k).itemType == Constants.ITEM_TYPE_SHORTCUT) { ShortcutItem existingShortcutItem = (ShortcutItem) folderItem.items.get(k); - if (existingShortcutItem.id.equalsIgnoreCase( - shortcutItem.id)) { + if (existingShortcutItem.id.equalsIgnoreCase(shortcutItem.id)) { folderItem.items.set(k, shortcutItem); - folderItem.icon = new GraphicsUtil(this).generateFolderIcon(this, - folderItem); - BlissFrameLayout blissFrameLayout = prepareLauncherItem( - launcherItem); + folderItem.icon = new GraphicsUtil(this).generateFolderIcon(this, folderItem); + BlissFrameLayout blissFrameLayout = prepareLauncherItem(launcherItem); mDock.removeViewAt(i); addAppToDock(blissFrameLayout, i); return; @@ -724,22 +705,17 @@ public class LauncherActivity extends AppCompatActivity implements for (int i = 0; i < pages.size(); i++) { GridLayout gridLayout = pages.get(i); for (int j = 0; j < gridLayout.getChildCount(); j++) { - BlissFrameLayout viewGroup = - (BlissFrameLayout) gridLayout.getChildAt(j); + BlissFrameLayout viewGroup = (BlissFrameLayout) gridLayout.getChildAt(j); LauncherItem launcherItem = getAppDetails(viewGroup); if (launcherItem.itemType == Constants.ITEM_TYPE_FOLDER) { FolderItem folderItem = (FolderItem) launcherItem; for (int k = 0; k < folderItem.items.size(); k++) { if (folderItem.items.get(k).itemType == Constants.ITEM_TYPE_SHORTCUT) { - ShortcutItem existingShortcutItem = - (ShortcutItem) folderItem.items.get(k); - if (existingShortcutItem.id.equalsIgnoreCase( - shortcutItem.id)) { + ShortcutItem existingShortcutItem = (ShortcutItem) folderItem.items.get(k); + if (existingShortcutItem.id.equalsIgnoreCase(shortcutItem.id)) { folderItem.items.set(k, shortcutItem); - folderItem.icon = new GraphicsUtil(this).generateFolderIcon(this, - folderItem); - BlissFrameLayout blissFrameLayout = prepareLauncherItem( - launcherItem); + folderItem.icon = new GraphicsUtil(this).generateFolderIcon(this, folderItem); + BlissFrameLayout blissFrameLayout = prepareLauncherItem(launcherItem); gridLayout.removeViewAt(j); addAppToGrid(gridLayout, blissFrameLayout, j); moveTo = i + 1; @@ -795,7 +771,8 @@ public class LauncherActivity extends AppCompatActivity implements for (LauncherItem item : folderItem.items) { if (item.itemType == Constants.ITEM_TYPE_APPLICATION) { ApplicationItem applicationItem = (ApplicationItem) item; - if (applicationItem.packageName.equalsIgnoreCase(packageName) && applicationItem.user.isSameUser(userHandle)) { + if (applicationItem.packageName.equalsIgnoreCase(packageName) + && applicationItem.user.isSameUser(userHandle)) { folderItem.items.remove(applicationItem); } } else if (item.itemType == Constants.ITEM_TYPE_SHORTCUT) { @@ -808,7 +785,8 @@ public class LauncherActivity extends AppCompatActivity implements updateFolderInGrid(mDock, folderItem, j); } else if (appItem.itemType == Constants.ITEM_TYPE_APPLICATION) { ApplicationItem applicationItem = (ApplicationItem) appItem; - if (applicationItem.packageName.equalsIgnoreCase(packageName) && applicationItem.user.isSameUser(userHandle)) { + if (applicationItem.packageName.equalsIgnoreCase(packageName) + && applicationItem.user.isSameUser(userHandle)) { mDock.removeViewAt(j); } } else if (appItem.itemType == Constants.ITEM_TYPE_SHORTCUT) { @@ -828,7 +806,8 @@ public class LauncherActivity extends AppCompatActivity implements for (LauncherItem item : folderItem.items) { if (item.itemType == Constants.ITEM_TYPE_APPLICATION) { ApplicationItem applicationItem = (ApplicationItem) item; - if (applicationItem.packageName.equalsIgnoreCase(packageName) && applicationItem.user.isSameUser(userHandle)) { + if (applicationItem.packageName.equalsIgnoreCase(packageName) + && applicationItem.user.isSameUser(userHandle)) { folderItem.items.remove(applicationItem); } } else if (item.itemType == Constants.ITEM_TYPE_SHORTCUT) { @@ -851,7 +830,8 @@ public class LauncherActivity extends AppCompatActivity implements } } else if (launcherItem.itemType == Constants.ITEM_TYPE_APPLICATION) { ApplicationItem applicationItem = (ApplicationItem) launcherItem; - if (applicationItem.packageName.equalsIgnoreCase(packageName) && applicationItem.user.isSameUser(userHandle)) { + if (applicationItem.packageName.equalsIgnoreCase(packageName) + && applicationItem.user.isSameUser(userHandle)) { grid.removeViewAt(j); if (grid.getChildCount() == 0) { pages.remove(i); @@ -885,8 +865,7 @@ public class LauncherActivity extends AppCompatActivity implements private void updateFolder() { mFolderAppsViewPager.getAdapter().notifyDataSetChanged(); if (activeFolder.items.size() == 0) { - ((ViewGroup) activeFolderView.getParent()).removeView - (activeFolderView); + ((ViewGroup) activeFolderView.getParent()).removeView(activeFolderView); hideFolderWindowContainer(); } else { if (activeFolder.items.size() == 1) { @@ -898,32 +877,25 @@ public class LauncherActivity extends AppCompatActivity implements if (folderFromDock) { addAppToDock(view, mDock.indexOfChild(activeFolderView)); } else { - GridLayout gridLayout = pages.get - (getCurrentAppsPageNumber()); - addAppToGrid(gridLayout, view, - gridLayout.indexOfChild(activeFolderView)); + GridLayout gridLayout = pages.get(getCurrentAppsPageNumber()); + addAppToGrid(gridLayout, view, gridLayout.indexOfChild(activeFolderView)); } - ((ViewGroup) activeFolderView.getParent()).removeView( - activeFolderView); + ((ViewGroup) activeFolderView.getParent()).removeView(activeFolderView); hideFolderWindowContainer(); } else { updateIcon(activeFolderView, activeFolder, - new GraphicsUtil(this).generateFolderIcon(this, - activeFolder), - folderFromDock); + new GraphicsUtil(this).generateFolderIcon(this, activeFolder), folderFromDock); hideFolderWindowContainer(); } } } - private void updateFolderInGrid(GridLayout grid, FolderItem folderItem, - int folderIndex) { + private void updateFolderInGrid(GridLayout grid, FolderItem folderItem, int folderIndex) { if (folderItem.items.size() == 0) { grid.removeViewAt(folderIndex); } else { - folderItem.icon = new GraphicsUtil(this).generateFolderIcon(this, - folderItem); + folderItem.icon = new GraphicsUtil(this).generateFolderIcon(this, folderItem); BlissFrameLayout blissFrameLayout = prepareLauncherItem(folderItem); grid.removeViewAt(folderIndex); if (grid instanceof DockGridLayout) { @@ -946,16 +918,14 @@ public class LauncherActivity extends AppCompatActivity implements for (int i = 0; i < mFolderAppsViewPager.getChildCount(); i++) { GridLayout gridLayout = (GridLayout) mFolderAppsViewPager.getChildAt(i); for (int j = 0; j < gridLayout.getChildCount(); j++) { - BlissFrameLayout viewGroup = - (BlissFrameLayout) gridLayout.getChildAt(j); - final LauncherItem existingItem = - getAppDetails(viewGroup); + BlissFrameLayout viewGroup = (BlissFrameLayout) gridLayout.getChildAt(j); + final LauncherItem existingItem = getAppDetails(viewGroup); if (existingItem.itemType == Constants.ITEM_TYPE_APPLICATION) { ApplicationItem existingAppItem = (ApplicationItem) existingItem; - if (existingAppItem.packageName.equalsIgnoreCase(packageName) && existingAppItem.user.isSameUser(userHandle)) { + if (existingAppItem.packageName.equalsIgnoreCase(packageName) + && existingAppItem.user.isSameUser(userHandle)) { BlissFrameLayout blissFrameLayout = prepareLauncherItem(updatedAppItem); - GridLayout.LayoutParams iconLayoutParams = - new GridLayout.LayoutParams(); + GridLayout.LayoutParams iconLayoutParams = new GridLayout.LayoutParams(); iconLayoutParams.height = mDeviceProfile.cellHeightPx; iconLayoutParams.width = mDeviceProfile.cellWidthPx; gridLayout.removeViewAt(j); @@ -969,21 +939,18 @@ public class LauncherActivity extends AppCompatActivity implements } for (int i = 0; i < mDock.getChildCount(); i++) { - BlissFrameLayout viewGroup = - (BlissFrameLayout) mDock.getChildAt(i); + BlissFrameLayout viewGroup = (BlissFrameLayout) mDock.getChildAt(i); LauncherItem existingAppItem = getAppDetails(viewGroup); if (existingAppItem.itemType == Constants.ITEM_TYPE_FOLDER) { FolderItem folderItem = (FolderItem) existingAppItem; for (int k = 0; k < folderItem.items.size(); k++) { if (folderItem.items.get(k).itemType == Constants.ITEM_TYPE_APPLICATION) { ApplicationItem applicationItem = (ApplicationItem) folderItem.items.get(k); - if (applicationItem.packageName.equalsIgnoreCase( - packageName) && applicationItem.user.isSameUser(userHandle)) { + if (applicationItem.packageName.equalsIgnoreCase(packageName) + && applicationItem.user.isSameUser(userHandle)) { folderItem.items.set(k, updatedAppItem); - folderItem.icon = new GraphicsUtil(this).generateFolderIcon(this, - folderItem); - BlissFrameLayout blissFrameLayout = prepareLauncherItem( - existingAppItem); + folderItem.icon = new GraphicsUtil(this).generateFolderIcon(this, folderItem); + BlissFrameLayout blissFrameLayout = prepareLauncherItem(existingAppItem); mDock.removeViewAt(i); addAppToDock(blissFrameLayout, i); return; @@ -1008,22 +975,18 @@ public class LauncherActivity extends AppCompatActivity implements for (int i = 0; i < pages.size(); i++) { GridLayout gridLayout = pages.get(i); for (int j = 0; j < gridLayout.getChildCount(); j++) { - BlissFrameLayout viewGroup = - (BlissFrameLayout) gridLayout.getChildAt(j); + BlissFrameLayout viewGroup = (BlissFrameLayout) gridLayout.getChildAt(j); LauncherItem existingAppItem = getAppDetails(viewGroup); if (existingAppItem.itemType == Constants.ITEM_TYPE_FOLDER) { FolderItem folderItem = (FolderItem) existingAppItem; for (int k = 0; k < folderItem.items.size(); k++) { if (folderItem.items.get(k).itemType == Constants.ITEM_TYPE_APPLICATION) { - ApplicationItem applicationItem = - (ApplicationItem) folderItem.items.get(k); - if (applicationItem.packageName.equalsIgnoreCase( - packageName) && applicationItem.user.isSameUser(userHandle)) { + ApplicationItem applicationItem = (ApplicationItem) folderItem.items.get(k); + if (applicationItem.packageName.equalsIgnoreCase(packageName) + && applicationItem.user.isSameUser(userHandle)) { folderItem.items.set(k, updatedAppItem); - folderItem.icon = new GraphicsUtil(this).generateFolderIcon(this, - folderItem); - BlissFrameLayout blissFrameLayout = prepareLauncherItem( - existingAppItem); + folderItem.icon = new GraphicsUtil(this).generateFolderIcon(this, folderItem); + BlissFrameLayout blissFrameLayout = prepareLauncherItem(existingAppItem); gridLayout.removeViewAt(j); addAppToGrid(gridLayout, blissFrameLayout, j); moveTo = i + 1; @@ -1072,27 +1035,26 @@ public class LauncherActivity extends AppCompatActivity implements } private void createOrUpdateBadgeCount() { - getCompositeDisposable().add( - NotificationRepository.getNotificationRepository().getNotifications().subscribeWith( - new DisposableObserver>() { - @Override - public void onNext(Set packages) { - mAppsWithNotifications = packages; - updateBadges(mAppsWithNotifications); - } + getCompositeDisposable().add(NotificationRepository.getNotificationRepository().getNotifications() + .subscribeWith(new DisposableObserver>() { + @Override + public void onNext(Set packages) { + mAppsWithNotifications = packages; + updateBadges(mAppsWithNotifications); + } - @Override - public void onError(Throwable e) { - Toast.makeText(LauncherActivity.this, getString(R.string.toast_recreating_launcher), - Toast.LENGTH_SHORT).show(); - e.printStackTrace(); - recreate(); - } + @Override + public void onError(Throwable e) { + Toast.makeText(LauncherActivity.this, getString(R.string.toast_recreating_launcher), + Toast.LENGTH_SHORT).show(); + e.printStackTrace(); + recreate(); + } - @Override - public void onComplete() { - } - })); + @Override + public void onComplete() { + } + })); } private void updateBadges(Set appsWithNotifications) { @@ -1100,8 +1062,7 @@ public class LauncherActivity extends AppCompatActivity implements for (int i = 0; i < mFolderAppsViewPager.getChildCount(); i++) { GridLayout gridLayout = (GridLayout) mFolderAppsViewPager.getChildAt(i); for (int j = 0; j < gridLayout.getChildCount(); j++) { - BlissFrameLayout viewGroup = - (BlissFrameLayout) gridLayout.getChildAt(j); + BlissFrameLayout viewGroup = (BlissFrameLayout) gridLayout.getChildAt(j); final LauncherItem appItem = getAppDetails(viewGroup); if (appItem.itemType != Constants.ITEM_TYPE_SHORTCUT) { updateBadgeToApp(viewGroup, appItem, appsWithNotifications, true); @@ -1112,8 +1073,7 @@ public class LauncherActivity extends AppCompatActivity implements for (int i = 0; i < pages.size(); i++) { GridLayout gridLayout = pages.get(i); for (int j = 0; j < gridLayout.getChildCount(); j++) { - BlissFrameLayout viewGroup = - (BlissFrameLayout) gridLayout.getChildAt(j); + BlissFrameLayout viewGroup = (BlissFrameLayout) gridLayout.getChildAt(j); final LauncherItem appItem = getAppDetails(viewGroup); if (appItem.itemType != Constants.ITEM_TYPE_SHORTCUT) { updateBadgeToApp(viewGroup, appItem, appsWithNotifications, true); @@ -1122,8 +1082,7 @@ public class LauncherActivity extends AppCompatActivity implements } for (int i = 0; i < mDock.getChildCount(); i++) { - BlissFrameLayout viewGroup = - (BlissFrameLayout) mDock.getChildAt(i); + BlissFrameLayout viewGroup = (BlissFrameLayout) mDock.getChildAt(i); final LauncherItem appItem = getAppDetails(viewGroup); if (appItem.itemType != Constants.ITEM_TYPE_SHORTCUT) { updateBadgeToApp(viewGroup, appItem, appsWithNotifications, false); @@ -1131,12 +1090,11 @@ public class LauncherActivity extends AppCompatActivity implements } } - private void updateBadgeToApp(BlissFrameLayout viewGroup, LauncherItem appItem, - Set appsWithNotifications, boolean withText) { + private void updateBadgeToApp(BlissFrameLayout viewGroup, LauncherItem appItem, Set appsWithNotifications, + boolean withText) { if (appItem != null) { if (appItem.itemType == Constants.ITEM_TYPE_FOLDER) { - viewGroup.applyBadge(checkHasApp((FolderItem) appItem, appsWithNotifications), - withText); + viewGroup.applyBadge(checkHasApp((FolderItem) appItem, appsWithNotifications), withText); } else { ApplicationItem applicationItem = (ApplicationItem) appItem; String pkgName = applicationItem.packageName; @@ -1158,12 +1116,11 @@ public class LauncherActivity extends AppCompatActivity implements } /** - * Adds a listener to the folder title. - * When clicked, the TextView transforms into an EditText. - * When the user changes the title and presses the DONE button, - * the EditText becomes a TextView again. - * This logic was necessary because on API 24, permanently having - * an EditText in the widgetsPage was breaking the drag/drop functionality. + * Adds a listener to the folder title. When clicked, the TextView transforms + * into an EditText. When the user changes the title and presses the DONE + * button, the EditText becomes a TextView again. This logic was necessary + * because on API 24, permanently having an EditText in the widgetsPage was + * breaking the drag/drop functionality. */ private void createFolderTitleListener() { mFolderTitleInput.setOnFocusChangeListener((v, hasFocus) -> { @@ -1183,15 +1140,13 @@ public class LauncherActivity extends AppCompatActivity implements } public void hideKeyboard(View view) { - InputMethodManager inputMethodManager = (InputMethodManager) getSystemService( - Activity.INPUT_METHOD_SERVICE); + InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); assert inputMethodManager != null; inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); } public void showKeyboard(View view) { - InputMethodManager inputMethodManager = (InputMethodManager) getSystemService( - Activity.INPUT_METHOD_SERVICE); + InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE); assert inputMethodManager != null; inputMethodManager.showSoftInput(view, 0); } @@ -1206,8 +1161,8 @@ public class LauncherActivity extends AppCompatActivity implements } /** - * Adds a scroll listener to the mHorizontalPager in order to keep the currentPageNumber - * updated + * Adds a scroll listener to the mHorizontalPager in order to keep the + * currentPageNumber updated */ private void createPageChangeListener() { mHorizontalPager.addOnScrollListener(new HorizontalPager.OnScrollListener() { @@ -1216,8 +1171,10 @@ public class LauncherActivity extends AppCompatActivity implements @Override public void onScroll(int scrollX) { float progress = (float) scrollX / mDeviceProfile.availableWidthPx; - if (progress >= 0.999) progress = 1; - if (progress <= 0.001) progress = 0; + if (progress >= 0.999) + progress = 1; + if (progress <= 0.001) + progress = 0; int dockHeight = mDock.getHeight() + mIndicator.getHeight(); float dockTranslationY = (1 - progress) * dockHeight; mDock.setTranslationY(dockTranslationY); @@ -1245,8 +1202,7 @@ public class LauncherActivity extends AppCompatActivity implements if (currentPageNumber == 0) { refreshSuggestedApps(widgetsPage, forceRefreshSuggestedApps); if (Preferences.weatherRefreshIntervalInMs(LauncherActivity.this) == 0) { - Intent intent = new Intent(LauncherActivity.this, - WeatherUpdateService.class); + Intent intent = new Intent(LauncherActivity.this, WeatherUpdateService.class); intent.setAction(WeatherUpdateService.ACTION_FORCE_UPDATE); startService(intent); } @@ -1280,12 +1236,9 @@ public class LauncherActivity extends AppCompatActivity implements openUsageAccessSettingsTv.setVisibility(GONE); suggestedAppsGridLayout.setVisibility(VISIBLE); - List suggestedApps = usageStats.stream() - .map(UsageStats::getPackageName) + List suggestedApps = usageStats.stream().map(UsageStats::getPackageName) .map(packageName -> AppUtils.createAppItem(this, packageName, new UserHandle())) - .filter(Objects::nonNull) - .limit(4) - .collect(Collectors.toList()); + .filter(Objects::nonNull).limit(4).collect(Collectors.toList()); if (!forceRefresh && suggestedApps.equals(mSuggestedApps)) { // no changes, skip update @@ -1293,8 +1246,7 @@ public class LauncherActivity extends AppCompatActivity implements } suggestedAppsGridLayout.removeAllViews(); - suggestedApps.stream() - .map(this::prepareSuggestedApp) + suggestedApps.stream().map(this::prepareSuggestedApp) .forEach(view -> addAppToGrid(suggestedAppsGridLayout, view)); mSuggestedApps = suggestedApps; @@ -1305,8 +1257,7 @@ public class LauncherActivity extends AppCompatActivity implements /** * Populates the pages and the mDock for the first time. */ - private void createUI( - List launcherItems) { + private void createUI(List launcherItems) { mHorizontalPager.setUiCreated(false); mDock.setEnabled(false); @@ -1350,7 +1301,7 @@ public class LauncherActivity extends AppCompatActivity implements currentPageNumber = 0; mHorizontalPager.setUiCreated(true); - //DatabaseManager.getManager(this).saveLayouts(pages, mDock); + // DatabaseManager.getManager(this).saveLayouts(pages, mDock); mDock.setEnabled(true); setUpSwipeSearchContainer(); } @@ -1360,8 +1311,7 @@ public class LauncherActivity extends AppCompatActivity implements GridLayout grid = (GridLayout) getLayoutInflater().inflate(R.layout.apps_page, null); grid.setRowCount(mDeviceProfile.numRows); grid.setLayoutTransition(getDefaultLayoutTransition()); - grid.setPadding(mDeviceProfile.iconDrawablePaddingPx / 2, - (int) (Utilities.pxFromDp(8, this)), + grid.setPadding(mDeviceProfile.iconDrawablePaddingPx / 2, (int) (Utilities.pxFromDp(8, this)), mDeviceProfile.iconDrawablePaddingPx / 2, 0); // If a user taps outside (background / space) stop wobbling @@ -1373,18 +1323,17 @@ public class LauncherActivity extends AppCompatActivity implements } private void createWidgetsPage() { - widgetsPage = (InsettableFrameLayout) getLayoutInflater().inflate(R.layout.widgets_page, - mHorizontalPager, false); + widgetsPage = (InsettableFrameLayout) getLayoutInflater().inflate(R.layout.widgets_page, mHorizontalPager, + false); widgetContainer = widgetsPage.findViewById(R.id.widget_container); - /*widgetsPage.setPadding(0, - (int) (Utilities.pxFromDp(8, this)), - 0, 0);*/ + /* + * widgetsPage.setPadding(0, (int) (Utilities.pxFromDp(8, this)), 0, 0); + */ mHorizontalPager.addView(widgetsPage, 0); widgetsPage.setOnDragListener(null); ScrollView scrollView = widgetsPage.findViewById(R.id.widgets_scroll_container); scrollView.setOnTouchListener((v, event) -> { - if (widgetsPage.findViewById(R.id.widget_resizer_container).getVisibility() - == VISIBLE) { + if (widgetsPage.findViewById(R.id.widget_resizer_container).getVisibility() == VISIBLE) { hideWidgetResizeContainer(); } return false; @@ -1396,14 +1345,12 @@ public class LauncherActivity extends AppCompatActivity implements // Prepare app suggestions view // [[BEGIN]] - widgetsPage.findViewById(R.id.openUsageAccessSettings).setOnClickListener( - view -> startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS))); + widgetsPage.findViewById(R.id.openUsageAccessSettings) + .setOnClickListener(view -> startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS))); // divided by 2 because of left and right padding. - int padding = - (int) (mDeviceProfile.availableWidthPx / 2 - Utilities.pxFromDp(8, this) - - 2 - * mDeviceProfile.cellWidthPx); + int padding = (int) (mDeviceProfile.availableWidthPx / 2 - Utilities.pxFromDp(8, this) + - 2 * mDeviceProfile.cellWidthPx); widgetsPage.findViewById(R.id.suggestedAppGrid).setPadding(padding, 0, padding, 0); // [[END]] @@ -1438,25 +1385,17 @@ public class LauncherActivity extends AppCompatActivity implements RecyclerView suggestionRecyclerView = widgetsPage.findViewById(R.id.suggestionRecyclerView); AutoCompleteAdapter suggestionAdapter = new AutoCompleteAdapter(this); suggestionRecyclerView.setHasFixedSize(true); - suggestionRecyclerView.setLayoutManager( - new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); + suggestionRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); suggestionRecyclerView.setAdapter(suggestionAdapter); - getCompositeDisposable().add(RxTextView.textChanges(mSearchInput) - .debounce(300, TimeUnit.MILLISECONDS) - .map(CharSequence::toString) - .distinctUntilChanged() - .switchMap(charSequence -> { + getCompositeDisposable().add(RxTextView.textChanges(mSearchInput).debounce(300, TimeUnit.MILLISECONDS) + .map(CharSequence::toString).distinctUntilChanged().switchMap(charSequence -> { if (charSequence != null && charSequence.length() > 0) { return searchForQuery(charSequence); } else { - return Observable.just( - new SuggestionsResult(charSequence)); + return Observable.just(new SuggestionsResult(charSequence)); } - }) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeWith( - new SearchInputDisposableObserver(this, suggestionAdapter, widgetsPage))); + }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) + .subscribeWith(new SearchInputDisposableObserver(this, suggestionAdapter, widgetsPage))); mSearchInput.setOnFocusChangeListener((v, hasFocus) -> { if (!hasFocus) { @@ -1477,24 +1416,21 @@ public class LauncherActivity extends AppCompatActivity implements // [[END]] // Prepare edit widgets button - findViewById(R.id.edit_widgets_button).setOnClickListener( - view -> startActivity(new Intent(this, WidgetsActivity.class))); + findViewById(R.id.edit_widgets_button) + .setOnClickListener(view -> startActivity(new Intent(this, WidgetsActivity.class))); if (WeatherUtils.isWeatherServiceAvailable(this)) { startService(new Intent(this, WeatherSourceListenerService.class)); startService(new Intent(this, DeviceStatusService.class)); } - if (!Preferences.useCustomWeatherLocation(this)) { if (!WeatherPreferences.hasLocationPermission(this)) { String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION}; - requestPermissions(permissions, - WeatherPreferences.LOCATION_PERMISSION_REQUEST_CODE); + requestPermissions(permissions, WeatherPreferences.LOCATION_PERMISSION_REQUEST_CODE); } else { LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); - if (!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER) - && Preferences.getEnableLocation(this)) { + if (!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER) && Preferences.getEnableLocation(this)) { showLocationEnableDialog(); Preferences.setEnableLocation(this); } else { @@ -1503,30 +1439,30 @@ public class LauncherActivity extends AppCompatActivity implements } } } else { - startService(new Intent(this, WeatherUpdateService.class) - .setAction(WeatherUpdateService.ACTION_FORCE_UPDATE)); + startService( + new Intent(this, WeatherUpdateService.class).setAction(WeatherUpdateService.ACTION_FORCE_UPDATE)); } // [[END]] int[] widgetIds = mAppWidgetHost.getAppWidgetIds(); getCompositeDisposable().add(DatabaseManager.getManager(this).getWidgets(widgetIds) .subscribeOn(Schedulers.from(AppExecutors.getInstance().diskIO())) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(this::bindWidgets)); + .observeOn(AndroidSchedulers.mainThread()).subscribe(this::bindWidgets)); } private void bindWidgets(List widgets) { for (WidgetItem widget : widgets) { AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(widget.id); - if (appWidgetInfo == null) continue; + if (appWidgetInfo == null) + continue; - RoundedWidgetView hostView = (RoundedWidgetView) mAppWidgetHost.createView( - getApplicationContext(), widget.id, - appWidgetInfo); + RoundedWidgetView hostView = (RoundedWidgetView) mAppWidgetHost.createView(getApplicationContext(), + widget.id, appWidgetInfo); hostView.setAppWidget(widget.id, appWidgetInfo); RoundedWidgetView widgetView = WidgetViewBuilder.create(this, hostView); - if (widgetView == null) continue; + if (widgetView == null) + continue; if (widget.height != 0) { int minHeight = hostView.getAppWidgetInfo().minResizeHeight; int maxHeight = mDeviceProfile.availableHeightPx * 3 / 4; @@ -1539,10 +1475,9 @@ public class LauncherActivity extends AppCompatActivity implements @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, - @NonNull int[] grantResults) { + @NonNull int[] grantResults) { if (requestCode == WeatherPreferences.LOCATION_PERMISSION_REQUEST_CODE) { - if (grantResults.length > 0 - && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // We only get here if user tried to enable the preference, // hence safe to turn it on after permission is granted LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); @@ -1555,8 +1490,7 @@ public class LauncherActivity extends AppCompatActivity implements } } } else if (requestCode == STORAGE_PERMISSION_REQUEST_CODE) { - if (grantResults.length > 0 - && grantResults[0] == PackageManager.PERMISSION_GRANTED) { + if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { BlurWallpaperProvider.Companion.getInstance(getApplicationContext()).updateAsync(); } } @@ -1568,13 +1502,11 @@ public class LauncherActivity extends AppCompatActivity implements builder.setTitle(R.string.weather_retrieve_location_dialog_title); builder.setMessage(R.string.weather_retrieve_location_dialog_message); builder.setCancelable(false); - builder.setPositiveButton(R.string.weather_retrieve_location_dialog_enable_button, - (dialog1, whichButton) -> { - Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); - intent.setFlags( - Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); - startActivityForResult(intent, REQUEST_LOCATION_SOURCE_SETTING); - }); + builder.setPositiveButton(R.string.weather_retrieve_location_dialog_enable_button, (dialog1, whichButton) -> { + Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); + intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); + startActivityForResult(intent, REQUEST_LOCATION_SOURCE_SETTING); + }); builder.setNegativeButton(R.string.cancel, null); enableLocationDialog = builder.create(); enableLocationDialog.show(); @@ -1585,8 +1517,7 @@ public class LauncherActivity extends AppCompatActivity implements if (requestCode == REQUEST_LOCATION_SOURCE_SETTING) { LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { - Toast.makeText(this, getString(R.string.toast_custom_location), - Toast.LENGTH_SHORT).show(); + Toast.makeText(this, getString(R.string.toast_custom_location), Toast.LENGTH_SHORT).show(); } else { startService(new Intent(this, WeatherUpdateService.class) .setAction(WeatherUpdateService.ACTION_FORCE_UPDATE)); @@ -1596,20 +1527,16 @@ public class LauncherActivity extends AppCompatActivity implements } } - private ObservableSource searchForQuery( - CharSequence charSequence) { - Observable launcherItems = searchForLauncherItems( - charSequence.toString()).subscribeOn(Schedulers.io()); - Observable networkItems = searchForNetworkItems( - charSequence).subscribeOn(Schedulers.io()); + private ObservableSource searchForQuery(CharSequence charSequence) { + Observable launcherItems = searchForLauncherItems(charSequence.toString()) + .subscribeOn(Schedulers.io()); + Observable networkItems = searchForNetworkItems(charSequence).subscribeOn(Schedulers.io()); return launcherItems.mergeWith(networkItems); } - private Observable searchForLauncherItems( - CharSequence charSequence) { + private Observable searchForLauncherItems(CharSequence charSequence) { String query = Utilities.stripCaseAndAccents(charSequence.toString()); - SuggestionsResult suggestionsResult = new SuggestionsResult( - query); + SuggestionsResult suggestionsResult = new SuggestionsResult(query); List launcherItems = new ArrayList<>(); pages.parallelStream().forEach(gridLayout -> { for (int i = 0; i < gridLayout.getChildCount(); i++) { @@ -1643,26 +1570,23 @@ public class LauncherActivity extends AppCompatActivity implements } } - launcherItems.sort(Comparator.comparing(launcherItem -> - launcherItem.title.toString().toLowerCase().indexOf(query) - )); + launcherItems + .sort(Comparator.comparing(launcherItem -> launcherItem.title.toString().toLowerCase().indexOf(query))); if (launcherItems.size() > 4) { suggestionsResult.setLauncherItems(launcherItems.subList(0, 4)); } else { suggestionsResult.setLauncherItems(launcherItems); } - return Observable.just(suggestionsResult) - .onErrorReturn(throwable -> { - suggestionsResult.setLauncherItems(new ArrayList<>()); - return suggestionsResult; - }); + return Observable.just(suggestionsResult).onErrorReturn(throwable -> { + suggestionsResult.setLauncherItems(new ArrayList<>()); + return suggestionsResult; + }); } private Observable searchForNetworkItems(CharSequence charSequence) { String query = charSequence.toString().toLowerCase(Locale.getDefault()).trim(); - SuggestionProvider suggestionProvider = new SearchSuggestionUtil().getSuggestionProvider( - this); + SuggestionProvider suggestionProvider = new SearchSuggestionUtil().getSuggestionProvider(this); return suggestionProvider.query(query).toObservable(); } @@ -1675,8 +1599,7 @@ public class LauncherActivity extends AppCompatActivity implements } private void runSearch(String query) { - Intent intent = new Intent(Intent.ACTION_VIEW, - new SearchSuggestionUtil().getUriForQuery(this, query)); + Intent intent = new Intent(Intent.ACTION_VIEW, new SearchSuggestionUtil().getUriForQuery(this, query)); startActivity(intent); } @@ -1697,18 +1620,17 @@ public class LauncherActivity extends AppCompatActivity implements view.findViewById(R.id.app_label).setVisibility(View.VISIBLE); view.setLayoutParams(iconLayoutParams); view.setWithText(true); - if (index == EMPTY_LOCATION_DRAG || index == LauncherItem.INVALID_CELL - || index > page.getChildCount()) { + if (index == EMPTY_LOCATION_DRAG || index == LauncherItem.INVALID_CELL || index > page.getChildCount()) { page.addView(view); } else { page.addView(view, index); } - //DatabaseManager.getManager(this).saveLayouts(pages, mDock); + // DatabaseManager.getManager(this).saveLayouts(pages, mDock); } /** - * Adds networkItems to the mDock making sure that the GridLayout's parameters are - * not violated. + * Adds networkItems to the mDock making sure that the GridLayout's parameters + * are not violated. */ private void addAppToDock(BlissFrameLayout view, int index) { view.findViewById(R.id.app_label).setVisibility(GONE); @@ -1720,8 +1642,7 @@ public class LauncherActivity extends AppCompatActivity implements iconLayoutParams.setGravity(Gravity.CENTER); view.setLayoutParams(iconLayoutParams); view.setWithText(false); - if (index == LauncherItem.INVALID_CELL || index == EMPTY_LOCATION_DRAG - || index > mDock.getChildCount()) { + if (index == LauncherItem.INVALID_CELL || index == EMPTY_LOCATION_DRAG || index > mDock.getChildCount()) { mDock.addView(view); } else { mDock.addView(view, index); @@ -1729,16 +1650,14 @@ public class LauncherActivity extends AppCompatActivity implements } /** - * Converts an AppItem into a View object that can be rendered inside - * the pages and the mDock. + * Converts an AppItem into a View object that can be rendered inside the pages + * and the mDock. *

* The View object also has all the required listeners attached to it. */ @SuppressLint({"InflateParams", "ClickableViewAccessibility"}) private BlissFrameLayout prepareLauncherItem(final LauncherItem launcherItem) { - final BlissFrameLayout iconView = (BlissFrameLayout) getLayoutInflater().inflate( - R.layout.app_view, - null); + final BlissFrameLayout iconView = (BlissFrameLayout) getLayoutInflater().inflate(R.layout.app_view, null); iconView.setLauncherItem(launcherItem); final SquareFrameLayout icon = iconView.findViewById(R.id.app_icon); if (launcherItem.itemType == Constants.ITEM_TYPE_FOLDER) { @@ -1770,12 +1689,10 @@ public class LauncherActivity extends AppCompatActivity implements iconPressedAt = System.currentTimeMillis(); } } else if (event.getActionMasked() == MotionEvent.ACTION_MOVE) { - if (longPressed || (!mLongClickStartsDrag - && (System.currentTimeMillis() - iconPressedAt) > 150)) { + if (longPressed || (!mLongClickStartsDrag && (System.currentTimeMillis() - iconPressedAt) > 150)) { longPressed = false; movingApp = iconView; - dragShadowBuilder = new BlissDragShadowBuilder( - icon, (event.getX() < 0 ? 0 : event.getX()), + dragShadowBuilder = new BlissDragShadowBuilder(icon, (event.getX() < 0 ? 0 : event.getX()), (event.getY() < 0 ? 0 : event.getY())); icon.startDragAndDrop(null, dragShadowBuilder, iconView, 0); if (iconView.getParent().getParent() instanceof HorizontalPager) { @@ -1818,15 +1735,12 @@ public class LauncherActivity extends AppCompatActivity implements } public BlissFrameLayout prepareSuggestedApp(final LauncherItem launcherItem) { - final BlissFrameLayout v = (BlissFrameLayout) getLayoutInflater().inflate( - R.layout.app_view, - null); + final BlissFrameLayout v = (BlissFrameLayout) getLayoutInflater().inflate(R.layout.app_view, null); v.setLauncherItem(launcherItem); final SquareFrameLayout icon = v.findViewById(R.id.app_icon); if (launcherItem.itemType == Constants.ITEM_TYPE_APPLICATION) { - v.applyBadge(mAppsWithNotifications.contains( - ((ApplicationItem) launcherItem).packageName), true); + v.applyBadge(mAppsWithNotifications.contains(((ApplicationItem) launcherItem).packageName), true); } icon.setOnClickListener(view -> startActivitySafely(this, launcherItem, view)); return v; @@ -1851,8 +1765,8 @@ public class LauncherActivity extends AppCompatActivity implements if (user == null || user.equals(Process.myUserHandle())) { context.startActivity(intent); } else { - ((LauncherApps) getSystemService(LAUNCHER_APPS_SERVICE)) - .startMainActivity(intent.getComponent(), user, intent.getSourceBounds(), null); + ((LauncherApps) getSystemService(LAUNCHER_APPS_SERVICE)).startMainActivity(intent.getComponent(), + user, intent.getSourceBounds(), null); } } } @@ -1866,16 +1780,14 @@ public class LauncherActivity extends AppCompatActivity implements // Temporarily disable deathPenalty on all default checks. For eg, shortcuts // containing file Uri's would cause a crash as penaltyDeathOnFileUriExposure // is enabled by default on NYC. - StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll() - .penaltyLog().build()); + StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build()); if (appItem.itemType == Constants.ITEM_TYPE_SHORTCUT) { if (Utilities.ATLEAST_OREO) { String id = appItem.id; String packageName = intent.getPackage(); - DeepShortcutManager.getInstance(context).startShortcut( - packageName, id, intent.getSourceBounds(), null, - Process.myUserHandle()); + DeepShortcutManager.getInstance(context).startShortcut(packageName, id, + intent.getSourceBounds(), null, Process.myUserHandle()); } else { context.startActivity(intent); } @@ -1891,12 +1803,9 @@ public class LauncherActivity extends AppCompatActivity implements // Due to legacy reasons, direct call shortcuts require Launchers to have the // corresponding permission. Show the appropriate permission prompt if that // is the case. - if (intent.getComponent() == null - && Intent.ACTION_CALL.equals(intent.getAction()) - && context.checkSelfPermission(Manifest.permission.CALL_PHONE) != - PackageManager.PERMISSION_GRANTED) { - requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, - REQUEST_PERMISSION_CALL_PHONE); + if (intent.getComponent() == null && Intent.ACTION_CALL.equals(intent.getAction()) && context + .checkSelfPermission(Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) { + requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, REQUEST_PERMISSION_CALL_PHONE); } else { // No idea why this was thrown. throw e; @@ -1943,20 +1852,17 @@ public class LauncherActivity extends AppCompatActivity implements } } - private void makeAppWobble(BlissFrameLayout blissFrameLayout, boolean shouldPlayAnimation, - int i) { + private void makeAppWobble(BlissFrameLayout blissFrameLayout, boolean shouldPlayAnimation, int i) { UserManager userManager = (UserManager) getSystemService(Context.USER_SERVICE); Bundle restrictions = userManager.getUserRestrictions(); - boolean uninstallDisabled = restrictions.getBoolean(UserManager.DISALLOW_APPS_CONTROL, - false) + boolean uninstallDisabled = restrictions.getBoolean(UserManager.DISALLOW_APPS_CONTROL, false) || restrictions.getBoolean(UserManager.DISALLOW_UNINSTALL_APPS, false); if (shouldPlayAnimation) { if (blissFrameLayout.getAnimation() == null) { ImageView imageView = blissFrameLayout.findViewById(R.id.uninstall_app); if (imageView == null) { if (!uninstallDisabled) { - new Handler(Looper.getMainLooper()).post( - () -> addUninstallIcon(blissFrameLayout)); + new Handler(Looper.getMainLooper()).post(() -> addUninstallIcon(blissFrameLayout)); } } @@ -1968,8 +1874,7 @@ public class LauncherActivity extends AppCompatActivity implements } } else { blissFrameLayout.clearAnimation(); - new Handler(Looper.getMainLooper()).post( - () -> removeUninstallIcon(blissFrameLayout)); + new Handler(Looper.getMainLooper()).post(() -> removeUninstallIcon(blissFrameLayout)); } } @@ -2001,14 +1906,16 @@ public class LauncherActivity extends AppCompatActivity implements SquareFrameLayout appIcon = blissFrameLayout.findViewById(R.id.app_icon); int size = mDeviceProfile.uninstallIconSizePx; int topPadding = (appIcon.getTop() - mDeviceProfile.uninstallIconSizePx / 2 - + mDeviceProfile.uninstallIconPadding > 0) ? - appIcon.getTop() - mDeviceProfile.uninstallIconSizePx / 2 - + mDeviceProfile.uninstallIconPadding : 0; + + mDeviceProfile.uninstallIconPadding > 0) + ? appIcon.getTop() - mDeviceProfile.uninstallIconSizePx / 2 + + mDeviceProfile.uninstallIconPadding + : 0; int bottomPadding = topPadding; int rightPadding = (appIcon.getLeft() - mDeviceProfile.uninstallIconSizePx / 2 - + mDeviceProfile.uninstallIconPadding > 0) ? - appIcon.getLeft() - mDeviceProfile.uninstallIconSizePx / 2 - + mDeviceProfile.uninstallIconPadding : 0; + + mDeviceProfile.uninstallIconPadding > 0) + ? appIcon.getLeft() - mDeviceProfile.uninstallIconSizePx / 2 + + mDeviceProfile.uninstallIconPadding + : 0; int leftPadding = rightPadding; ImageView imageView = new ImageView(this); @@ -2027,14 +1934,13 @@ public class LauncherActivity extends AppCompatActivity implements } else { Uri packageUri = Uri.fromParts("package", componentName.getPackageName(), componentName.getClassName()); - Intent i = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageUri) - .putExtra(Intent.EXTRA_USER, launcherItem.user.getRealHandle()); + Intent i = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageUri).putExtra(Intent.EXTRA_USER, + launcherItem.user.getRealHandle()); startActivity(i); } } else if (launcherItem.itemType == Constants.ITEM_TYPE_SHORTCUT) { AlertDialog dialog = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.AlertDialogCustom)) - .setTitle(launcherItem.title) - .setMessage(R.string.uninstall_shortcut_dialog) + .setTitle(launcherItem.title).setMessage(R.string.uninstall_shortcut_dialog) .setPositiveButton(R.string.ok, (dialog1, which) -> { ShortcutItem shortcut = (ShortcutItem) launcherItem; if (shortcut.packageName != null) { @@ -2044,24 +1950,24 @@ public class LauncherActivity extends AppCompatActivity implements removeShortcutView(shortcut, blissFrameLayout); } } else { - // Null package name generally comes for nougat shortcuts so don't unpin here, just directly delete it. + // Null package name generally comes for nougat shortcuts so don't unpin here, + // just directly delete it. deleteShortcutFromProvider(shortcut.id); removeShortcutView(shortcut, blissFrameLayout); } - }) - .setNegativeButton(R.string.cancel, null) - .setIcon(launcherItem.icon) - .create(); + }).setNegativeButton(R.string.cancel, null).setIcon(launcherItem.icon).create(); dialog.setOnShowListener(arg0 -> { - dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.color_blue)); - dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.color_blue)); + dialog.getButton(AlertDialog.BUTTON_POSITIVE) + .setTextColor(getResources().getColor(R.color.color_blue)); + dialog.getButton(AlertDialog.BUTTON_NEGATIVE) + .setTextColor(getResources().getColor(R.color.color_blue)); }); dialog.show(); } }); - FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams( - size + 2 * rightPadding, size + 2 * topPadding); + FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(size + 2 * rightPadding, + size + 2 * topPadding); layoutParams.gravity = Gravity.END | Gravity.TOP; blissFrameLayout.addView(imageView, layoutParams); } @@ -2080,8 +1986,7 @@ public class LauncherActivity extends AppCompatActivity implements blissFrameLayout.clearAnimation(); ((ViewGroup) blissFrameLayout.getParent()).removeView(blissFrameLayout); if (activeFolder.items.size() == 0) { - ((ViewGroup) activeFolderView.getParent()).removeView - (activeFolderView); + ((ViewGroup) activeFolderView.getParent()).removeView(activeFolderView); hideFolderWindowContainer(); } else if (activeFolder.items.size() == 1) { LauncherItem item = activeFolder.items.get(0); @@ -2092,19 +1997,15 @@ public class LauncherActivity extends AppCompatActivity implements if (folderFromDock) { addAppToDock(view, mDock.indexOfChild(activeFolderView)); } else { - GridLayout gridLayout = pages.get - (getCurrentAppsPageNumber()); - addAppToGrid(gridLayout, view, - gridLayout.indexOfChild(activeFolderView)); + GridLayout gridLayout = pages.get(getCurrentAppsPageNumber()); + addAppToGrid(gridLayout, view, gridLayout.indexOfChild(activeFolderView)); } activeFolderView.clearAnimation(); - ((ViewGroup) activeFolderView.getParent()).removeView( - activeFolderView); + ((ViewGroup) activeFolderView.getParent()).removeView(activeFolderView); hideFolderWindowContainer(); } else { updateIcon(activeFolderView, activeFolder, - new GraphicsUtil(this).generateFolderIcon(this, activeFolder), - folderFromDock); + new GraphicsUtil(this).generateFolderIcon(this, activeFolder), folderFromDock); hideFolderWindowContainer(); } } else { @@ -2114,12 +2015,15 @@ public class LauncherActivity extends AppCompatActivity implements } /** - * Creates drag listeners for the mDock and pages, which are responsible for almost - * all the drag and drop functionality present in this app. + * Creates drag listeners for the mDock and pages, which are responsible for + * almost all the drag and drop functionality present in this app. */ private void createDragListener() { - /*mHorizontalPager.setOnDragListener(new SystemDragDriver(workspaceEventListener)); - mDock.setOnDragListener(new SystemDragDriver(dockEventListener));*/ + /* + * mHorizontalPager.setOnDragListener(new + * SystemDragDriver(workspaceEventListener)); mDock.setOnDragListener(new + * SystemDragDriver(dockEventListener)); + */ mDock.setOnDragListener(new View.OnDragListener() { public float cX; public float cY; @@ -2162,13 +2066,11 @@ public class LauncherActivity extends AppCompatActivity implements if (index == EMPTY_LOCATION_DRAG) { discardCollidingApp(); } else { - BlissFrameLayout latestCollidingApp = - (BlissFrameLayout) mDock.getChildAt(index); + BlissFrameLayout latestCollidingApp = (BlissFrameLayout) mDock.getChildAt(index); if (collidingApp != latestCollidingApp) { if (collidingApp != null) { makeAppCold(collidingApp, - !(collidingApp.getParent().getParent() instanceof - HorizontalPager)); + !(collidingApp.getParent().getParent() instanceof HorizontalPager)); } collidingApp = latestCollidingApp; folderInterest = false; @@ -2188,15 +2090,13 @@ public class LauncherActivity extends AppCompatActivity implements makeAppHot(collidingApp); } else { View app = collidingApp; - makeAppCold(app, - !(app.getParent().getParent() instanceof HorizontalPager)); + makeAppCold(app, !(app.getParent().getParent() instanceof HorizontalPager)); } } } if (!folderInterest && !mDockReorderAlarm.alarmPending()) { - DockReorderAlarmListener dockReorderAlarmListener = - new DockReorderAlarmListener(index); + DockReorderAlarmListener dockReorderAlarmListener = new DockReorderAlarmListener(index); mDockReorderAlarm.setOnAlarmListener(dockReorderAlarmListener); mDockReorderAlarm.setAlarm(REORDER_TIMEOUT); } @@ -2210,8 +2110,7 @@ public class LauncherActivity extends AppCompatActivity implements if (!folderInterest) { if (movingApp.getParent() == null) { if (mDock.getChildCount() >= mDeviceProfile.numColumns) { - Toast.makeText(LauncherActivity.this, - getString(R.string.toast_dock_full), + Toast.makeText(LauncherActivity.this, getString(R.string.toast_dock_full), Toast.LENGTH_SHORT).show(); } else { addAppToDock(movingApp, EMPTY_LOCATION_DRAG); @@ -2238,15 +2137,13 @@ public class LauncherActivity extends AppCompatActivity implements int right = left + mFolderAppsViewPager.getWidth(); int bottom = top + mFolderAppsViewPager.getHeight(); - if (!(left < right && top < bottom && cX >= left - && cX < right && cY >= top && cY < bottom)) { + if (!(left < right && top < bottom && cX >= left && cX < right && cY >= top && cY < bottom)) { removeAppFromFolder(); } else { movingApp.setVisibility(View.VISIBLE); int currentItem = mFolderAppsViewPager.getCurrentItem(); - makeAppWobble(movingApp, true, - ((GridLayout) mFolderAppsViewPager.getChildAt( - currentItem)).indexOfChild(movingApp)); + makeAppWobble(movingApp, true, ((GridLayout) mFolderAppsViewPager.getChildAt(currentItem)) + .indexOfChild(movingApp)); } } return true; @@ -2270,8 +2167,7 @@ public class LauncherActivity extends AppCompatActivity implements } } else if (dragEvent.getAction() == DragEvent.ACTION_DRAG_LOCATION) { cX = dragEvent.getX() - dragShadowBuilder.xOffset; - cY = mHorizontalPager.getY() + dragEvent.getY() - - dragShadowBuilder.yOffset; + cY = mHorizontalPager.getY() + dragEvent.getY() - dragShadowBuilder.yOffset; // Don't offer rearrange functionality when app is being dragged // out of folder window @@ -2297,11 +2193,8 @@ public class LauncherActivity extends AppCompatActivity implements ImageView dot = new ImageView(LauncherActivity.this); dot.setImageDrawable(getDrawable(R.drawable.dot_off)); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( - getResources().getDimensionPixelSize( - R.dimen.dotSize), - getResources().getDimensionPixelSize( - R.dimen.dotSize) - ); + getResources().getDimensionPixelSize(R.dimen.dotSize), + getResources().getDimensionPixelSize(R.dimen.dotSize)); dot.setLayoutParams(params); mIndicator.addView(dot); mHorizontalPager.addView(layout); @@ -2313,8 +2206,7 @@ public class LauncherActivity extends AppCompatActivity implements if (getCurrentAppsPageNumber() - 1 >= 0) { mHorizontalPager.scrollLeft(300); } else if (getCurrentAppsPageNumber() + 1 == pages.size() - 2 - && getGridFromPage(pages.get(pages.size() - 1)).getChildCount() - <= 0) { + && getGridFromPage(pages.get(pages.size() - 1)).getChildCount() <= 0) { mIndicator.removeViewAt(pages.size()); mHorizontalPager.removeViewAt(pages.size()); pages.remove(pages.size() - 1); @@ -2336,8 +2228,7 @@ public class LauncherActivity extends AppCompatActivity implements if (collidingApp != latestCollidingApp) { if (collidingApp != null) { makeAppCold(collidingApp, - !(collidingApp.getParent().getParent() instanceof - HorizontalPager)); + !(collidingApp.getParent().getParent() instanceof HorizontalPager)); } collidingApp = (BlissFrameLayout) latestCollidingApp; folderInterest = false; @@ -2347,8 +2238,7 @@ public class LauncherActivity extends AppCompatActivity implements folderInterest = false; } else { latestFolderInterest = checkIfFolderInterest( - getGridFromPage(pages.get(getCurrentAppsPageNumber())), - index, cX, cY); + getGridFromPage(pages.get(getCurrentAppsPageNumber())), index, cX, cY); if (latestFolderInterest != folderInterest) { folderInterest = latestFolderInterest; @@ -2359,15 +2249,14 @@ public class LauncherActivity extends AppCompatActivity implements makeAppHot(collidingApp); } else { makeAppCold(collidingApp, - !(collidingApp.getParent().getParent() instanceof - HorizontalPager)); + !(collidingApp.getParent().getParent() instanceof HorizontalPager)); } } } if (!folderInterest && !mReorderAlarm.alarmPending()) { - ReorderAlarmListener reorderAlarmListener = new ReorderAlarmListener( - page, (ViewGroup) movingApp.getParent(), index); + ReorderAlarmListener reorderAlarmListener = new ReorderAlarmListener(page, + (ViewGroup) movingApp.getParent(), index); mReorderAlarm.setOnAlarmListener(reorderAlarmListener); mReorderAlarm.setAlarm(REORDER_TIMEOUT); } @@ -2381,8 +2270,7 @@ public class LauncherActivity extends AppCompatActivity implements GridLayout gridLayout = pages.get(getCurrentAppsPageNumber()); if (!folderInterest) { if (movingApp.getParent() == null) { - if (gridLayout.getChildCount() - < mDeviceProfile.maxAppsPerPage) { + if (gridLayout.getChildCount() < mDeviceProfile.maxAppsPerPage) { addAppToGrid(gridLayout, movingApp); } } @@ -2399,8 +2287,7 @@ public class LauncherActivity extends AppCompatActivity implements } } else { cX = dragEvent.getX() - dragShadowBuilder.xOffset; - cY = mHorizontalPager.getY() + dragEvent.getY() - - dragShadowBuilder.yOffset; + cY = mHorizontalPager.getY() + dragEvent.getY() - dragShadowBuilder.yOffset; // Drop functionality when the folder window is visible int[] topLeftCorner = new int[2]; @@ -2410,17 +2297,14 @@ public class LauncherActivity extends AppCompatActivity implements int right = left + mFolderAppsViewPager.getWidth(); int bottom = top + mFolderAppsViewPager.getHeight(); - if (!(left < right && top < bottom && cX >= left - && cX < right && cY >= top && cY < bottom)) { + if (!(left < right && top < bottom && cX >= left && cX < right && cY >= top && cY < bottom)) { removeAppFromFolder(); } else { movingApp.setVisibility(View.VISIBLE); int currentItem = mFolderAppsViewPager.getCurrentItem(); - GridLayout gridLayout = (GridLayout) mFolderAppsViewPager.getChildAt( - currentItem); + GridLayout gridLayout = (GridLayout) mFolderAppsViewPager.getChildAt(currentItem); if (gridLayout != null) { - makeAppWobble(movingApp, true, - gridLayout.indexOfChild(movingApp)); + makeAppWobble(movingApp, true, gridLayout.indexOfChild(movingApp)); } } } @@ -2435,13 +2319,11 @@ public class LauncherActivity extends AppCompatActivity implements if (!dragEvent.getResult()) { if (mFolderWindowContainer.getVisibility() == View.VISIBLE) { int currentItem = mFolderAppsViewPager.getCurrentItem(); - makeAppWobble(movingApp, true, - ((GridLayout) mFolderAppsViewPager.getChildAt( - currentItem)).indexOfChild(movingApp)); + makeAppWobble(movingApp, true, ((GridLayout) mFolderAppsViewPager.getChildAt(currentItem)) + .indexOfChild(movingApp)); } else if (movingApp.getParent().getParent() instanceof HorizontalPager) { GridLayout gridLayout = pages.get(getCurrentAppsPageNumber()); - makeAppWobble(movingApp, true, - gridLayout.indexOfChild(movingApp)); + makeAppWobble(movingApp, true, gridLayout.indexOfChild(movingApp)); } else { makeAppWobble(movingApp, true, mDock.indexOfChild(movingApp)); } @@ -2505,21 +2387,18 @@ public class LauncherActivity extends AppCompatActivity implements * Remove app from the folder by dragging out of the folder view. */ private void removeAppFromFolder() { - if (pages.get(getCurrentAppsPageNumber()).getChildCount() - >= mDeviceProfile.maxAppsPerPage) { + if (pages.get(getCurrentAppsPageNumber()).getChildCount() >= mDeviceProfile.maxAppsPerPage) { Toast.makeText(this, getString(R.string.toast_no_room), Toast.LENGTH_SHORT).show(); movingApp.setVisibility(View.VISIBLE); int currentItem = mFolderAppsViewPager.getCurrentItem(); makeAppWobble(movingApp, true, - ((GridLayout) mFolderAppsViewPager.getChildAt( - currentItem)).indexOfChild(movingApp)); + ((GridLayout) mFolderAppsViewPager.getChildAt(currentItem)).indexOfChild(movingApp)); } else { LauncherItem app = getAppDetails(movingApp); activeFolder.items.remove(app); mFolderAppsViewPager.getAdapter().notifyDataSetChanged(); assert app != null; - app.container = - folderFromDock ? Constants.CONTAINER_HOTSEAT : Constants.CONTAINER_DESKTOP; + app.container = folderFromDock ? Constants.CONTAINER_HOTSEAT : Constants.CONTAINER_DESKTOP; app.screenId = folderFromDock ? -1 : currentPageNumber; if (activeFolder.items.size() == 0) { @@ -2545,9 +2424,7 @@ public class LauncherActivity extends AppCompatActivity implements LauncherItem item = activeFolder.items.get(0); activeFolder.items.remove(item); mFolderAppsViewPager.getAdapter().notifyDataSetChanged(); - item.container = - folderFromDock ? Constants.CONTAINER_HOTSEAT - : Constants.CONTAINER_DESKTOP; + item.container = folderFromDock ? Constants.CONTAINER_HOTSEAT : Constants.CONTAINER_DESKTOP; item.screenId = folderFromDock ? -1 : currentPageNumber; BlissFrameLayout view = prepareLauncherItem(item); if (folderFromDock) { @@ -2569,10 +2446,8 @@ public class LauncherActivity extends AppCompatActivity implements DatabaseManager.getManager(this).removeLauncherItem(activeFolder.id); } else { updateIcon(activeFolderView, activeFolder, - new GraphicsUtil(this).generateFolderIcon(this, activeFolder), - folderFromDock); - activeFolderView.applyBadge(checkHasApp(activeFolder, mAppsWithNotifications), - !folderFromDock); + new GraphicsUtil(this).generateFolderIcon(this, activeFolder), folderFromDock); + activeFolderView.applyBadge(checkHasApp(activeFolder, mAppsWithNotifications), !folderFromDock); } if (movingApp.getParent() != null) { ((ViewGroup) movingApp.getParent()).removeView(movingApp); @@ -2589,20 +2464,20 @@ public class LauncherActivity extends AppCompatActivity implements } /** - * Returns an app to normal if the user doesn't express move/folder-creation interests. + * Returns an app to normal if the user doesn't express move/folder-creation + * interests. */ private void discardCollidingApp() { if (collidingApp != null) { - makeAppCold(collidingApp, - !(collidingApp.getParent().getParent() instanceof HorizontalPager)); + makeAppCold(collidingApp, !(collidingApp.getParent().getParent() instanceof HorizontalPager)); collidingApp = null; folderInterest = false; } } /** - * Creates/updates a folder using the tags associated with the app being dragged, - * and the target app. + * Creates/updates a folder using the tags associated with the app being + * dragged, and the target app. */ private void createOrUpdateFolder(boolean fromDock) { int index; @@ -2612,8 +2487,7 @@ public class LauncherActivity extends AppCompatActivity implements if (fromDock) { index = mDock.indexOfChild(collidingApp); } else { - index = getGridFromPage(pages.get(getCurrentAppsPageNumber())).indexOfChild( - collidingApp); + index = getGridFromPage(pages.get(getCurrentAppsPageNumber())).indexOfChild(collidingApp); } LauncherItem app1 = getAppDetails(collidingApp); @@ -2625,12 +2499,9 @@ public class LauncherActivity extends AppCompatActivity implements app2.screenId = -1; app2.cell = folderItem.items.size(); folderItem.items.add(app2); - updateIcon(collidingApp, app1, - new GraphicsUtil(this).generateFolderIcon(this, folderItem), - folderFromDock); + updateIcon(collidingApp, app1, new GraphicsUtil(this).generateFolderIcon(this, folderItem), folderFromDock); collidingApp.applyBadge(checkHasApp(folderItem, mAppsWithNotifications), !fromDock); - makeAppWobble(collidingApp, true, - index); + makeAppWobble(collidingApp, true, index); } else { FolderItem folder = new FolderItem(); folder.title = getString(R.string.untitled); @@ -2644,8 +2515,7 @@ public class LauncherActivity extends AppCompatActivity implements folder.items.add(app1); app2.cell = folder.items.size(); folder.items.add(app2); - Drawable folderIcon = new GraphicsUtil(this).generateFolderIcon(this, - app1.icon, app2.icon); + Drawable folderIcon = new GraphicsUtil(this).generateFolderIcon(this, app1.icon, app2.icon); folder.icon = folderIcon; BlissFrameLayout folderView = prepareLauncherItem(folder); makeAppWobble(collidingApp, false, index); @@ -2665,16 +2535,16 @@ public class LauncherActivity extends AppCompatActivity implements makeAppCold(collidingApp, fromDock); makeAppCold(movingApp, fromDock); - //DatabaseManager.getManager(LauncherActivity.this).saveLayouts(pages, mDock); + // DatabaseManager.getManager(LauncherActivity.this).saveLayouts(pages, mDock); } - private void updateIcon(BlissFrameLayout appView, LauncherItem app, Drawable drawable, - boolean folderFromDock) { + private void updateIcon(BlissFrameLayout appView, LauncherItem app, Drawable drawable, boolean folderFromDock) { app.icon = drawable; List tags = (List) appView.getTag(); SquareImageView iv = (SquareImageView) tags.get(0); iv.setImageDrawable(drawable); - //appView.applyBadge(checkHasApp(app, mAppsWithNotifications), !folderFromDock); + // appView.applyBadge(checkHasApp(app, mAppsWithNotifications), + // !folderFromDock); } /** @@ -2718,8 +2588,8 @@ public class LauncherActivity extends AppCompatActivity implements } /** - * Checks if the user wants to create a folder based on the distance - * between the dragged app and the dragged-over app + * Checks if the user wants to create a folder based on the distance between the + * dragged app and the dragged-over app */ private boolean checkIfFolderInterest(ViewGroup view, int index, float x, float y) { View v = view.getChildAt(index).findViewById(R.id.app_icon); @@ -2749,15 +2619,12 @@ public class LauncherActivity extends AppCompatActivity implements float minDistance = Float.MAX_VALUE; int index = EMPTY_LOCATION_DRAG; - for (int i = 0; i < page.getChildCount(); i++) { View v = page.getChildAt(i).findViewById(R.id.app_icon); Rect r = new Rect(); v.getGlobalVisibleRect(r); - Rect r2 = new Rect((int) (x - mDeviceProfile.iconSizePx / 2), - (int) (y - mDeviceProfile.iconSizePx / 2), - (int) (x + mDeviceProfile.iconSizePx / 2), - (int) (y + mDeviceProfile.iconSizePx / 2)); + Rect r2 = new Rect((int) (x - mDeviceProfile.iconSizePx / 2), (int) (y - mDeviceProfile.iconSizePx / 2), + (int) (x + mDeviceProfile.iconSizePx / 2), (int) (y + mDeviceProfile.iconSizePx / 2)); if (Rect.intersects(r, r2)) { float vx = r.left + (float) (r.right - r.left) / 2; float vy = r.top + (float) (r.bottom - r.top) / 2; @@ -2782,14 +2649,12 @@ public class LauncherActivity extends AppCompatActivity implements transition.setStartDelay(LayoutTransition.CHANGE_DISAPPEARING, 0); transition.addTransitionListener(new LayoutTransition.TransitionListener() { @Override - public void startTransition(LayoutTransition layoutTransition, - ViewGroup viewGroup, View view, int i) { + public void startTransition(LayoutTransition layoutTransition, ViewGroup viewGroup, View view, int i) { dragDropEnabled = false; } @Override - public void endTransition(LayoutTransition layoutTransition, - ViewGroup viewGroup, View view, int i) { + public void endTransition(LayoutTransition layoutTransition, ViewGroup viewGroup, View view, int i) { dragDropEnabled = true; } }); @@ -2804,8 +2669,8 @@ public class LauncherActivity extends AppCompatActivity implements mIndicator.removeAllViews(); } - LinearLayout.LayoutParams params = new LinearLayout.LayoutParams( - mDeviceProfile.pageIndicatorSizePx, mDeviceProfile.pageIndicatorSizePx); + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mDeviceProfile.pageIndicatorSizePx, + mDeviceProfile.pageIndicatorSizePx); for (int i = 0; i < pages.size() + 1; i++) { ImageView dot = new ImageView(this); @@ -2818,12 +2683,10 @@ public class LauncherActivity extends AppCompatActivity implements private void updateIndicator() { if (mIndicator.getChildAt(activeDot) != null) { - ((ImageView) mIndicator.getChildAt(activeDot)).setImageResource( - R.drawable.dot_off); + ((ImageView) mIndicator.getChildAt(activeDot)).setImageResource(R.drawable.dot_off); } if (mIndicator.getChildAt(currentPageNumber) != null) { - ((ImageView) mIndicator.getChildAt(currentPageNumber)).setImageResource( - R.drawable.dot_on); + ((ImageView) mIndicator.getChildAt(currentPageNumber)).setImageResource(R.drawable.dot_on); activeDot = currentPageNumber; } } @@ -2856,14 +2719,12 @@ public class LauncherActivity extends AppCompatActivity implements // bounds, since that's the origin for the positioning animation // properties (X, Y). v.getGlobalVisibleRect(startBounds); - findViewById(R.id.workspace) - .getGlobalVisibleRect(finalBounds, globalOffset); + findViewById(R.id.workspace).getGlobalVisibleRect(finalBounds, globalOffset); startBounds.offset(-globalOffset.x, -globalOffset.y); finalBounds.offset(-globalOffset.x, -globalOffset.y); float startScale; - if ((float) finalBounds.width() / finalBounds.height() - > (float) startBounds.width() / startBounds.height()) { + if ((float) finalBounds.width() / finalBounds.height() > (float) startBounds.width() / startBounds.height()) { // Extend start bounds horizontally startScale = (float) startBounds.height() / finalBounds.height(); float startWidth = startScale * finalBounds.width(); @@ -2882,17 +2743,16 @@ public class LauncherActivity extends AppCompatActivity implements // Construct and run the parallel animation of the four translation and // scale properties (X, Y, SCALE_X, and SCALE_Y). AnimatorSet set = new AnimatorSet(); - /*ValueAnimator valueAnimator = ValueAnimator.ofInt(0, 18); - valueAnimator.addUpdateListener(animation -> - BlurWallpaperProvider.getInstance(this).blur((Integer) animation.getAnimatedValue()));*/ - set.play(ObjectAnimator.ofFloat(mFolderWindowContainer, View.X, - startBounds.left, finalBounds.left)) - .with(ObjectAnimator.ofFloat(mFolderWindowContainer, View.Y, - startBounds.top, finalBounds.top)) - .with(ObjectAnimator.ofFloat(mFolderWindowContainer, View.SCALE_X, - startScale, 1f)) - .with(ObjectAnimator.ofFloat(mFolderWindowContainer, - View.SCALE_Y, startScale, 1f)) + /* + * ValueAnimator valueAnimator = ValueAnimator.ofInt(0, 18); + * valueAnimator.addUpdateListener(animation -> + * BlurWallpaperProvider.getInstance(this).blur((Integer) + * animation.getAnimatedValue())); + */ + set.play(ObjectAnimator.ofFloat(mFolderWindowContainer, View.X, startBounds.left, finalBounds.left)) + .with(ObjectAnimator.ofFloat(mFolderWindowContainer, View.Y, startBounds.top, finalBounds.top)) + .with(ObjectAnimator.ofFloat(mFolderWindowContainer, View.SCALE_X, startScale, 1f)) + .with(ObjectAnimator.ofFloat(mFolderWindowContainer, View.SCALE_Y, startScale, 1f)) .with(ObjectAnimator.ofFloat(blurLayer, View.ALPHA, 1f)) .with(ObjectAnimator.ofFloat(mHorizontalPager, View.ALPHA, 0f)) .with(ObjectAnimator.ofFloat(mIndicator, View.ALPHA, 0f)) @@ -2910,7 +2770,7 @@ public class LauncherActivity extends AppCompatActivity implements // is the center of the view). mFolderWindowContainer.setPivotX(0f); mFolderWindowContainer.setPivotY(0f); - //BlurWallpaperProvider.getInstance(LauncherActivity.this).clear(); + // BlurWallpaperProvider.getInstance(LauncherActivity.this).clear(); } @Override @@ -2940,12 +2800,11 @@ public class LauncherActivity extends AppCompatActivity implements mFolderTitleInput.setCursorVisible(false); mFolderAppsViewPager.setAdapter(new FolderAppsPagerAdapter(this, app.items)); - mFolderAppsViewPager.getLayoutParams().width = - mDeviceProfile.cellWidthPx * 3 + mDeviceProfile.iconDrawablePaddingPx; - mFolderAppsViewPager.getLayoutParams().height = - mDeviceProfile.cellHeightPx * 3 + mDeviceProfile.iconDrawablePaddingPx; - ((CircleIndicator) mLauncherView.findViewById(R.id.indicator)).setViewPager( - mFolderAppsViewPager); + mFolderAppsViewPager.getLayoutParams().width = mDeviceProfile.cellWidthPx * 3 + + mDeviceProfile.iconDrawablePaddingPx; + mFolderAppsViewPager.getLayoutParams().height = mDeviceProfile.cellHeightPx * 3 + + mDeviceProfile.iconDrawablePaddingPx; + ((CircleIndicator) mLauncherView.findViewById(R.id.indicator)).setViewPager(mFolderAppsViewPager); } @@ -2972,25 +2831,21 @@ public class LauncherActivity extends AppCompatActivity implements // Animate the four positioning/sizing properties in parallel, // back to their original values. AnimatorSet set = new AnimatorSet(); - /*ValueAnimator valueAnimator = ValueAnimator.ofInt(18, 0); - valueAnimator.addUpdateListener(animation -> - BlurWallpaperProvider.getInstance(this).blurWithLauncherView(mergedView, (Integer) animation.getAnimatedValue()));*/ - set.play(ObjectAnimator - .ofFloat(mFolderWindowContainer, View.X, startBounds.left)) - .with(ObjectAnimator - .ofFloat(mFolderWindowContainer, - View.Y, startBounds.top)) - .with(ObjectAnimator - .ofFloat(mFolderWindowContainer, - View.SCALE_X, startScaleFinal)) - .with(ObjectAnimator - .ofFloat(mFolderWindowContainer, - View.SCALE_Y, startScaleFinal)) + /* + * ValueAnimator valueAnimator = ValueAnimator.ofInt(18, 0); + * valueAnimator.addUpdateListener(animation -> + * BlurWallpaperProvider.getInstance(this).blurWithLauncherView(mergedView, + * (Integer) animation.getAnimatedValue())); + */ + set.play(ObjectAnimator.ofFloat(mFolderWindowContainer, View.X, startBounds.left)) + .with(ObjectAnimator.ofFloat(mFolderWindowContainer, View.Y, startBounds.top)) + .with(ObjectAnimator.ofFloat(mFolderWindowContainer, View.SCALE_X, startScaleFinal)) + .with(ObjectAnimator.ofFloat(mFolderWindowContainer, View.SCALE_Y, startScaleFinal)) .with(ObjectAnimator.ofFloat(blurLayer, View.ALPHA, 0f)) .with(ObjectAnimator.ofFloat(mHorizontalPager, View.ALPHA, 1f)) .with(ObjectAnimator.ofFloat(mIndicator, View.ALPHA, 1f)) .with(ObjectAnimator.ofFloat(mDock, View.ALPHA, 1f)); - //.with(valueAnimator); + // .with(valueAnimator); set.setDuration(300); set.setInterpolator(new LinearInterpolator()); set.addListener(new AnimatorListenerAdapter() { @@ -3029,14 +2884,12 @@ public class LauncherActivity extends AppCompatActivity implements @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); - final boolean alreadyOnHome = hasWindowFocus() && - ((intent.getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) - != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); + final boolean alreadyOnHome = hasWindowFocus() && ((intent.getFlags() + & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); - boolean shouldMoveToDefaultScreen = - alreadyOnHome && swipeSearchContainer.getVisibility() != VISIBLE && !isWobbling - && mFolderWindowContainer.getVisibility() != View.VISIBLE - && (activeRoundedWidgetView == null || !activeRoundedWidgetView.isWidgetActivated()); + boolean shouldMoveToDefaultScreen = alreadyOnHome && swipeSearchContainer.getVisibility() != VISIBLE + && !isWobbling && mFolderWindowContainer.getVisibility() != View.VISIBLE + && (activeRoundedWidgetView == null || !activeRoundedWidgetView.isWidgetActivated()); if (alreadyOnHome) { returnToHomeScreen(); @@ -3087,78 +2940,63 @@ public class LauncherActivity extends AppCompatActivity implements set.setDuration(animationDuration); set.setInterpolator(new LinearInterpolator()); set.addListener(new AnimatorListenerAdapter() { - @Override - public void onAnimationCancel(Animator animation) { - super.onAnimationCancel(animation); - currentAnimator = null; - swipeSearchContainer.setVisibility(GONE); - blurLayer.setAlpha(0f); - mHorizontalPager.setVisibility(VISIBLE); - mDock.setVisibility(VISIBLE); - mIndicator.setVisibility(VISIBLE); - } + @Override + public void onAnimationCancel(Animator animation) { + super.onAnimationCancel(animation); + currentAnimator = null; + swipeSearchContainer.setVisibility(GONE); + blurLayer.setAlpha(0f); + mHorizontalPager.setVisibility(VISIBLE); + mDock.setVisibility(VISIBLE); + mIndicator.setVisibility(VISIBLE); + } + + @Override + public void onAnimationEnd(Animator animation) { + super.onAnimationEnd(animation); + currentAnimator = null; - @Override - public void onAnimationEnd(Animator animation) { - super.onAnimationEnd(animation); - currentAnimator = null; - - blurLayer.setAlpha(1f); - mHorizontalPager.setVisibility(GONE); - mDock.setVisibility(GONE); - mIndicator.setVisibility(GONE); - - BlissInput searchEditText = swipeSearchContainer.findViewById( - R.id.search_input); - ImageView clearSuggestions = swipeSearchContainer.findViewById( - R.id.clearSuggestionImageView); - searchDisposableObserver = RxTextView.textChanges(searchEditText) - .debounce(300, TimeUnit.MILLISECONDS) - .map(CharSequence::toString) - .distinctUntilChanged() - .switchMap(charSequence -> { - if (charSequence != null && charSequence.length() > 0) { - LauncherActivity.this.runOnUiThread( - () -> clearSuggestions.setVisibility(VISIBLE)); - return LauncherActivity.this.searchForQuery(charSequence); - } else { - LauncherActivity.this.runOnUiThread( - () -> clearSuggestions.setVisibility(GONE)); - return Observable.just( - new SuggestionsResult(charSequence)); - } - }) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeWith( - new SearchInputDisposableObserver(LauncherActivity.this, - ((RecyclerView) swipeSearchContainer.findViewById( - R.id.suggestionRecyclerView)).getAdapter(), - swipeSearchContainer)); - searchEditText.requestFocus(); - refreshSuggestedApps(swipeSearchContainer, true); + blurLayer.setAlpha(1f); + mHorizontalPager.setVisibility(GONE); + mDock.setVisibility(GONE); + mIndicator.setVisibility(GONE); + + BlissInput searchEditText = swipeSearchContainer.findViewById(R.id.search_input); + ImageView clearSuggestions = swipeSearchContainer.findViewById(R.id.clearSuggestionImageView); + searchDisposableObserver = RxTextView.textChanges(searchEditText).debounce(300, TimeUnit.MILLISECONDS) + .map(CharSequence::toString).distinctUntilChanged().switchMap(charSequence -> { + if (charSequence != null && charSequence.length() > 0) { + LauncherActivity.this.runOnUiThread(() -> clearSuggestions.setVisibility(VISIBLE)); + return LauncherActivity.this.searchForQuery(charSequence); + } else { + LauncherActivity.this.runOnUiThread(() -> clearSuggestions.setVisibility(GONE)); + return Observable.just(new SuggestionsResult(charSequence)); } - } - ); + }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) + .subscribeWith(new SearchInputDisposableObserver(LauncherActivity.this, + ((RecyclerView) swipeSearchContainer.findViewById(R.id.suggestionRecyclerView)) + .getAdapter(), + swipeSearchContainer)); + searchEditText.requestFocus(); + refreshSuggestedApps(swipeSearchContainer, true); + } + }); set.start(); currentAnimator = set; } private void setUpSwipeSearchContainer() { BlissInput searchEditText = swipeSearchContainer.findViewById(R.id.search_input); - ImageView clearSuggestions = swipeSearchContainer.findViewById( - R.id.clearSuggestionImageView); + ImageView clearSuggestions = swipeSearchContainer.findViewById(R.id.clearSuggestionImageView); clearSuggestions.setOnClickListener(v -> { searchEditText.setText(""); searchEditText.clearFocus(); }); - RecyclerView suggestionRecyclerView = swipeSearchContainer.findViewById( - R.id.suggestionRecyclerView); + RecyclerView suggestionRecyclerView = swipeSearchContainer.findViewById(R.id.suggestionRecyclerView); AutoCompleteAdapter networkSuggestionAdapter = new AutoCompleteAdapter(this); suggestionRecyclerView.setAdapter(networkSuggestionAdapter); - suggestionRecyclerView.setLayoutManager( - new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); + suggestionRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)); searchEditText.setOnFocusChangeListener((v, hasFocus) -> { if (!hasFocus) { @@ -3186,8 +3024,7 @@ public class LauncherActivity extends AppCompatActivity implements currentAnimator.cancel(); } AnimatorSet set = new AnimatorSet(); - set.play(ObjectAnimator.ofFloat(swipeSearchContainer, View.TRANSLATION_Y, - -swipeSearchContainer.getHeight())) + set.play(ObjectAnimator.ofFloat(swipeSearchContainer, View.TRANSLATION_Y, -swipeSearchContainer.getHeight())) .with(ObjectAnimator.ofFloat(mHorizontalPager, View.ALPHA, 1f)) .with(ObjectAnimator.ofFloat(mIndicator, View.ALPHA, 1f)) .with(ObjectAnimator.ofFloat(mDock, View.ALPHA, 1f)) @@ -3195,51 +3032,46 @@ public class LauncherActivity extends AppCompatActivity implements set.setDuration(300); set.setInterpolator(new LinearInterpolator()); set.addListener(new AnimatorListenerAdapter() { - @Override - public void onAnimationStart(Animator animation) { - super.onAnimationStart(animation); - mHorizontalPager.setVisibility(VISIBLE); - mDock.setVisibility(VISIBLE); - mIndicator.setVisibility(VISIBLE); - //BlurWallpaperProvider.getInstance(LauncherActivity.this).clear(); - } + @Override + public void onAnimationStart(Animator animation) { + super.onAnimationStart(animation); + mHorizontalPager.setVisibility(VISIBLE); + mDock.setVisibility(VISIBLE); + mIndicator.setVisibility(VISIBLE); + // BlurWallpaperProvider.getInstance(LauncherActivity.this).clear(); + } - @Override - public void onAnimationCancel(Animator animation) { - super.onAnimationCancel(animation); - currentAnimator = null; - swipeSearchContainer.setVisibility(VISIBLE); - blurLayer.setAlpha(1f); - mHorizontalPager.setVisibility(GONE); - mDock.setVisibility(GONE); - mIndicator.setVisibility(GONE); - } + @Override + public void onAnimationCancel(Animator animation) { + super.onAnimationCancel(animation); + currentAnimator = null; + swipeSearchContainer.setVisibility(VISIBLE); + blurLayer.setAlpha(1f); + mHorizontalPager.setVisibility(GONE); + mDock.setVisibility(GONE); + mIndicator.setVisibility(GONE); + } - @Override - public void onAnimationEnd(Animator animation) { - super.onAnimationEnd(animation); - currentAnimator = null; - swipeSearchContainer.setVisibility(GONE); - blurLayer.setAlpha(0f); - if (searchDisposableObserver != null - && !searchDisposableObserver.isDisposed()) { - searchDisposableObserver.dispose(); - } - ((BlissInput) swipeSearchContainer.findViewById(R.id.search_input)).setText( - ""); - swipeSearchContainer.findViewById( - R.id.search_input).clearFocus(); - } - } - ); + @Override + public void onAnimationEnd(Animator animation) { + super.onAnimationEnd(animation); + currentAnimator = null; + swipeSearchContainer.setVisibility(GONE); + blurLayer.setAlpha(0f); + if (searchDisposableObserver != null && !searchDisposableObserver.isDisposed()) { + searchDisposableObserver.dispose(); + } + ((BlissInput) swipeSearchContainer.findViewById(R.id.search_input)).setText(""); + swipeSearchContainer.findViewById(R.id.search_input).clearFocus(); + } + }); set.start(); currentAnimator = set; } @Override public void onSwipeStart() { - swipeSearchContainer.setTranslationY( - BlissLauncher.getApplication(this).getDeviceProfile().availableHeightPx); + swipeSearchContainer.setTranslationY(BlissLauncher.getApplication(this).getDeviceProfile().availableHeightPx); swipeSearchContainer.setVisibility(GONE); showSwipeSearch = false; } @@ -3277,8 +3109,7 @@ public class LauncherActivity extends AppCompatActivity implements } public void showWidgetResizeContainer(RoundedWidgetView roundedWidgetView) { - RelativeLayout widgetResizeContainer = widgetsPage.findViewById( - R.id.widget_resizer_container); + RelativeLayout widgetResizeContainer = widgetsPage.findViewById(R.id.widget_resizer_container); if (widgetResizeContainer.getVisibility() != VISIBLE) { activeRoundedWidgetView = roundedWidgetView; @@ -3293,34 +3124,33 @@ public class LauncherActivity extends AppCompatActivity implements }); AnimatorSet set = new AnimatorSet(); - set.play(ObjectAnimator.ofFloat(widgetResizeContainer, View.TRANSLATION_Y, - Utilities.pxFromDp(48, this), 0)); + set.play( + ObjectAnimator.ofFloat(widgetResizeContainer, View.TRANSLATION_Y, Utilities.pxFromDp(48, this), 0)); set.setDuration(200); set.setInterpolator(new LinearInterpolator()); set.addListener(new AnimatorListenerAdapter() { - @Override - public void onAnimationStart(Animator animation) { - super.onAnimationStart(animation); - widgetResizeContainer.setVisibility(VISIBLE); - } + @Override + public void onAnimationStart(Animator animation) { + super.onAnimationStart(animation); + widgetResizeContainer.setVisibility(VISIBLE); + } - @Override - public void onAnimationCancel(Animator animation) { - super.onAnimationCancel(animation); - currentAnimator = null; - widgetResizeContainer.setVisibility(GONE); - roundedWidgetView.removeBorder(); - } + @Override + public void onAnimationCancel(Animator animation) { + super.onAnimationCancel(animation); + currentAnimator = null; + widgetResizeContainer.setVisibility(GONE); + roundedWidgetView.removeBorder(); + } - @Override - public void onAnimationEnd(Animator animation) { - super.onAnimationEnd(animation); - currentAnimator = null; - prepareWidgetResizeSeekBar(seekBar); - roundedWidgetView.addBorder(); - } - } - ); + @Override + public void onAnimationEnd(Animator animation) { + super.onAnimationEnd(animation); + currentAnimator = null; + prepareWidgetResizeSeekBar(seekBar); + roundedWidgetView.addBorder(); + } + }); set.start(); currentAnimator = set; } @@ -3340,16 +3170,14 @@ public class LauncherActivity extends AppCompatActivity implements @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { int newHeight = minHeight + (normalisedDifference * progress); - LinearLayout.LayoutParams layoutParams = - (LinearLayout.LayoutParams) activeRoundedWidgetView.getLayoutParams(); + LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) activeRoundedWidgetView + .getLayoutParams(); layoutParams.height = newHeight; activeRoundedWidgetView.setLayoutParams(layoutParams); Bundle newOps = new Bundle(); - newOps.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, - mDeviceProfile.getMaxWidgetWidth()); - newOps.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH, - mDeviceProfile.getMaxWidgetWidth()); + newOps.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, mDeviceProfile.getMaxWidgetWidth()); + newOps.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH, mDeviceProfile.getMaxWidgetWidth()); newOps.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT, newHeight); newOps.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, newHeight); activeRoundedWidgetView.updateAppWidgetOptions(newOps); @@ -3363,49 +3191,45 @@ public class LauncherActivity extends AppCompatActivity implements @Override public void onStopTrackingTouch(SeekBar seekBar) { - DatabaseManager.getManager(LauncherActivity.this).saveWidgetHeight( - activeRoundedWidgetView.getAppWidgetId(), seekBar.getProgress()); + DatabaseManager.getManager(LauncherActivity.this) + .saveWidgetHeight(activeRoundedWidgetView.getAppWidgetId(), seekBar.getProgress()); } }); } public void hideWidgetResizeContainer() { - RelativeLayout widgetResizeContainer = widgetsPage.findViewById( - R.id.widget_resizer_container); + RelativeLayout widgetResizeContainer = widgetsPage.findViewById(R.id.widget_resizer_container); if (widgetResizeContainer.getVisibility() == VISIBLE) { if (currentAnimator != null) { currentAnimator.cancel(); } AnimatorSet set = new AnimatorSet(); - set.play(ObjectAnimator.ofFloat(widgetResizeContainer, View.TRANSLATION_Y, - Utilities.pxFromDp(48, this))); + set.play(ObjectAnimator.ofFloat(widgetResizeContainer, View.TRANSLATION_Y, Utilities.pxFromDp(48, this))); set.setDuration(200); set.setInterpolator(new LinearInterpolator()); set.addListener(new AnimatorListenerAdapter() { - @Override - public void onAnimationStart(Animator animation) { - super.onAnimationStart(animation); - ((SeekBar) widgetsPage.findViewById( - R.id.widget_resizer_seekbar)).setOnSeekBarChangeListener(null); - } + @Override + public void onAnimationStart(Animator animation) { + super.onAnimationStart(animation); + ((SeekBar) widgetsPage.findViewById(R.id.widget_resizer_seekbar)).setOnSeekBarChangeListener(null); + } - @Override - public void onAnimationCancel(Animator animation) { - super.onAnimationCancel(animation); - currentAnimator = null; - widgetResizeContainer.setVisibility(VISIBLE); - } + @Override + public void onAnimationCancel(Animator animation) { + super.onAnimationCancel(animation); + currentAnimator = null; + widgetResizeContainer.setVisibility(VISIBLE); + } - @Override - public void onAnimationEnd(Animator animation) { - super.onAnimationEnd(animation); - currentAnimator = null; - widgetResizeContainer.setVisibility(GONE); - activeRoundedWidgetView.removeBorder(); - } - } - ); + @Override + public void onAnimationEnd(Animator animation) { + super.onAnimationEnd(animation); + currentAnimator = null; + widgetResizeContainer.setVisibility(GONE); + activeRoundedWidgetView.removeBorder(); + } + }); set.start(); currentAnimator = set; } @@ -3413,7 +3237,8 @@ public class LauncherActivity extends AppCompatActivity implements public void forceReload() { allAppsDisplayed = false; - BlissLauncher.getApplication(this).getAppProvider().getAppsRepository().updateAppsRelay(Collections.emptyList()); + BlissLauncher.getApplication(this).getAppProvider().getAppsRepository() + .updateAppsRelay(Collections.emptyList()); } @Override @@ -3443,14 +3268,12 @@ public class LauncherActivity extends AppCompatActivity implements @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { - GridLayout viewGroup = (GridLayout) LayoutInflater.from(mContext).inflate( - R.layout.apps_page, container, false); + GridLayout viewGroup = (GridLayout) LayoutInflater.from(mContext).inflate(R.layout.apps_page, container, + false); viewGroup.setRowCount(3); viewGroup.setColumnCount(3); - viewGroup.setPadding(mDeviceProfile.iconDrawablePaddingPx / 2, - mDeviceProfile.iconDrawablePaddingPx / 2, - mDeviceProfile.iconDrawablePaddingPx / 2, - mDeviceProfile.iconDrawablePaddingPx / 2); + viewGroup.setPadding(mDeviceProfile.iconDrawablePaddingPx / 2, mDeviceProfile.iconDrawablePaddingPx / 2, + mDeviceProfile.iconDrawablePaddingPx / 2, mDeviceProfile.iconDrawablePaddingPx / 2); int i = 0; while (9 * position + i < mFolderAppItems.size() && i < 9) { LauncherItem appItem = mFolderAppItems.get(9 * position + i); @@ -3478,8 +3301,7 @@ public class LauncherActivity extends AppCompatActivity implements } @Override - public void destroyItem(@NonNull ViewGroup container, int position, - @NonNull Object object) { + public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { container.removeView((View) object); } } @@ -3517,8 +3339,7 @@ public class LauncherActivity extends AppCompatActivity implements } public void onAlarm(Alarm alarm) { - if (mDock.getChildCount() < mDeviceProfile.numColumns - || parentPage == -99) { + if (mDock.getChildCount() < mDeviceProfile.numColumns || parentPage == -99) { if (movingApp.getParent() != null) { ((ViewGroup) movingApp.getParent()).removeView(movingApp); } diff --git a/app/src/main/java/foundation/e/blisslauncher/features/launcher/OnSwipeDownListener.java b/app/src/main/java/foundation/e/blisslauncher/features/launcher/OnSwipeDownListener.java index 9bb1b1a13e3db22b87df586391bb717c1b7d3402..1d4ed4f794ba62cc192133fae4d1bdc91cf0926b 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/launcher/OnSwipeDownListener.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/launcher/OnSwipeDownListener.java @@ -3,6 +3,8 @@ package foundation.e.blisslauncher.features.launcher; public interface OnSwipeDownListener { void onSwipeStart(); + void onSwipe(int position); + void onSwipeFinish(); } diff --git a/app/src/main/java/foundation/e/blisslauncher/features/launcher/SearchInputDisposableObserver.java b/app/src/main/java/foundation/e/blisslauncher/features/launcher/SearchInputDisposableObserver.java index 0da9bf53dd1d3d27a9a3e95ae5cb1edb01af2c42..f36232d5c118ce0b44c885a2507ecb13579297e3 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/launcher/SearchInputDisposableObserver.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/launcher/SearchInputDisposableObserver.java @@ -2,17 +2,14 @@ package foundation.e.blisslauncher.features.launcher; import android.view.View; import android.view.ViewGroup; - import androidx.recyclerview.widget.RecyclerView; - -import java.util.ArrayList; - import foundation.e.blisslauncher.R; import foundation.e.blisslauncher.core.customviews.BlissFrameLayout; import foundation.e.blisslauncher.core.database.model.LauncherItem; import foundation.e.blisslauncher.features.suggestions.AutoCompleteAdapter; import foundation.e.blisslauncher.features.suggestions.SuggestionsResult; import io.reactivex.observers.DisposableObserver; +import java.util.ArrayList; public class SearchInputDisposableObserver extends DisposableObserver { @@ -20,7 +17,8 @@ public class SearchInputDisposableObserver extends DisposableObserver(), - suggestionsResults.queryText); + launcherActivity.refreshSuggestedApps(appSuggestionsViewGroup, true); + networkSuggestionAdapter.updateSuggestions(new ArrayList<>(), suggestionsResults.queryText); } } diff --git a/app/src/main/java/foundation/e/blisslauncher/features/launcher/tasks/LoadAppsTask.java b/app/src/main/java/foundation/e/blisslauncher/features/launcher/tasks/LoadAppsTask.java index 3d1458036f9661ecc65a360ece478e24dc55fb7b..bf9a5280acb083d2e46b653c5522221f483c7f28 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/launcher/tasks/LoadAppsTask.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/launcher/tasks/LoadAppsTask.java @@ -1,12 +1,10 @@ package foundation.e.blisslauncher.features.launcher.tasks; import android.os.AsyncTask; - -import java.util.Map; - import foundation.e.blisslauncher.core.database.model.ApplicationItem; import foundation.e.blisslauncher.core.utils.AppUtils; import foundation.e.blisslauncher.features.launcher.AppProvider; +import java.util.Map; public class LoadAppsTask extends AsyncTask> { diff --git a/app/src/main/java/foundation/e/blisslauncher/features/launcher/tasks/LoadDatabaseTask.java b/app/src/main/java/foundation/e/blisslauncher/features/launcher/tasks/LoadDatabaseTask.java index ada820a7a21762090e4c4b2e6f87325a25d21e86..6225da2e85a36d3164be3dc9b3d61245384a12bf 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/launcher/tasks/LoadDatabaseTask.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/launcher/tasks/LoadDatabaseTask.java @@ -1,13 +1,11 @@ package foundation.e.blisslauncher.features.launcher.tasks; import android.os.AsyncTask; - -import java.util.List; - import foundation.e.blisslauncher.core.database.LauncherDB; import foundation.e.blisslauncher.core.database.model.LauncherItem; import foundation.e.blisslauncher.core.migrate.Migration; import foundation.e.blisslauncher.features.launcher.AppProvider; +import java.util.List; public class LoadDatabaseTask extends AsyncTask> { diff --git a/app/src/main/java/foundation/e/blisslauncher/features/launcher/tasks/LoadShortcutTask.java b/app/src/main/java/foundation/e/blisslauncher/features/launcher/tasks/LoadShortcutTask.java index 13693c9246ba45bea4f3bf853c1068a2e345ccee..ffe9df383755d3d89d161ea9791269a8b27d5c4c 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/launcher/tasks/LoadShortcutTask.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/launcher/tasks/LoadShortcutTask.java @@ -3,14 +3,12 @@ package foundation.e.blisslauncher.features.launcher.tasks; import android.os.AsyncTask; import android.os.Process; import android.util.Log; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import foundation.e.blisslauncher.features.launcher.AppProvider; import foundation.e.blisslauncher.features.shortcuts.DeepShortcutManager; import foundation.e.blisslauncher.features.shortcuts.ShortcutInfoCompat; +import java.util.HashMap; +import java.util.List; +import java.util.Map; public class LoadShortcutTask extends AsyncTask> { @@ -28,8 +26,8 @@ public class LoadShortcutTask extends AsyncTask doInBackground(Void... voids) { - List list = DeepShortcutManager.getInstance(mAppProvider.getContext()).queryForPinnedShortcuts(null, - Process.myUserHandle()); + List list = DeepShortcutManager.getInstance(mAppProvider.getContext()) + .queryForPinnedShortcuts(null, Process.myUserHandle()); Log.i(TAG, "doInBackground: " + list.size()); Map shortcutInfoMap = new HashMap<>(); for (ShortcutInfoCompat shortcutInfoCompat : list) { diff --git a/app/src/main/java/foundation/e/blisslauncher/features/notification/DotRenderer.java b/app/src/main/java/foundation/e/blisslauncher/features/notification/DotRenderer.java index f4e68593dcbf92e110c345a878cbedc52dd18753..a259014682643f5b5f5a1de14c71c3a0d1345ed8 100755 --- a/app/src/main/java/foundation/e/blisslauncher/features/notification/DotRenderer.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/notification/DotRenderer.java @@ -6,20 +6,16 @@ import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; - import foundation.e.blisslauncher.R; -/** - * Created by falcon on 20/3/18. - */ +/** Created by falcon on 20/3/18. */ public class DotRenderer { private static final float SIZE_PERCENTAGE = 0.3375f; private final Context mContext; private final int mSize; - private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | - Paint.FILTER_BITMAP_FLAG); + private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG); public DotRenderer(Context context, int iconSizePx) { mContext = context; @@ -27,13 +23,11 @@ public class DotRenderer { } public void drawDot(Canvas canvas, Rect iconBounds) { - Bitmap myBitmap = BitmapFactory.decodeResource( - mContext.getResources(), - R.drawable.notification_icon_72); + Bitmap myBitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.notification_icon_72); Bitmap scaledBitmap = Bitmap.createScaledBitmap(myBitmap, mSize, mSize, true); canvas.drawBitmap(scaledBitmap, iconBounds.left - scaledBitmap.getWidth() / 2, iconBounds.top - scaledBitmap.getHeight() / 2, mPaint); - //canvas.drawCircle(badgeCenterX, badgeCenterY, mSize/2, mPaint); + // canvas.drawCircle(badgeCenterX, badgeCenterY, mSize/2, mPaint); } } diff --git a/app/src/main/java/foundation/e/blisslauncher/features/notification/NotificationRepository.java b/app/src/main/java/foundation/e/blisslauncher/features/notification/NotificationRepository.java index d8d84755df7b4a840178cf763530434c6dd87bde..7066f652f79801dc53383abbd9a3f7af778f221d 100755 --- a/app/src/main/java/foundation/e/blisslauncher/features/notification/NotificationRepository.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/notification/NotificationRepository.java @@ -3,19 +3,13 @@ package foundation.e.blisslauncher.features.notification; import android.app.Notification; import android.service.notification.StatusBarNotification; import android.util.Log; - import com.jakewharton.rxrelay2.BehaviorRelay; - import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; -/** - * Created by Amit Kumar - * Email : mr.doc10jl96@gmail.com - */ - +/** Created by Amit Kumar Email : mr.doc10jl96@gmail.com */ public class NotificationRepository { private BehaviorRelay> notificationRelay; @@ -39,10 +33,9 @@ public class NotificationRepository { Set notificationSet = new HashSet<>(); for (StatusBarNotification statusBarNotification : list) { Notification notification = statusBarNotification.getNotification(); - if ((notification.flags & Notification.FLAG_ONGOING_EVENT) - == Notification.FLAG_ONGOING_EVENT - || (notification.flags & Notification.FLAG_FOREGROUND_SERVICE) - == Notification.FLAG_FOREGROUND_SERVICE) { + if ((notification.flags & Notification.FLAG_ONGOING_EVENT) == Notification.FLAG_ONGOING_EVENT + || (notification.flags + & Notification.FLAG_FOREGROUND_SERVICE) == Notification.FLAG_FOREGROUND_SERVICE) { continue; } notificationSet.add(statusBarNotification.getPackageName()); diff --git a/app/src/main/java/foundation/e/blisslauncher/features/notification/NotificationService.java b/app/src/main/java/foundation/e/blisslauncher/features/notification/NotificationService.java index 6bd0657c6727cac4ec40fb654f1766b707b61a8f..f5f824da700013df015379f85764945baf2d6d19 100755 --- a/app/src/main/java/foundation/e/blisslauncher/features/notification/NotificationService.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/notification/NotificationService.java @@ -8,15 +8,10 @@ import android.os.Handler; import android.provider.Settings; import android.service.notification.NotificationListenerService; import android.service.notification.StatusBarNotification; - -import java.util.Collections; - import foundation.e.blisslauncher.core.utils.ListUtil; +import java.util.Collections; -/** - * Created by falcon on 14/3/18. - */ - +/** Created by falcon on 14/3/18. */ public class NotificationService extends NotificationListenerService { private static boolean sIsConnected = false; @@ -36,8 +31,7 @@ public class NotificationService extends NotificationListenerService { super.onCreate(); mNotificationRepository = NotificationRepository.getNotificationRepository(); - getContentResolver().registerContentObserver( - NOTIFICATION_BADGING_URI, false, mNotificationSettingsObserver); + getContentResolver().registerContentObserver(NOTIFICATION_BADGING_URI, false, mNotificationSettingsObserver); onNotificationSettingsChanged(); } @@ -49,8 +43,8 @@ public class NotificationService extends NotificationListenerService { } private void onNotificationSettingsChanged() { - mAreDotsDisabled = Settings.Secure.getInt( - getContentResolver(), NOTIFICATION_BADGING_URI.getLastPathSegment(), 1) != 1; + mAreDotsDisabled = Settings.Secure.getInt(getContentResolver(), NOTIFICATION_BADGING_URI.getLastPathSegment(), + 1) != 1; if (mAreDotsDisabled && sIsConnected) { requestUnbind(); updateNotifications(); diff --git a/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/AddItemActivity.java b/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/AddItemActivity.java index b9cfb5cd798d0b2bdb7ff9aceefd08aacde84098..91a46d87d582655ba88348c8e93d1f229a00b0f4 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/AddItemActivity.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/AddItemActivity.java @@ -5,7 +5,6 @@ import android.content.Context; import android.content.pm.LauncherApps; import android.os.Build; import android.os.Bundle; - import androidx.appcompat.app.AppCompatActivity; @TargetApi(Build.VERSION_CODES.O) @@ -25,12 +24,11 @@ public class AddItemActivity extends AppCompatActivity { } if (request.getRequestType() == LauncherApps.PinItemRequest.REQUEST_TYPE_SHORTCUT) { - InstallShortcutReceiver.queueShortcut( - new ShortcutInfoCompat(request.getShortcutInfo()), this.getApplicationContext()); + InstallShortcutReceiver.queueShortcut(new ShortcutInfoCompat(request.getShortcutInfo()), + this.getApplicationContext()); request.accept(); finish(); } } - } } diff --git a/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/DeepShortcutManager.java b/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/DeepShortcutManager.java index 96d7c81dfc317553a237aaaca6e8173e5dce38d1..3cfa63288d8e27b04348c592f3b9587a7e750c13 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/DeepShortcutManager.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/DeepShortcutManager.java @@ -27,21 +27,20 @@ import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.UserHandle; import android.util.Log; - +import foundation.e.blisslauncher.core.Utilities; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import foundation.e.blisslauncher.core.Utilities; - /** - * Performs operations related to deep shortcuts, such as querying for them, pinning them, etc. + * Performs operations related to deep shortcuts, such as querying for them, + * pinning them, etc. */ public class DeepShortcutManager { private static final String TAG = "DeepShortcutManager"; - private static final int FLAG_GET_ALL = ShortcutQuery.FLAG_MATCH_DYNAMIC - | ShortcutQuery.FLAG_MATCH_MANIFEST | ShortcutQuery.FLAG_MATCH_PINNED; + private static final int FLAG_GET_ALL = ShortcutQuery.FLAG_MATCH_DYNAMIC | ShortcutQuery.FLAG_MATCH_MANIFEST + | ShortcutQuery.FLAG_MATCH_PINNED; private static DeepShortcutManager sInstance; private static final Object sInstanceLock = new Object(); @@ -73,27 +72,27 @@ public class DeepShortcutManager { /** * Queries for the shortcuts with the package name and provided ids. * - * This method is intended to get the full details for shortcuts when they are added or updated, - * because we only get "key" fields in onShortcutsChanged(). + *

+ * This method is intended to get the full details for shortcuts when they are + * added or updated, because we only get "key" fields in onShortcutsChanged(). */ - public List queryForFullDetails(String packageName, - List shortcutIds, UserHandle user) { + public List queryForFullDetails(String packageName, List shortcutIds, UserHandle user) { return query(FLAG_GET_ALL, packageName, null, shortcutIds, user); } /** - * Gets all the manifest and dynamic shortcuts associated with the given package and user, - * to be displayed in the shortcuts container on long press. + * Gets all the manifest and dynamic shortcuts associated with the given package + * and user, to be displayed in the shortcuts container on long press. */ - public List queryForShortcutsContainer(ComponentName activity, - List ids, UserHandle user) { - return query(ShortcutQuery.FLAG_MATCH_MANIFEST | ShortcutQuery.FLAG_MATCH_DYNAMIC, - activity.getPackageName(), activity, ids, user); + public List queryForShortcutsContainer(ComponentName activity, List ids, + UserHandle user) { + return query(ShortcutQuery.FLAG_MATCH_MANIFEST | ShortcutQuery.FLAG_MATCH_DYNAMIC, activity.getPackageName(), + activity, ids, user); } /** - * Removes the given shortcut from the current list of pinned shortcuts. - * (Runs on background thread) + * Removes the given shortcut from the current list of pinned shortcuts. (Runs + * on background thread) */ @TargetApi(25) public void unpinShortcut(final ShortcutKey key) { @@ -106,7 +105,7 @@ public class DeepShortcutManager { try { mLauncherApps.pinShortcuts(packageName, pinnedIds, user); mWasLastCallSuccess = true; - } catch (SecurityException |IllegalStateException e) { + } catch (SecurityException | IllegalStateException e) { Log.w(TAG, "Failed to unpin shortcut", e); mWasLastCallSuccess = false; } @@ -114,8 +113,8 @@ public class DeepShortcutManager { } /** - * Adds the given shortcut to the current list of pinned shortcuts. - * (Runs on background thread) + * Adds the given shortcut to the current list of pinned shortcuts. (Runs on + * background thread) */ @TargetApi(25) public void pinShortcut(final ShortcutKey key) { @@ -128,8 +127,8 @@ public class DeepShortcutManager { try { mLauncherApps.pinShortcuts(packageName, pinnedIds, user); mWasLastCallSuccess = true; - Log.d(TAG, "pinShortcut called: "+key); - } catch (SecurityException |IllegalStateException e) { + Log.d(TAG, "pinShortcut called: " + key); + } catch (SecurityException | IllegalStateException e) { Log.w(TAG, "Failed to pin shortcut", e); mWasLastCallSuccess = false; } @@ -137,14 +136,13 @@ public class DeepShortcutManager { } @TargetApi(25) - public void startShortcut(String packageName, String id, Rect sourceBounds, - Bundle startActivityOptions, UserHandle user) { + public void startShortcut(String packageName, String id, Rect sourceBounds, Bundle startActivityOptions, + UserHandle user) { if (Utilities.ATLEAST_NOUGAT_MR1) { try { - mLauncherApps.startShortcut(packageName, id, sourceBounds, - startActivityOptions, user); + mLauncherApps.startShortcut(packageName, id, sourceBounds, startActivityOptions, user); mWasLastCallSuccess = true; - } catch (SecurityException |IllegalStateException e) { + } catch (SecurityException | IllegalStateException e) { Log.e(TAG, "Failed to start shortcut", e); mWasLastCallSuccess = false; } @@ -155,11 +153,10 @@ public class DeepShortcutManager { public Drawable getShortcutIconDrawable(ShortcutInfoCompat shortcutInfo, int density) { if (Utilities.ATLEAST_NOUGAT_MR1) { try { - Drawable icon = mLauncherApps.getShortcutIconDrawable( - shortcutInfo.getShortcutInfo(), density); + Drawable icon = mLauncherApps.getShortcutIconDrawable(shortcutInfo.getShortcutInfo(), density); mWasLastCallSuccess = true; return icon; - } catch (SecurityException |IllegalStateException e) { + } catch (SecurityException | IllegalStateException e) { Log.e(TAG, "Failed to get shortcut icon", e); mWasLastCallSuccess = false; } @@ -168,8 +165,10 @@ public class DeepShortcutManager { } /** - * Returns the id's of pinned shortcuts associated with the given package and user. + * Returns the id's of pinned shortcuts associated with the given package and + * user. * + *

* If packageName is null, returns all pinned shortcuts regardless of package. */ public List queryForPinnedShortcuts(String packageName, UserHandle user) { @@ -190,13 +189,15 @@ public class DeepShortcutManager { /** * Query the system server for all the shortcuts matching the given parameters. - * If packageName == null, we query for all shortcuts with the passed flags, regardless of app. + * If packageName == null, we query for all shortcuts with the passed flags, + * regardless of app. * + *

* TODO: Use the cache to optimize this so we don't make an RPC every time. */ @TargetApi(25) - private List query(int flags, String packageName, - ComponentName activity, List shortcutIds, UserHandle user) { + private List query(int flags, String packageName, ComponentName activity, + List shortcutIds, UserHandle user) { if (Utilities.ATLEAST_NOUGAT_MR1) { ShortcutQuery q = new ShortcutQuery(); q.setQueryFlags(flags); @@ -231,7 +232,7 @@ public class DeepShortcutManager { if (Utilities.ATLEAST_NOUGAT_MR1) { try { return mLauncherApps.hasShortcutHostPermission(); - } catch (SecurityException |IllegalStateException e) { + } catch (SecurityException | IllegalStateException e) { Log.e(TAG, "Failed to make shortcut manager call", e); } } diff --git a/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/InstallShortcutReceiver.java b/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/InstallShortcutReceiver.java index e7cf14e88b95f85a8203c0260af94c7c0e952189..e7bd6d1a05881fcd98bc4e1f2a57c02624f4eb0e 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/InstallShortcutReceiver.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/InstallShortcutReceiver.java @@ -9,10 +9,6 @@ import android.graphics.drawable.Drawable; import android.os.Parcelable; import android.os.UserManager; import android.util.Log; - - -import java.io.ByteArrayOutputStream; - import foundation.e.blisslauncher.BlissLauncher; import foundation.e.blisslauncher.core.IconsHandler; import foundation.e.blisslauncher.core.Utilities; @@ -21,12 +17,12 @@ import foundation.e.blisslauncher.core.events.EventRelay; import foundation.e.blisslauncher.core.events.ShortcutAddEvent; import foundation.e.blisslauncher.core.utils.Constants; import foundation.e.blisslauncher.core.utils.UserHandle; +import java.io.ByteArrayOutputStream; public class InstallShortcutReceiver extends BroadcastReceiver { private static final String TAG = "InstallShortcutReceiver"; - private static final String ACTION_INSTALL_SHORTCUT = - "com.android.launcher.action.INSTALL_SHORTCUT"; + private static final String ACTION_INSTALL_SHORTCUT = "com.android.launcher.action.INSTALL_SHORTCUT"; private static final String LAUNCH_INTENT_KEY = "intent.launch"; private static final String DEEPSHORTCUT_TYPE_KEY = "isDeepShortcut"; @@ -52,10 +48,11 @@ public class InstallShortcutReceiver extends BroadcastReceiver { } ShortcutItem shortcutItem = createShortcutItem(data, context); EventRelay.getInstance().push(new ShortcutAddEvent(shortcutItem)); - /*context.startActivity(new Intent(Intent.ACTION_MAIN) - .addCategory(Intent.CATEGORY_HOME) - .setPackage(context.getPackageName()) - .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));*/ + /* + * context.startActivity(new Intent(Intent.ACTION_MAIN) + * .addCategory(Intent.CATEGORY_HOME) .setPackage(context.getPackageName()) + * .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); + */ } public static void queueShortcut(ShortcutInfoCompat info, Context context) { @@ -63,7 +60,7 @@ public class InstallShortcutReceiver extends BroadcastReceiver { UserManager userManager = (UserManager) context.getSystemService(Context.USER_SERVICE); ShortcutItem shortcutItem = new ShortcutItem(); shortcutItem.id = info.getId(); - Log.i(TAG, "queueShortcut: "+ shortcutItem.id); + Log.i(TAG, "queueShortcut: " + shortcutItem.id); shortcutItem.user = new UserHandle(userManager.getSerialNumberForUser(info.getUserHandle()), info.getUserHandle()); shortcutItem.packageName = info.getPackage(); @@ -71,14 +68,14 @@ public class InstallShortcutReceiver extends BroadcastReceiver { shortcutItem.container = Constants.CONTAINER_DESKTOP; Drawable icon = DeepShortcutManager.getInstance(context).getShortcutIconDrawable(info, context.getResources().getDisplayMetrics().densityDpi); - shortcutItem.icon = BlissLauncher.getApplication(context).getIconsHandler().convertIcon( - icon); + shortcutItem.icon = BlissLauncher.getApplication(context).getIconsHandler().convertIcon(icon); shortcutItem.launchIntent = info.makeIntent(); EventRelay.getInstance().push(new ShortcutAddEvent(shortcutItem)); - /*context.startActivity(new Intent(Intent.ACTION_MAIN) - .addCategory(Intent.CATEGORY_HOME) - .setPackage(context.getPackageName()) - .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));*/ + /* + * context.startActivity(new Intent(Intent.ACTION_MAIN) + * .addCategory(Intent.CATEGORY_HOME) .setPackage(context.getPackageName()) + * .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)); + */ } private static ShortcutItem createShortcutItem(Intent data, Context context) { @@ -87,7 +84,8 @@ public class InstallShortcutReceiver extends BroadcastReceiver { Parcelable bitmap = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON); if (intent == null) { - // If the intent is null, we can't construct a valid ShortcutInfo, so we return null + // If the intent is null, we can't construct a valid ShortcutInfo, so we return + // null Log.e(TAG, "Can't construct ShortcutInfo with null intent"); return null; } @@ -104,13 +102,11 @@ public class InstallShortcutReceiver extends BroadcastReceiver { } else { Parcelable extra = data.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE); if (extra instanceof Intent.ShortcutIconResource) { - icon = IconsHandler.createIconDrawable( - (Intent.ShortcutIconResource) extra, context); + icon = IconsHandler.createIconDrawable((Intent.ShortcutIconResource) extra, context); } } if (icon == null) { - icon = BlissLauncher.getApplication( - context).getIconsHandler().getFullResDefaultActivityIcon(); + icon = BlissLauncher.getApplication(context).getIconsHandler().getFullResDefaultActivityIcon(); } item.packageName = intent.getPackage(); item.container = Constants.CONTAINER_DESKTOP; @@ -128,8 +124,8 @@ public class InstallShortcutReceiver extends BroadcastReceiver { } private static Bitmap convertToBitmap(Drawable drawable) { - Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), - drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); + Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), + Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(canvas); diff --git a/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/ShortcutCache.java b/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/ShortcutCache.java index ffaac6da5a060d59af124188b82e9cb0f187ab9a..8314b110793d08ba3134fad8a9a3893bbbbd52f3 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/ShortcutCache.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/ShortcutCache.java @@ -20,12 +20,11 @@ import android.annotation.TargetApi; import android.os.Build; import android.util.ArrayMap; import android.util.LruCache; - import java.util.List; /** - * Loads {@link ShortcutInfoCompat}s on demand (e.g. when launcher - * loads for pinned shortcuts and on long-press for dynamic shortcuts), and caches them + * Loads {@link ShortcutInfoCompat}s on demand (e.g. when launcher loads for + * pinned shortcuts and on long-press for dynamic shortcuts), and caches them * for handful of apps in an LruCache while launcher lives. */ @TargetApi(Build.VERSION_CODES.N) @@ -44,9 +43,11 @@ public class ShortcutCache { /** * Removes shortcuts from the cache when shortcuts change for a given package. * + *

* Returns a map of ids to their evicted shortcuts. * - * @see android.content.pm.LauncherApps.Callback#onShortcutsChanged(String, List, UserHandle). + * @see android.content.pm.LauncherApps.Callback#onShortcutsChanged(String, + * List, UserHandle). */ public void removeShortcuts(List shortcuts) { for (ShortcutInfoCompat shortcut : shortcuts) { diff --git a/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/ShortcutInfoCompat.java b/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/ShortcutInfoCompat.java index d627e71160a57c98557fa4e12723ad2b0d130816..0e583a69de0e91d30b283de7e452285700ef264a 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/ShortcutInfoCompat.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/ShortcutInfoCompat.java @@ -24,8 +24,8 @@ import android.os.Build; import android.os.UserHandle; /** - * Wrapper class for {@link android.content.pm.ShortcutInfo}, representing deep shortcuts into apps. - * + * Wrapper class for {@link android.content.pm.ShortcutInfo}, representing deep + * shortcuts into apps. */ @TargetApi(Build.VERSION_CODES.N) public class ShortcutInfoCompat { @@ -40,9 +40,7 @@ public class ShortcutInfoCompat { @TargetApi(Build.VERSION_CODES.N) public Intent makeIntent() { - return new Intent(Intent.ACTION_MAIN) - .addCategory(INTENT_CATEGORY) - .setComponent(getActivity()) + return new Intent(Intent.ACTION_MAIN).addCategory(INTENT_CATEGORY).setComponent(getActivity()) .setPackage(getPackage()) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) .putExtra(EXTRA_SHORTCUT_ID, getId()); diff --git a/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/ShortcutKey.java b/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/ShortcutKey.java index 9df2171f1594f6484708c29ca2cac1893bfbe35d..873b8dcb7d925d9f06ade194eb1e198704f8cf25 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/ShortcutKey.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/ShortcutKey.java @@ -3,13 +3,12 @@ package foundation.e.blisslauncher.features.shortcuts; import android.content.ComponentName; import android.content.Intent; import android.os.UserHandle; - import foundation.e.blisslauncher.core.database.model.ShortcutItem; import foundation.e.blisslauncher.core.utils.ComponentKey; - /** - * A key that uniquely identifies a shortcut using its package, id, and user handle. + * A key that uniquely identifies a shortcut using its package, id, and user + * handle. */ public class ShortcutKey extends ComponentKey { @@ -23,17 +22,15 @@ public class ShortcutKey extends ComponentKey { } public static ShortcutKey fromInfo(ShortcutInfoCompat shortcutInfo) { - return new ShortcutKey(shortcutInfo.getPackage(), shortcutInfo.getUserHandle(), - shortcutInfo.getId()); + return new ShortcutKey(shortcutInfo.getPackage(), shortcutInfo.getUserHandle(), shortcutInfo.getId()); } - public static ShortcutKey fromItem(ShortcutItem shortcutItem){ + public static ShortcutKey fromItem(ShortcutItem shortcutItem) { return new ShortcutKey(shortcutItem.packageName, shortcutItem.user.getRealHandle(), shortcutItem.id); } public static ShortcutKey fromIntent(Intent intent, UserHandle user) { - String shortcutId = intent.getStringExtra( - ShortcutInfoCompat.EXTRA_SHORTCUT_ID); + String shortcutId = intent.getStringExtra(ShortcutInfoCompat.EXTRA_SHORTCUT_ID); return new ShortcutKey(intent.getPackage(), user, shortcutId); } } diff --git a/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/UninstallShortcutReceiver.java b/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/UninstallShortcutReceiver.java index aa9ccf2826cd3090cb68f0402042ea43b105cb0b..b0f586c6358a3c5340e72ec68fdca00d1811d720 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/UninstallShortcutReceiver.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/shortcuts/UninstallShortcutReceiver.java @@ -3,7 +3,6 @@ package foundation.e.blisslauncher.features.shortcuts; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; - import foundation.e.blisslauncher.core.database.DatabaseManager; public class UninstallShortcutReceiver extends BroadcastReceiver { @@ -14,5 +13,4 @@ public class UninstallShortcutReceiver extends BroadcastReceiver { DatabaseManager databaseManager = DatabaseManager.getManager(context); databaseManager.removeShortcut(name); } - } diff --git a/app/src/main/java/foundation/e/blisslauncher/features/suggestions/AutoCompleteAdapter.java b/app/src/main/java/foundation/e/blisslauncher/features/suggestions/AutoCompleteAdapter.java index 3c39bc08637f2a2fdf9774b7f391b8a8baf54a70..84866d95a586abfde3ee5b7954e6fd244cf894cd 100755 --- a/app/src/main/java/foundation/e/blisslauncher/features/suggestions/AutoCompleteAdapter.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/suggestions/AutoCompleteAdapter.java @@ -10,19 +10,15 @@ import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.widget.TextView; - import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; - +import foundation.e.blisslauncher.R; +import foundation.e.blisslauncher.features.launcher.LauncherActivity; import java.util.ArrayList; import java.util.List; import java.util.Locale; -import foundation.e.blisslauncher.R; -import foundation.e.blisslauncher.features.launcher.LauncherActivity; - -public class AutoCompleteAdapter extends - RecyclerView.Adapter { +public class AutoCompleteAdapter extends RecyclerView.Adapter { private List mItems = new ArrayList<>(); private final OnSuggestionClickListener mOnSuggestionClickListener; private final LayoutInflater mInflater; @@ -36,26 +32,22 @@ public class AutoCompleteAdapter extends @NonNull @Override - public AutoCompleteAdapter.AutoCompleteViewHolder onCreateViewHolder(@NonNull ViewGroup parent, - int viewType) { + public AutoCompleteAdapter.AutoCompleteViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = mInflater.inflate(R.layout.item_suggestion, parent, false); AutoCompleteViewHolder holder = new AutoCompleteViewHolder(view); - view.setOnClickListener( - v -> mOnSuggestionClickListener.onClick(mItems.get(holder.getAdapterPosition()))); + view.setOnClickListener(v -> mOnSuggestionClickListener.onClick(mItems.get(holder.getAdapterPosition()))); return holder; } @Override - public void onBindViewHolder(@NonNull AutoCompleteAdapter.AutoCompleteViewHolder holder, - int position) { + public void onBindViewHolder(@NonNull AutoCompleteAdapter.AutoCompleteViewHolder holder, int position) { String suggestion = mItems.get(position); if (mQueryText != null) { SpannableStringBuilder spannable = new SpannableStringBuilder(suggestion); String lcSuggestion = suggestion.toLowerCase(Locale.getDefault()); int queryTextPos = lcSuggestion.indexOf(mQueryText); while (queryTextPos >= 0) { - spannable.setSpan(new StyleSpan(Typeface.BOLD), - queryTextPos, queryTextPos + mQueryText.length(), + spannable.setSpan(new StyleSpan(Typeface.BOLD), queryTextPos, queryTextPos + mQueryText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); queryTextPos = lcSuggestion.indexOf(mQueryText, queryTextPos + mQueryText.length()); } diff --git a/app/src/main/java/foundation/e/blisslauncher/features/suggestions/DuckDuckGoProvider.java b/app/src/main/java/foundation/e/blisslauncher/features/suggestions/DuckDuckGoProvider.java index 695b9b6f2dba826f2514cdc04362880e92b8de0a..ee856718a0948d59a363458f629dee9b8fd755be 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/suggestions/DuckDuckGoProvider.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/suggestions/DuckDuckGoProvider.java @@ -1,42 +1,32 @@ package foundation.e.blisslauncher.features.suggestions; -import java.io.IOException; -import java.util.ArrayList; - import foundation.e.blisslauncher.core.network.RetrofitService; import foundation.e.blisslauncher.core.network.duckduckgo.DuckDuckGoResult; import foundation.e.blisslauncher.core.network.duckduckgo.DuckDuckGoSuggestionService; import io.reactivex.Observable; import io.reactivex.Single; +import java.io.IOException; +import java.util.ArrayList; public class DuckDuckGoProvider implements SuggestionProvider { - private DuckDuckGoSuggestionService getSuggestionService() { String URL = "https://duckduckgo.com"; - return RetrofitService.getInstance( - URL).create(DuckDuckGoSuggestionService.class); + return RetrofitService.getInstance(URL).create(DuckDuckGoSuggestionService.class); } @Override public Single query(String query) { - return getSuggestionService().query(query) - .retryWhen(errors -> errors.flatMap(error -> { - // For IOExceptions, we retry - if (error instanceof IOException) { - return Observable.just(null); - } - // For anything else, don't retry - return Observable.error(error); - })) - .onErrorReturn(throwable -> new ArrayList<>()) - .flatMapIterable(duckDuckGoResults -> duckDuckGoResults) - .take(3) - .map(DuckDuckGoResult::getPhrase) - .toList() - .map(suggestions -> { - SuggestionsResult suggestionsResult = - new SuggestionsResult(query); + return getSuggestionService().query(query).retryWhen(errors -> errors.flatMap(error -> { + // For IOExceptions, we retry + if (error instanceof IOException) { + return Observable.just(null); + } + // For anything else, don't retry + return Observable.error(error); + })).onErrorReturn(throwable -> new ArrayList<>()).flatMapIterable(duckDuckGoResults -> duckDuckGoResults) + .take(3).map(DuckDuckGoResult::getPhrase).toList().map(suggestions -> { + SuggestionsResult suggestionsResult = new SuggestionsResult(query); suggestionsResult.setNetworkItems(suggestions); return suggestionsResult; }); diff --git a/app/src/main/java/foundation/e/blisslauncher/features/suggestions/QwantProvider.java b/app/src/main/java/foundation/e/blisslauncher/features/suggestions/QwantProvider.java index 0c6eb4b7cfa662134172118d37031661b629f20d..0b2a94a83c9678cea1c11cefdc7fea1622a75001 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/suggestions/QwantProvider.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/suggestions/QwantProvider.java @@ -1,41 +1,33 @@ package foundation.e.blisslauncher.features.suggestions; -import java.io.IOException; - import foundation.e.blisslauncher.core.network.RetrofitService; import foundation.e.blisslauncher.core.network.qwant.QwantItem; import foundation.e.blisslauncher.core.network.qwant.QwantResult; import foundation.e.blisslauncher.core.network.qwant.QwantSuggestionService; import io.reactivex.Observable; import io.reactivex.Single; +import java.io.IOException; public class QwantProvider implements SuggestionProvider { private QwantSuggestionService getSuggestionService() { String URL = "https://api.qwant.com"; - return RetrofitService.getInstance( - URL).create(QwantSuggestionService.class); + return RetrofitService.getInstance(URL).create(QwantSuggestionService.class); } @Override public Single query(String query) { - return getSuggestionService().query(query) - .retryWhen(errors -> errors.flatMap(error -> { - // For IOExceptions, we retry - if (error instanceof IOException) { - return Observable.just(new QwantResult()); - } - // For anything else, don't retry - return Observable.error(error); - })) - .filter(qwantResult -> qwantResult.getStatus().equals("success")) - .flatMapIterable(qwantResult -> qwantResult.getData().getItems()) - .take(3) - .map(QwantItem::getValue) - .toList() - .map(suggestions -> { - SuggestionsResult suggestionsResult = - new SuggestionsResult(query); + return getSuggestionService().query(query).retryWhen(errors -> errors.flatMap(error -> { + // For IOExceptions, we retry + if (error instanceof IOException) { + return Observable.just(new QwantResult()); + } + // For anything else, don't retry + return Observable.error(error); + })).filter(qwantResult -> qwantResult.getStatus().equals("success")) + .flatMapIterable(qwantResult -> qwantResult.getData().getItems()).take(3).map(QwantItem::getValue) + .toList().map(suggestions -> { + SuggestionsResult suggestionsResult = new SuggestionsResult(query); suggestionsResult.setNetworkItems(suggestions); return suggestionsResult; }); diff --git a/app/src/main/java/foundation/e/blisslauncher/features/suggestions/SearchSuggestionUtil.java b/app/src/main/java/foundation/e/blisslauncher/features/suggestions/SearchSuggestionUtil.java index 68a7eb9f35f9ff4a54ee4cb05a319d7783191f7d..0b61d631bc9c564b17820fae6c588e4ad6c50b4e 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/suggestions/SearchSuggestionUtil.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/suggestions/SearchSuggestionUtil.java @@ -39,8 +39,7 @@ public class SearchSuggestionUtil { private String defaultSearchEngine(Context context) { ContentResolver contentResolver = context.getContentResolver(); - Uri uri = Uri.parse("content://foundation.e.browser.provider").buildUpon().appendPath( - "search_engine").build(); + Uri uri = Uri.parse("content://foundation.e.browser.provider").buildUpon().appendPath("search_engine").build(); Cursor cursor = contentResolver.query(uri, null, null, null, null); if (cursor != null && cursor.moveToFirst()) { return cursor.getString(0); diff --git a/app/src/main/java/foundation/e/blisslauncher/features/suggestions/SuggestionsResult.java b/app/src/main/java/foundation/e/blisslauncher/features/suggestions/SuggestionsResult.java index 218b817baf12a7aa6094548ade0efeec689271eb..29a647d8305d4c738e753c0a597b0a899be616b7 100755 --- a/app/src/main/java/foundation/e/blisslauncher/features/suggestions/SuggestionsResult.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/suggestions/SuggestionsResult.java @@ -1,8 +1,7 @@ package foundation.e.blisslauncher.features.suggestions; -import java.util.List; - import foundation.e.blisslauncher.core.database.model.LauncherItem; +import java.util.List; public class SuggestionsResult { @@ -14,7 +13,6 @@ public class SuggestionsResult { public String queryText; public int type = -1; - public SuggestionsResult(String queryText) { this.queryText = queryText; } @@ -23,8 +21,7 @@ public class SuggestionsResult { return networkItems; } - public void setNetworkItems( - List networkItems) { + public void setNetworkItems(List networkItems) { this.networkItems = networkItems; this.type = TYPE_NETWORK_ITEM; } @@ -33,8 +30,7 @@ public class SuggestionsResult { return launcherItems; } - public void setLauncherItems( - List launcherItems) { + public void setLauncherItems(List launcherItems) { this.launcherItems = launcherItems; this.type = TYPE_LAUNCHER_ITEM; } diff --git a/app/src/main/java/foundation/e/blisslauncher/features/usagestats/AppUsageStats.java b/app/src/main/java/foundation/e/blisslauncher/features/usagestats/AppUsageStats.java index a5de1448838f115b059e21c3e1e6b2defb821463..544193ae4d655a9982af5a4cf54665600b0ce67d 100755 --- a/app/src/main/java/foundation/e/blisslauncher/features/usagestats/AppUsageStats.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/usagestats/AppUsageStats.java @@ -9,7 +9,8 @@ import android.content.Intent; import android.provider.Settings; import android.util.Log; import android.widget.Toast; - +import foundation.e.blisslauncher.R; +import foundation.e.blisslauncher.core.Preferences; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; @@ -18,9 +19,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import foundation.e.blisslauncher.R; -import foundation.e.blisslauncher.core.Preferences; - public class AppUsageStats { private final Context mContext; @@ -30,8 +28,7 @@ public class AppUsageStats { public AppUsageStats(Context context) { this.mContext = context; - mUsageStatsManager = (UsageStatsManager) context.getSystemService( - Context.USAGE_STATS_SERVICE); + mUsageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE); } public List getUsageStats() { @@ -39,8 +36,8 @@ public class AppUsageStats { Calendar cal = Calendar.getInstance(); cal.add(Calendar.YEAR, -1); - List stats = mUsageStatsManager.queryUsageStats(INTERVAL_BEST, - cal.getTimeInMillis(), System.currentTimeMillis()); + List stats = mUsageStatsManager.queryUsageStats(INTERVAL_BEST, cal.getTimeInMillis(), + System.currentTimeMillis()); Map aggregatedStats = new HashMap<>(); final int statCount = stats.size(); for (int i = 0; i < statCount; i++) { @@ -55,17 +52,15 @@ public class AppUsageStats { if (aggregatedStats.size() == 0 && Preferences.shouldOpenUsageAccess(mContext)) { Log.i(TAG, "The user may not allow the access to apps usage. "); - Toast.makeText(mContext, - mContext.getString(R.string.explanation_access_to_appusage_is_not_enabled), + Toast.makeText(mContext, mContext.getString(R.string.explanation_access_to_appusage_is_not_enabled), Toast.LENGTH_LONG).show(); mContext.startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS)); Preferences.setNotOpenUsageAccess(mContext); } else { Set> set = aggregatedStats.entrySet(); List> list = new ArrayList<>(set); - Collections.sort(list, - (o1, o2) -> Long.compare(o2.getValue().getTotalTimeInForeground(), - o1.getValue().getTotalTimeInForeground())); + Collections.sort(list, (o1, o2) -> Long.compare(o2.getValue().getTotalTimeInForeground(), + o1.getValue().getTotalTimeInForeground())); for (Map.Entry stringUsageStatsEntry : list) { usageStats.add(stringUsageStatsEntry.getValue()); } diff --git a/app/src/main/java/foundation/e/blisslauncher/features/weather/WeatherAppWidgetProvider.java b/app/src/main/java/foundation/e/blisslauncher/features/weather/WeatherAppWidgetProvider.java index 29bccfb05cb85dc23ff8a5ce7a6765acfed9309c..b15f6aecf920d11dc15ca4ed88bbb7fbdfc2e407 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/weather/WeatherAppWidgetProvider.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/weather/WeatherAppWidgetProvider.java @@ -2,14 +2,12 @@ package foundation.e.blisslauncher.features.weather; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; - import androidx.annotation.NonNull; - import foundation.e.blisslauncher.BuildConfig; public class WeatherAppWidgetProvider extends AppWidgetProvider { @NonNull - public static final ComponentName COMPONENT_NAME = new ComponentName( - BuildConfig.APPLICATION_ID, WeatherAppWidgetProvider.class.getName()); + public static final ComponentName COMPONENT_NAME = new ComponentName(BuildConfig.APPLICATION_ID, + WeatherAppWidgetProvider.class.getName()); } diff --git a/app/src/main/java/foundation/e/blisslauncher/features/weather/WeatherInfoView.java b/app/src/main/java/foundation/e/blisslauncher/features/weather/WeatherInfoView.java index e2b200fbe60ac297a37cfadf8db42d2da035862a..6b8388ddc4bec1f5ec81132eb87bc8050f3cf07f 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/weather/WeatherInfoView.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/weather/WeatherInfoView.java @@ -7,9 +7,7 @@ import android.content.IntentFilter; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; - import androidx.localbroadcastmanager.content.LocalBroadcastManager; - import foundation.e.blisslauncher.R; import foundation.e.blisslauncher.core.Preferences; import foundation.e.blisslauncher.features.launcher.LauncherActivity; @@ -44,25 +42,24 @@ public class WeatherInfoView extends LinearLayout { mWeatherSetupTextView = findViewById(R.id.weather_setup_textview); mWeatherPanel = findViewById(R.id.weather_panel); mWeatherPanel.setOnClickListener(v -> { - Intent launchIntent = getContext().getPackageManager().getLaunchIntentForPackage( - "foundation.e.weather"); + Intent launchIntent = getContext().getPackageManager().getLaunchIntentForPackage("foundation.e.weather"); if (launchIntent != null) { launchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); getContext().startActivity(launchIntent); } }); findViewById(R.id.weather_setting_imageview).setOnClickListener(v -> startWeatherPreferences()); - findViewById(R.id.weather_refresh_imageview).setOnClickListener(v -> WeatherUpdateService.scheduleNextUpdate(getContext(), true)); + findViewById(R.id.weather_refresh_imageview) + .setOnClickListener(v -> WeatherUpdateService.scheduleNextUpdate(getContext(), true)); } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); final LocalBroadcastManager broadcastManager = LocalBroadcastManager.getInstance(getContext()); - broadcastManager.registerReceiver(mWeatherReceiver, new IntentFilter( - WeatherUpdateService.ACTION_UPDATE_FINISHED)); - broadcastManager.registerReceiver(mResumeReceiver, new IntentFilter( - LauncherActivity.ACTION_LAUNCHER_RESUME)); + broadcastManager.registerReceiver(mWeatherReceiver, + new IntentFilter(WeatherUpdateService.ACTION_UPDATE_FINISHED)); + broadcastManager.registerReceiver(mResumeReceiver, new IntentFilter(LauncherActivity.ACTION_LAUNCHER_RESUME)); updateWeatherPanel(); } @@ -83,8 +80,7 @@ public class WeatherInfoView extends LinearLayout { } mWeatherSetupTextView.setVisibility(GONE); mWeatherPanel.setVisibility(VISIBLE); - ForecastBuilder.buildLargePanel(getContext(), mWeatherPanel, - Preferences.getCachedWeatherInfo(getContext())); + ForecastBuilder.buildLargePanel(getContext(), mWeatherPanel, Preferences.getCachedWeatherInfo(getContext())); } private void startWeatherPreferences() { diff --git a/app/src/main/java/foundation/e/blisslauncher/features/weather/WeatherWidgetHostView.java b/app/src/main/java/foundation/e/blisslauncher/features/weather/WeatherWidgetHostView.java index 4dcbdd6721fb9005e47652abeb17c22618428d30..cd8c2c59ad17dc813e53d325c11af37c41e162d1 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/weather/WeatherWidgetHostView.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/weather/WeatherWidgetHostView.java @@ -3,7 +3,6 @@ package foundation.e.blisslauncher.features.weather; import android.content.Context; import android.view.LayoutInflater; import android.widget.RemoteViews; - import foundation.e.blisslauncher.R; import foundation.e.blisslauncher.core.customviews.RoundedWidgetView; diff --git a/app/src/main/java/foundation/e/blisslauncher/features/widgets/AddedWidgetsAdapter.java b/app/src/main/java/foundation/e/blisslauncher/features/widgets/AddedWidgetsAdapter.java index 099b1c22c04fe1263a3012b0b6586b73a29ab5ce..7191906fec01d2307cee5bbd3345295fecefefc8 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/widgets/AddedWidgetsAdapter.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/widgets/AddedWidgetsAdapter.java @@ -7,17 +7,13 @@ import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; - import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; - +import foundation.e.blisslauncher.R; import java.util.ArrayList; import java.util.List; -import foundation.e.blisslauncher.R; - -public class AddedWidgetsAdapter extends - RecyclerView.Adapter { +public class AddedWidgetsAdapter extends RecyclerView.Adapter { private Context mContext; private int mDensity; @@ -35,20 +31,18 @@ public class AddedWidgetsAdapter extends @NonNull @Override public WidgetsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { - View view = LayoutInflater.from(mContext).inflate(R.layout.item_added_widget, viewGroup, - false); + View view = LayoutInflater.from(mContext).inflate(R.layout.item_added_widget, viewGroup, false); WidgetsViewHolder widgetsViewHolder = new WidgetsViewHolder(view); widgetsViewHolder.actionBtn.setImageResource(R.drawable.ic_remove_widget_red_24dp); - widgetsViewHolder.actionBtn.setOnClickListener( - v -> { - int position = widgetsViewHolder.getAdapterPosition(); - if (position != RecyclerView.NO_POSITION) { - Widget widget = mAppWidgetProviderInfos.get(position); - mAppWidgetProviderInfos.remove(position); - mOnActionClickListener.removeWidget(widget.id); - notifyItemRemoved(position); - } - }); + widgetsViewHolder.actionBtn.setOnClickListener(v -> { + int position = widgetsViewHolder.getAdapterPosition(); + if (position != RecyclerView.NO_POSITION) { + Widget widget = mAppWidgetProviderInfos.get(position); + mAppWidgetProviderInfos.remove(position); + mOnActionClickListener.removeWidget(widget.id); + notifyItemRemoved(position); + } + }); return widgetsViewHolder; } diff --git a/app/src/main/java/foundation/e/blisslauncher/features/widgets/CheckLongPressHelper.java b/app/src/main/java/foundation/e/blisslauncher/features/widgets/CheckLongPressHelper.java index a688201ad80b305f3b11188fa8842bf87fcea403..b216d3f62059dc7b8187008a26889700a21289ed 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/widgets/CheckLongPressHelper.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/widgets/CheckLongPressHelper.java @@ -19,11 +19,11 @@ package foundation.e.blisslauncher.features.widgets; import android.view.MotionEvent; import android.view.View; import android.view.ViewConfiguration; - import foundation.e.blisslauncher.core.Utilities; /** - * Utility class to handle tripper long press on a view with custom timeout and stylus event + * Utility class to handle tripper long press on a view with custom timeout and + * stylus event */ public class CheckLongPressHelper { @@ -56,7 +56,7 @@ public class CheckLongPressHelper { */ public void onTouchEvent(MotionEvent ev) { switch (ev.getAction()) { - case MotionEvent.ACTION_DOWN: { + case MotionEvent.ACTION_DOWN : { // Just in case the previous long press hasn't been cleared, we make sure to // start fresh on touch down. cancelLongPress(); @@ -67,11 +67,11 @@ public class CheckLongPressHelper { } break; } - case MotionEvent.ACTION_CANCEL: - case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL : + case MotionEvent.ACTION_UP : cancelLongPress(); break; - case MotionEvent.ACTION_MOVE: + case MotionEvent.ACTION_MOVE : if (!Utilities.pointInView(mView, ev.getX(), ev.getY(), mSlop)) { cancelLongPress(); } else if (mPendingCheckForLongPress != null && isStylusButtonPressed(ev)) { @@ -82,9 +82,7 @@ public class CheckLongPressHelper { } } - /** - * Overrides the default long press timeout. - */ + /** Overrides the default long press timeout. */ public void setLongPressTimeoutFactor(float longPressTimeoutFactor) { mLongPressTimeoutFactor = longPressTimeoutFactor; } @@ -99,9 +97,7 @@ public class CheckLongPressHelper { (long) (ViewConfiguration.getLongPressTimeout() * mLongPressTimeoutFactor)); } - /** - * Cancels any pending long press - */ + /** Cancels any pending long press */ public void cancelLongPress() { mHasPerformedLongPress = false; clearCallbacks(); @@ -115,9 +111,7 @@ public class CheckLongPressHelper { } private void triggerLongPress() { - if ((mView.getParent() != null) - && mView.hasWindowFocus() - && (!mView.isPressed() || mListener != null) + if ((mView.getParent() != null) && mView.hasWindowFocus() && (!mView.isPressed() || mListener != null) && !mHasPerformedLongPress) { boolean handled; if (mListener != null) { @@ -140,12 +134,12 @@ public class CheckLongPressHelper { } } - /** - * Identifies if the provided {@link MotionEvent} is a stylus with the primary stylus button - * pressed. + * Identifies if the provided {@link MotionEvent} is a stylus with the primary + * stylus button pressed. * - * @param event The event to check. + * @param event + * The event to check. * @return Whether a stylus button press occurred. */ private static boolean isStylusButtonPressed(MotionEvent event) { diff --git a/app/src/main/java/foundation/e/blisslauncher/features/widgets/WidgetManager.java b/app/src/main/java/foundation/e/blisslauncher/features/widgets/WidgetManager.java index 234c9c070abc373c35452dcdb1ffd88334714c20..20d8117dd3aea072334f2263c5a3d7e12817e2b4 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/widgets/WidgetManager.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/widgets/WidgetManager.java @@ -1,11 +1,10 @@ package foundation.e.blisslauncher.features.widgets; +import foundation.e.blisslauncher.core.customviews.RoundedWidgetView; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; -import foundation.e.blisslauncher.core.customviews.RoundedWidgetView; - public class WidgetManager { private static final WidgetManager ourInstance = new WidgetManager(); @@ -20,7 +19,8 @@ public class WidgetManager { } public void enqueueRemoveId(int id) { - // If the widget is not yet created but scheduled to be created we have to prevent the + // If the widget is not yet created but scheduled to be created we have to + // prevent the // creation, too. Iterator it = addWidgetViews.iterator(); while (it.hasNext()) { diff --git a/app/src/main/java/foundation/e/blisslauncher/features/widgets/WidgetPicker.java b/app/src/main/java/foundation/e/blisslauncher/features/widgets/WidgetPicker.java index f537c675eeba4682681e27b79231298d264f754f..bf319d2686652d078ea0d3dec5ae9ac41cdfb754 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/widgets/WidgetPicker.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/widgets/WidgetPicker.java @@ -13,19 +13,16 @@ import android.os.Parcelable; import android.util.DisplayMetrics; import android.util.Log; import android.widget.Toast; - import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; - +import foundation.e.blisslauncher.R; import java.text.Collator; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; -import foundation.e.blisslauncher.R; - public class WidgetPicker extends Activity implements WidgetPickerAdapter.OnClickListener { private static final int REQUEST_BIND_APPWIDGET = 111; @@ -60,10 +57,9 @@ public class WidgetPicker extends Activity implements WidgetPickerAdapter.OnClic Parcelable parcel = intent.getParcelableExtra(Intent.EXTRA_INTENT); if (parcel instanceof Intent) { mBaseIntent = (Intent) parcel; - mBaseIntent.setFlags(mBaseIntent.getFlags() & ~(Intent.FLAG_GRANT_READ_URI_PERMISSION - | Intent.FLAG_GRANT_WRITE_URI_PERMISSION - | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION - | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION)); + mBaseIntent.setFlags(mBaseIntent.getFlags() + & ~(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION + | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION | Intent.FLAG_GRANT_PREFIX_URI_PERMISSION)); } else { mBaseIntent = new Intent(Intent.ACTION_MAIN, null); mBaseIntent.addCategory(Intent.CATEGORY_DEFAULT); @@ -73,8 +69,7 @@ public class WidgetPicker extends Activity implements WidgetPickerAdapter.OnClic RecyclerView recyclerView = findViewById(R.id.all_widgets_recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this)); recyclerView.setHasFixedSize(true); - recyclerView.addItemDecoration( - new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); + recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); WidgetPickerAdapter adapter = new WidgetPickerAdapter(this); recyclerView.setAdapter(adapter); List items = new ArrayList<>(); @@ -90,9 +85,9 @@ public class WidgetPicker extends Activity implements WidgetPickerAdapter.OnClic } private void putInstalledAppWidgets(List items) { - List installed = - mAppWidgetManager.getInstalledProviders(); - if (installed == null) return; + List installed = mAppWidgetManager.getInstalledProviders(); + if (installed == null) + return; final int size = installed.size(); for (int i = 0; i < size; i++) { AppWidgetProviderInfo info = installed.get(i); @@ -109,36 +104,35 @@ public class WidgetPicker extends Activity implements WidgetPickerAdapter.OnClic final int density = res.getDisplayMetrics().densityDpi; int iconDensity; switch (density) { - case DisplayMetrics.DENSITY_MEDIUM: + case DisplayMetrics.DENSITY_MEDIUM : iconDensity = DisplayMetrics.DENSITY_LOW; break; - case DisplayMetrics.DENSITY_TV: + case DisplayMetrics.DENSITY_TV : iconDensity = DisplayMetrics.DENSITY_MEDIUM; break; - case DisplayMetrics.DENSITY_HIGH: + case DisplayMetrics.DENSITY_HIGH : iconDensity = DisplayMetrics.DENSITY_MEDIUM; break; - case DisplayMetrics.DENSITY_XHIGH: + case DisplayMetrics.DENSITY_XHIGH : iconDensity = DisplayMetrics.DENSITY_HIGH; break; - case DisplayMetrics.DENSITY_XXHIGH: + case DisplayMetrics.DENSITY_XXHIGH : iconDensity = DisplayMetrics.DENSITY_XHIGH; break; - default: - // The density is some abnormal value. Return some other + default : + // The density is some abnormal value. Return some other // abnormal value that is a reasonable scaling of it. iconDensity = (int) ((density * 0.75f) + .5f); } - Resources packageResources = mPackageManager. - getResourcesForApplication(info.provider.getPackageName()); + Resources packageResources = mPackageManager.getResourcesForApplication(info.provider.getPackageName()); icon = packageResources.getDrawableForDensity(info.icon, iconDensity); } catch (PackageManager.NameNotFoundException e) { - Log.w(TAG, "Can't load icon drawable 0x" + Integer.toHexString(info.icon) - + " for provider: " + info.provider); + Log.w(TAG, "Can't load icon drawable 0x" + Integer.toHexString(info.icon) + " for provider: " + + info.provider); } if (icon == null) { - Log.w(TAG, "Can't load icon drawable 0x" + Integer.toHexString(info.icon) - + " for provider: " + info.provider); + Log.w(TAG, "Can't load icon drawable 0x" + Integer.toHexString(info.icon) + " for provider: " + + info.provider); } } WidgetPickerAdapter.Item item = new WidgetPickerAdapter.Item(label, icon); @@ -158,12 +152,11 @@ public class WidgetPicker extends Activity implements WidgetPickerAdapter.OnClic try { Bundle options = null; if (intent.getExtras() != null) { - options = intent.getExtras().getBundle( - AppWidgetManager.EXTRA_APPWIDGET_OPTIONS); + options = intent.getExtras().getBundle(AppWidgetManager.EXTRA_APPWIDGET_OPTIONS); } - boolean success = mAppWidgetManager.bindAppWidgetIdIfAllowed(mAppWidgetId, - intent.getComponent(), options); + boolean success = mAppWidgetManager.bindAppWidgetIdIfAllowed(mAppWidgetId, intent.getComponent(), + options); if (success) { result = RESULT_OK; } else { @@ -171,8 +164,7 @@ public class WidgetPicker extends Activity implements WidgetPickerAdapter.OnClic permissionIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId); permissionIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, new ComponentName(item.packageName, item.className)); - intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE, - item.profile); + intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE, item.profile); // TODO: we need to make sure that this accounts for the options bundle. // intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_OPTIONS, options); startActivityForResult(permissionIntent, REQUEST_BIND_APPWIDGET); @@ -188,8 +180,8 @@ public class WidgetPicker extends Activity implements WidgetPickerAdapter.OnClic /** * Convenience method for setting the result code and intent. This method - * correctly injects the {@link AppWidgetManager#EXTRA_APPWIDGET_ID} that - * most hosts expect returned. + * correctly injects the {@link AppWidgetManager#EXTRA_APPWIDGET_ID} that most + * hosts expect returned. */ void setResultData(int code, Intent intent) { Intent result = intent != null ? intent : new Intent(); @@ -199,11 +191,10 @@ public class WidgetPicker extends Activity implements WidgetPickerAdapter.OnClic @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { - Log.d(TAG, "onActivityResult() called with: requestCode = [" + requestCode - + "], resultCode = [" + resultCode + "], data = [" + data + "]"); + Log.d(TAG, "onActivityResult() called with: requestCode = [" + requestCode + "], resultCode = [" + resultCode + + "], data = [" + data + "]"); if (requestCode == REQUEST_BIND_APPWIDGET) { - int appWidgetId = data != null ? - data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1; + int appWidgetId = data != null ? data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1) : -1; if (resultCode == RESULT_OK) { setResultData(RESULT_OK, null); } else { diff --git a/app/src/main/java/foundation/e/blisslauncher/features/widgets/WidgetPickerAdapter.java b/app/src/main/java/foundation/e/blisslauncher/features/widgets/WidgetPickerAdapter.java index 50b2b7fda764df06d4eda709fcd88677aa0c598e..1fc53bfdb9814bc7bc2c077ff5ce0d8bf598dd22 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/widgets/WidgetPickerAdapter.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/widgets/WidgetPickerAdapter.java @@ -12,17 +12,13 @@ import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; - import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; - +import foundation.e.blisslauncher.R; import java.util.ArrayList; import java.util.List; -import foundation.e.blisslauncher.R; - -public class WidgetPickerAdapter extends - RecyclerView.Adapter { +public class WidgetPickerAdapter extends RecyclerView.Adapter { private Context mContext; private List mItems = new ArrayList<>(); @@ -38,12 +34,11 @@ public class WidgetPickerAdapter extends @NonNull @Override public WidgetsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { - View view = LayoutInflater.from(mContext).inflate(R.layout.item_all_widget, viewGroup, - false); + View view = LayoutInflater.from(mContext).inflate(R.layout.item_all_widget, viewGroup, false); WidgetsViewHolder widgetsViewHolder = new WidgetsViewHolder(view); widgetsViewHolder.itemView.setOnClickListener(v -> { int position = widgetsViewHolder.getAdapterPosition(); - if (position != RecyclerView.NO_POSITION){ + if (position != RecyclerView.NO_POSITION) { mOnClickListener.onClick(mItems.get(position)); } }); @@ -77,7 +72,6 @@ public class WidgetPickerAdapter extends icon = itemView.findViewById(R.id.widget_icon); label = itemView.findViewById(R.id.widget_label); } - } public static class Item { @@ -88,9 +82,7 @@ public class WidgetPickerAdapter extends String className; Bundle extras; - /** - * Create a list item from given label and icon. - */ + /** Create a list item from given label and icon. */ Item(CharSequence label, Drawable icon) { this.label = label; this.icon = icon; @@ -112,8 +104,8 @@ public class WidgetPickerAdapter extends } /** - * Build the {@link Intent} described by this item. If this item - * can't create a valid {@link android.content.ComponentName}, it will return + * Build the {@link Intent} described by this item. If this item can't create a + * valid {@link android.content.ComponentName}, it will return * {@link Intent#ACTION_CREATE_SHORTCUT} filled with the item label. */ Intent getIntent(Intent baseIntent) { diff --git a/app/src/main/java/foundation/e/blisslauncher/features/widgets/WidgetViewBuilder.java b/app/src/main/java/foundation/e/blisslauncher/features/widgets/WidgetViewBuilder.java index d1128cc1a543129217b495acc5b62f79ebecb97d..99093287a1d121a251c5ba6938654233f9da6562 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/widgets/WidgetViewBuilder.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/widgets/WidgetViewBuilder.java @@ -20,13 +20,13 @@ public class WidgetViewBuilder { public static final String WIDGET_OPTION_DARK_TEXT = "foundation.e.blisslauncher.WIDGET_OPTION_DARK_TEXT"; public static RoundedWidgetView create(LauncherActivity launcherActivity, - @NonNull RoundedWidgetView roundedWidgetView) { - if (BlissLauncher.getApplication(launcherActivity).getAppWidgetHost() == null) return null; - roundedWidgetView.post(() -> updateWidgetOption(launcherActivity, roundedWidgetView, - roundedWidgetView.getAppWidgetInfo())); + @NonNull RoundedWidgetView roundedWidgetView) { + if (BlissLauncher.getApplication(launcherActivity).getAppWidgetHost() == null) + return null; + roundedWidgetView.post( + () -> updateWidgetOption(launcherActivity, roundedWidgetView, roundedWidgetView.getAppWidgetInfo())); - LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( - LinearLayout.LayoutParams.MATCH_PARENT, + LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); int margin = launcherActivity.getResources().getDimensionPixelSize(R.dimen.widget_margin); layoutParams.setMargins(0, margin, 0, margin); @@ -34,8 +34,8 @@ public class WidgetViewBuilder { roundedWidgetView.setOnLongClickListener(v -> { AppWidgetProviderInfo widgetProviderInfo = roundedWidgetView.getAppWidgetInfo(); - if ((widgetProviderInfo.resizeMode & AppWidgetProviderInfo.RESIZE_VERTICAL) - == AppWidgetProviderInfo.RESIZE_VERTICAL) { + if ((widgetProviderInfo.resizeMode + & AppWidgetProviderInfo.RESIZE_VERTICAL) == AppWidgetProviderInfo.RESIZE_VERTICAL) { launcherActivity.showWidgetResizeContainer(roundedWidgetView); } else { Log.i(TAG, launcherActivity.getString(R.string.widget_is_not_resizable)); @@ -46,17 +46,16 @@ public class WidgetViewBuilder { return roundedWidgetView; } - private static void updateWidgetOption(Context context, - RoundedWidgetView roundedWidgetView, + private static void updateWidgetOption(Context context, RoundedWidgetView roundedWidgetView, AppWidgetProviderInfo info) { Bundle newOps = new Bundle(); - newOps.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, BlissLauncher.getApplication( - context).getDeviceProfile().getMaxWidgetWidth()); - newOps.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH, BlissLauncher.getApplication( - context).getDeviceProfile().getMaxWidgetWidth()); + newOps.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_WIDTH, + BlissLauncher.getApplication(context).getDeviceProfile().getMaxWidgetWidth()); + newOps.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_WIDTH, + BlissLauncher.getApplication(context).getDeviceProfile().getMaxWidgetWidth()); newOps.putInt(AppWidgetManager.OPTION_APPWIDGET_MIN_HEIGHT, info.minHeight); - newOps.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, BlissLauncher.getApplication( - context).getDeviceProfile().getMaxWidgetHeight()); + newOps.putInt(AppWidgetManager.OPTION_APPWIDGET_MAX_HEIGHT, + BlissLauncher.getApplication(context).getDeviceProfile().getMaxWidgetHeight()); newOps.putBoolean(WIDGET_OPTION_DARK_TEXT, ThemesKt.isWorkspaceDarkText(context)); roundedWidgetView.updateAppWidgetOptions(newOps); } diff --git a/app/src/main/java/foundation/e/blisslauncher/features/widgets/WidgetsActivity.java b/app/src/main/java/foundation/e/blisslauncher/features/widgets/WidgetsActivity.java index ee10dc7a81ae7eb5a7bba2e2ccd856df537b8b9a..19ccfcca1f96bd91bbdf7e225d2fc7cd708a97cb 100644 --- a/app/src/main/java/foundation/e/blisslauncher/features/widgets/WidgetsActivity.java +++ b/app/src/main/java/foundation/e/blisslauncher/features/widgets/WidgetsActivity.java @@ -8,14 +8,9 @@ import android.content.Intent; import android.os.Bundle; import android.util.DisplayMetrics; import android.widget.Toast; - import androidx.recyclerview.widget.DividerItemDecoration; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; - -import java.util.ArrayList; -import java.util.List; - import foundation.e.blisslauncher.BlissLauncher; import foundation.e.blisslauncher.R; import foundation.e.blisslauncher.core.customviews.RoundedWidgetView; @@ -26,6 +21,8 @@ import foundation.e.blisslauncher.core.executors.AppExecutors; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; +import java.util.ArrayList; +import java.util.List; public class WidgetsActivity extends Activity implements AddedWidgetsAdapter.OnActionClickListener { @@ -51,8 +48,7 @@ public class WidgetsActivity extends Activity implements AddedWidgetsAdapter.OnA addedWidgets.setLayoutManager(new LinearLayoutManager(this)); addedWidgets.setHasFixedSize(false); addedWidgets.setNestedScrollingEnabled(false); - addedWidgets.addItemDecoration( - new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); + addedWidgets.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); DisplayMetrics metrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(metrics); @@ -77,8 +73,7 @@ public class WidgetsActivity extends Activity implements AddedWidgetsAdapter.OnA int[] widgetIds = mAppWidgetHost.getAppWidgetIds(); mCompositeDisposable.add(DatabaseManager.getManager(this).getWidgets(widgetIds) .subscribeOn(Schedulers.from(AppExecutors.getInstance().diskIO())) - .observeOn(AndroidSchedulers.mainThread()) - .subscribe(this::setWidgetItems)); + .observeOn(AndroidSchedulers.mainThread()).subscribe(this::setWidgetItems)); } private void setWidgetItems(List widgetItems) { @@ -139,10 +134,12 @@ public class WidgetsActivity extends Activity implements AddedWidgetsAdapter.OnA int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1); AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId); if (appWidgetInfo != null && appWidgetInfo.configure != null) { - /*Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE); - intent.setComponent(appWidgetInfo.configure); - intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); - startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);*/ + /* + * Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE); + * intent.setComponent(appWidgetInfo.configure); + * intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId); + * startActivityForResult(intent, REQUEST_CREATE_APPWIDGET); + */ startAppWidgetConfigureActivitySafely(appWidgetId); } else { createWidget(data); @@ -153,8 +150,7 @@ public class WidgetsActivity extends Activity implements AddedWidgetsAdapter.OnA Bundle extras = data.getExtras(); int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1); AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId); - RoundedWidgetView hostView = (RoundedWidgetView) mAppWidgetHost.createView( - getApplicationContext(), appWidgetId, + RoundedWidgetView hostView = (RoundedWidgetView) mAppWidgetHost.createView(getApplicationContext(), appWidgetId, appWidgetInfo); hostView.setAppWidget(appWidgetId, appWidgetInfo); WidgetManager.getInstance().enqueueAddWidget(hostView); @@ -163,11 +159,10 @@ public class WidgetsActivity extends Activity implements AddedWidgetsAdapter.OnA void startAppWidgetConfigureActivitySafely(int appWidgetId) { try { - mAppWidgetHost.startAppWidgetConfigureActivityForResult(this, appWidgetId, 0, - REQUEST_CREATE_APPWIDGET, null); + mAppWidgetHost.startAppWidgetConfigureActivityForResult(this, appWidgetId, 0, REQUEST_CREATE_APPWIDGET, + null); } catch (ActivityNotFoundException e) { Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show(); } } - } diff --git a/app/src/test/java/foundation/e/blisslauncher/core/events/EventRelayTest.java b/app/src/test/java/foundation/e/blisslauncher/core/events/EventRelayTest.java index 100b138b7373c1d9360343bcc68c1a6139f2363f..cbd5fb661a546bb1b2c8f4cabe2b1fee8da28f54 100644 --- a/app/src/test/java/foundation/e/blisslauncher/core/events/EventRelayTest.java +++ b/app/src/test/java/foundation/e/blisslauncher/core/events/EventRelayTest.java @@ -1,5 +1,11 @@ package foundation.e.blisslauncher.core.events; +import static org.mockito.Mockito.reset; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -7,13 +13,6 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; - -import static org.mockito.Mockito.reset; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; - @RunWith(MockitoJUnitRunner.class) @SuppressWarnings("unchecked") public class EventRelayTest { @@ -65,7 +64,8 @@ public class EventRelayTest { eventRelay.push(appAddEvent); eventRelay.push(appAddEvent); - // Now subscribe to the relay to confirm if all previously pushed events are being relayed. + // Now subscribe to the relay to confirm if all previously pushed events are + // being relayed. eventRelay.subscribe(eventsObserver); verify(eventsObserver, times(2)).accept(appAddEvent); verify(eventsObserver).complete(); // Check if complete() gets called. @@ -82,15 +82,13 @@ public class EventRelayTest { public void testPushingAfterSubscribe() { // Subscribe first eventRelay.subscribe(eventsObserver); - //Push the event + // Push the event eventRelay.push(shortcutAddEvent); verify(eventsObserver, times(1)).accept(shortcutAddEvent); verify(eventsObserver, times(1)).complete(); } - /** - * This test is done separately to confirm that complete() is not called. - */ + /** This test is done separately to confirm that complete() is not called. */ @Test public void testTimeChangeEventPush() { eventRelay.subscribe(eventsObserver); @@ -121,4 +119,4 @@ public class EventRelayTest { verify(eventsObserver, times(0)).accept(appChangeEvent); verify(eventsObserver, times(0)).complete(); } -} \ No newline at end of file +} diff --git a/build-logic/kotlin-plugins/src/main/kotlin/foundation/e/blisslauncher/gradle/SpotlessPlugin.kt b/build-logic/kotlin-plugins/src/main/kotlin/foundation/e/blisslauncher/gradle/SpotlessPlugin.kt index 3f694da53887fe2d1f9108f1c072ca1b36162400..8c4dca475eaa50d41b03254862bfe1bfbb5d27b5 100644 --- a/build-logic/kotlin-plugins/src/main/kotlin/foundation/e/blisslauncher/gradle/SpotlessPlugin.kt +++ b/build-logic/kotlin-plugins/src/main/kotlin/foundation/e/blisslauncher/gradle/SpotlessPlugin.kt @@ -16,6 +16,9 @@ class SpotlessPlugin : Plugin { java { target("**/*.java") removeUnusedImports() + eclipse() + indentWithTabs(2) + indentWithSpaces(4) } kotlin { diff --git a/data/.gitignore b/data/.gitignore deleted file mode 100644 index 796b96d1c402326528b4ba3c12ee9d92d0e212e9..0000000000000000000000000000000000000000 --- a/data/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build diff --git a/data/build.gradle.kts b/data/build.gradle.kts deleted file mode 100644 index a033c6bae2d157cfd701b513eee1b061a3de92ea..0000000000000000000000000000000000000000 --- a/data/build.gradle.kts +++ /dev/null @@ -1,52 +0,0 @@ -@file:Suppress("UnstableApiUsage", "DSL_SCOPE_VIOLATION") - -import foundation.e.blisslauncher.buildsrc.Versions - -plugins { - alias(libs.plugins.android.library) - alias(libs.plugins.kotlin.android) - alias(libs.plugins.kotlin.kapt) -} - -android { - namespace = "foundation.e.blisslauncher.data" - compileSdk = Versions.COMPILE_SDK - - defaultConfig { - minSdk = Versions.MIN_SDK - - testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" - consumerProguardFiles("consumer-rules.pro") - } - - compileOptions { - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 - } - - testOptions { - unitTests { - isIncludeAndroidResources = true - all { - it.minHeapSize = "64m" - it.maxHeapSize = "128m" - } - } - } -} - -dependencies { - implementation(fileTree(mapOf("dir" to "libs", "include" to listOf("*.jar")))) - implementation(libs.kotlin.stdlib.jdk8) - implementation(libs.androidx.appcompat) - implementation(libs.androidx.core.ktx) - - implementation(libs.androidx.room.runtime) - kapt(libs.androidx.room.compiler) - - kapt(libs.dagger.compiler) - - testImplementation(libs.junit) - testImplementation(libs.robolectric) - testImplementation(libs.mockk) -} diff --git a/data/consumer-rules.pro b/data/consumer-rules.pro deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/data/proguard-rules.pro b/data/proguard-rules.pro deleted file mode 100644 index 2f9dc5a47edc8241c18c1374b3f1fcf6396a829d..0000000000000000000000000000000000000000 --- a/data/proguard-rules.pro +++ /dev/null @@ -1,21 +0,0 @@ -# Add project specific ProGuard rules here. -# You can control the set of applied configuration files using the -# proguardFiles setting in build.gradle.kts. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} - -# Uncomment this to preserve the line number information for -# debugging stack traces. -#-keepattributes SourceFile,LineNumberTable - -# If you keep the line number information, uncomment this to -# hide the original source file name. -#-renamesourcefileattribute SourceFile diff --git a/data/src/main/AndroidManifest.xml b/data/src/main/AndroidManifest.xml deleted file mode 100644 index cc947c56799598205b8fb518f3ba95843c1bab71..0000000000000000000000000000000000000000 --- a/data/src/main/AndroidManifest.xml +++ /dev/null @@ -1 +0,0 @@ - diff --git a/data/src/main/res/values/strings.xml b/data/src/main/res/values/strings.xml deleted file mode 100644 index e4ffffe8b9df199f4fdd163f54b39e20803dbb55..0000000000000000000000000000000000000000 --- a/data/src/main/res/values/strings.xml +++ /dev/null @@ -1,3 +0,0 @@ - - Data - diff --git a/data/src/test/java/foundation/e/blisslauncher/data/ExampleUnitTest.kt b/data/src/test/java/foundation/e/blisslauncher/data/ExampleUnitTest.kt deleted file mode 100644 index eb7c58612d315b9b04063db8811d2035a1879ce2..0000000000000000000000000000000000000000 --- a/data/src/test/java/foundation/e/blisslauncher/data/ExampleUnitTest.kt +++ /dev/null @@ -1,16 +0,0 @@ -package foundation.e.blisslauncher.data - -import org.junit.Assert -import org.junit.Test - -/** - * Example local unit test, which will execute on the development machine (host). - * - * See [testing documentation](http://d.android.com/tools/testing). - */ -class ExampleUnitTest { - @Test - fun addition_isCorrect() { - Assert.assertEquals(4, 2 + 2) - } -} diff --git a/domain/.gitignore b/domain/.gitignore deleted file mode 100644 index 796b96d1c402326528b4ba3c12ee9d92d0e212e9..0000000000000000000000000000000000000000 --- a/domain/.gitignore +++ /dev/null @@ -1 +0,0 @@ -/build diff --git a/domain/build.gradle.kts b/domain/build.gradle.kts deleted file mode 100644 index 421e841d87dc62ed363adacf4524e7871a0a6809..0000000000000000000000000000000000000000 --- a/domain/build.gradle.kts +++ /dev/null @@ -1,33 +0,0 @@ -@file:Suppress("UnstableApiUsage", "DSL_SCOPE_VIOLATION") - -import foundation.e.blisslauncher.buildsrc.Versions - -plugins { - alias(libs.plugins.android.library) - alias(libs.plugins.kotlin.android) - alias(libs.plugins.kotlin.kapt) -} - -android { - namespace = "foundation.e.blisslauncher.domain" - compileSdk = Versions.COMPILE_SDK - - defaultConfig { - minSdk = Versions.MIN_SDK - targetSdk = Versions.TARGET_SDK - } - - compileOptions { - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 - } -} - -dependencies { - implementation(libs.kotlin.stdlib.jdk8) - kapt(libs.dagger.compiler) - - implementation(libs.rx.kotlin) - implementation(libs.timber) - testImplementation(libs.junit) -} diff --git a/domain/consumer-rules.pro b/domain/consumer-rules.pro deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/domain/proguard-rules.pro b/domain/proguard-rules.pro deleted file mode 100644 index 2f9dc5a47edc8241c18c1374b3f1fcf6396a829d..0000000000000000000000000000000000000000 --- a/domain/proguard-rules.pro +++ /dev/null @@ -1,21 +0,0 @@ -# Add project specific ProGuard rules here. -# You can control the set of applied configuration files using the -# proguardFiles setting in build.gradle.kts. -# -# For more details, see -# http://developer.android.com/guide/developing/tools/proguard.html - -# If your project uses WebView with JS, uncomment the following -# and specify the fully qualified class name to the JavaScript interface -# class: -#-keepclassmembers class fqcn.of.javascript.interface.for.webview { -# public *; -#} - -# Uncomment this to preserve the line number information for -# debugging stack traces. -#-keepattributes SourceFile,LineNumberTable - -# If you keep the line number information, uncomment this to -# hide the original source file name. -#-renamesourcefileattribute SourceFile diff --git a/domain/src/main/AndroidManifest.xml b/domain/src/main/AndroidManifest.xml deleted file mode 100644 index cc947c56799598205b8fb518f3ba95843c1bab71..0000000000000000000000000000000000000000 --- a/domain/src/main/AndroidManifest.xml +++ /dev/null @@ -1 +0,0 @@ - diff --git a/domain/src/main/java/foundation/e/blisslauncher/domain/executors/PostExecutionThread.kt b/domain/src/main/java/foundation/e/blisslauncher/domain/executors/PostExecutionThread.kt deleted file mode 100644 index 3a80de7b12ccf3c908da3ed340b7937b2924116a..0000000000000000000000000000000000000000 --- a/domain/src/main/java/foundation/e/blisslauncher/domain/executors/PostExecutionThread.kt +++ /dev/null @@ -1,7 +0,0 @@ -package foundation.e.blisslauncher.domain.executors - -import io.reactivex.Scheduler - -interface PostExecutionThread { - val scheduler: Scheduler -} diff --git a/domain/src/main/java/foundation/e/blisslauncher/domain/executors/ThreadExecutor.kt b/domain/src/main/java/foundation/e/blisslauncher/domain/executors/ThreadExecutor.kt deleted file mode 100644 index 8c42d0692381c2e0695a7fae8b9b8e20ad28fcf3..0000000000000000000000000000000000000000 --- a/domain/src/main/java/foundation/e/blisslauncher/domain/executors/ThreadExecutor.kt +++ /dev/null @@ -1,5 +0,0 @@ -package foundation.e.blisslauncher.domain.executors - -import java.util.concurrent.Executor - -interface ThreadExecutor : Executor diff --git a/domain/src/main/java/foundation/e/blisslauncher/domain/interactors/Interactor.kt b/domain/src/main/java/foundation/e/blisslauncher/domain/interactors/Interactor.kt deleted file mode 100644 index 341a3d9784104af58af91dc5a82943cac6b673d7..0000000000000000000000000000000000000000 --- a/domain/src/main/java/foundation/e/blisslauncher/domain/interactors/Interactor.kt +++ /dev/null @@ -1,54 +0,0 @@ -package foundation.e.blisslauncher.domain.interactors - -import foundation.e.blisslauncher.domain.executors.PostExecutionThread -import foundation.e.blisslauncher.domain.executors.ThreadExecutor -import io.reactivex.Completable -import io.reactivex.Flowable -import io.reactivex.disposables.CompositeDisposable -import io.reactivex.disposables.Disposable -import io.reactivex.rxkotlin.plusAssign -import io.reactivex.schedulers.Schedulers -import timber.log.Timber - -interface Interactor { - val threadExecutor: ThreadExecutor - val postExecutionThread: PostExecutionThread -} - -abstract class FlowableInteractor : Interactor

, Disposable { - - private val disposables: CompositeDisposable = CompositeDisposable() - - protected abstract fun buildObservable(params: P? = null): Flowable - - operator fun invoke(params: P, onNext: (next: T) -> Unit = {}, onComplete: () -> Unit = {}) { - disposables += - this.buildObservable(params) - .subscribeOn(Schedulers.from(threadExecutor)) - .observeOn(postExecutionThread.scheduler) - .subscribe(onNext, Timber::w, onComplete) - } - - override fun dispose() = disposables.dispose() - - override fun isDisposed(): Boolean = disposables.isDisposed -} - -abstract class CompletableInteractor : Interactor

, Disposable { - - private val disposables: CompositeDisposable = CompositeDisposable() - - protected abstract fun buildObservable(params: P? = null): Completable - - operator fun invoke(params: P, onComplete: () -> Unit = {}) { - disposables += - this.buildObservable(params) - .subscribeOn(Schedulers.from(threadExecutor)) - .observeOn(postExecutionThread.scheduler) - .subscribe(onComplete, Timber::w) - } - - override fun dispose() = disposables.dispose() - - override fun isDisposed(): Boolean = disposables.isDisposed -} diff --git a/domain/src/test/java/foundation/e/blisslauncher/domain/ExampleUnitTest.kt b/domain/src/test/java/foundation/e/blisslauncher/domain/ExampleUnitTest.kt deleted file mode 100644 index 16b020231987a7d0dc64e208efd2838bd06a38d7..0000000000000000000000000000000000000000 --- a/domain/src/test/java/foundation/e/blisslauncher/domain/ExampleUnitTest.kt +++ /dev/null @@ -1,16 +0,0 @@ -package foundation.e.blisslauncher.domain - -import org.junit.Assert.assertEquals -import org.junit.Test - -/** - * Example local unit test, which will execute on the development machine (host). - * - * See [testing documentation](http://d.android.com/tools/testing). - */ -class ExampleUnitTest { - @Test - fun addition_isCorrect() { - assertEquals(4, 2 + 2) - } -} diff --git a/settings.gradle.kts b/settings.gradle.kts index 1bbbd5c60436dac9395d20148429118e82664674..026c826e3d794f3d48da6deeb9af64da9a240537 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -26,6 +26,6 @@ enableFeaturePreview("VERSION_CATALOGS") enableFeaturePreview("TYPESAFE_PROJECT_ACCESSORS") -include(":app", ":data", ":domain") +include(":app") rootProject.name = "blisslauncher"