Skip to content

Commit

Permalink
More Kotlinization. (#450)
Browse files Browse the repository at this point in the history
* Make things more kotlin-ey in the Application Module.

* Went a bit overboard with the Kotlinizing - return types need to be
explicit for dagger in some places.

* It mostly doesn't matter if analytics is null, so silently skip if
that's the case.

* More auto-Kotlin conversion.

* More auto Kotlin conversion.

* Minor clean up of some imports.

Boy this code is unnecessarily complex. Why did I decide I wanted a
factory here?

* More auto-converted stuff.  Search package this time.

* More auto-kotlin conversions and some clean up.  This time the touch
code.

* Kotlinizing more utils functions.

* Restore the Java sensor smoother code for now to avoid a merge conflict.

* Converting the AnalyticsInterface to Kotlin broke the build.
Only the FDroid build, for reasons I don't understand.
Revert for now.
  • Loading branch information
jaydeetay committed Dec 30, 2021
1 parent c366e2c commit 27acc12
Show file tree
Hide file tree
Showing 36 changed files with 942 additions and 1,169 deletions.
4 changes: 2 additions & 2 deletions app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -85,10 +85,12 @@ android {
dependencies {
implementation project(path: ':datamodel')

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

// Android support
implementation 'androidx.appcompat:appcompat:1.4.0'
implementation 'androidx.preference:preference:1.1.1'
implementation "androidx.core:core-ktx:1.7.0"

// Third-party
implementation 'com.google.guava:guava:30.1.1-jre'
Expand Down Expand Up @@ -121,8 +123,6 @@ dependencies {
androidTestImplementation 'org.hamcrest:hamcrest-library:1.3'
// Optional -- UI testing with Espresso
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation "androidx.core:core-ktx:1.7.0"
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
// Optional -- UI testing with UI Automator
// androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
}
68 changes: 16 additions & 52 deletions app/src/main/java/com/google/android/stardroid/ApplicationModule.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import android.hardware.SensorManager
import android.location.LocationManager
import android.net.ConnectivityManager
import android.util.Log
import androidx.core.content.ContextCompat
import androidx.core.content.getSystemService
import androidx.preference.PreferenceManager
import com.google.android.stardroid.control.*
import com.google.android.stardroid.layers.*
Expand All @@ -18,7 +18,6 @@ import com.google.android.stardroid.util.AnalyticsInterface
import com.google.android.stardroid.util.MiscUtil.getTag
import dagger.Module
import dagger.Provides
import java.util.concurrent.ExecutorService
import java.util.concurrent.ScheduledThreadPoolExecutor
import javax.inject.Named
import javax.inject.Singleton
Expand All @@ -28,96 +27,66 @@ import javax.inject.Singleton
* Created by johntaylor on 3/26/16.
*/
@Module
class ApplicationModule(app: StardroidApplication) {
private val app: StardroidApplication
class ApplicationModule(private val app: StardroidApplication) {

@Provides
@Singleton
fun provideApplication(): StardroidApplication {
return app
}
fun provideApplication() = app

@Provides
fun provideContext(): Context {
return app
}
fun provideContext(): Context = app

@Provides
@Singleton
fun provideSharedPreferences(): SharedPreferences {
Log.d(TAG, "Providing shared preferences")
return PreferenceManager.getDefaultSharedPreferences(app)
}
fun provideSharedPreferences() = PreferenceManager.getDefaultSharedPreferences(app)

@Provides
@Singleton
fun provideLocationManager(): LocationManager? {
return ContextCompat.getSystemService(app, LocationManager::class.java)
}
fun provideLocationManager() = app.getSystemService<LocationManager>()

@Provides
@Singleton
fun provideAstronomerModel(
@Named("zero") magneticDeclinationCalculator: MagneticDeclinationCalculator
): AstronomerModel {
return AstronomerModelImpl(magneticDeclinationCalculator)
}
): AstronomerModel = AstronomerModelImpl(magneticDeclinationCalculator)

@Provides
@Singleton
@Named("zero")
fun provideDefaultMagneticDeclinationCalculator(): MagneticDeclinationCalculator {
return ZeroMagneticDeclinationCalculator()
}
fun provideDefaultMagneticDeclinationCalculator(): MagneticDeclinationCalculator = ZeroMagneticDeclinationCalculator()

@Provides
@Singleton
@Named("real")
fun provideRealMagneticDeclinationCalculator(): MagneticDeclinationCalculator {
return RealMagneticDeclinationCalculator()
}
fun provideRealMagneticDeclinationCalculator(): MagneticDeclinationCalculator = RealMagneticDeclinationCalculator()

@Provides
@Singleton
fun provideAnalytics(analytics: Analytics): AnalyticsInterface {
return analytics
}
fun provideAnalytics(analytics: Analytics): AnalyticsInterface = analytics

@Provides
@Singleton
fun provideBackgroundExecutor(): ExecutorService {
return ScheduledThreadPoolExecutor(1)
}
fun provideBackgroundExecutor() = ScheduledThreadPoolExecutor(1)

@Provides
@Singleton
fun provideAssetManager(): AssetManager {
return app.assets
}
fun provideAssetManager() = app.assets

@Provides
@Singleton
fun provideResources(): Resources {
return app.resources
}
fun provideResources() = app.resources

@Provides
@Singleton
fun provideSensorManager(): SensorManager? {
return ContextCompat.getSystemService(app, SensorManager::class.java)
}
fun provideSensorManager() = app.getSystemService<SensorManager>()

@Provides
@Singleton
fun provideConnectivityManager(): ConnectivityManager? {
return ContextCompat.getSystemService(app, ConnectivityManager::class.java)
}
fun provideConnectivityManager() = app.getSystemService<ConnectivityManager>()

@Provides
@Singleton
fun provideAccountManager(context: Context): AccountManager {
return AccountManager.get(context)
}
fun provideAccountManager(context: Context) = AccountManager.get(context)

@Provides
@Singleton
Expand Down Expand Up @@ -145,9 +114,4 @@ class ApplicationModule(app: StardroidApplication) {
companion object {
private val TAG = getTag(ApplicationModule::class.java)
}

init {
Log.d(TAG, "Creating application module for $app")
this.app = app
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import android.util.Log
import androidx.core.content.pm.PackageInfoCompat
import androidx.preference.PreferenceManager
import com.google.android.stardroid.layers.LayerManager
import com.google.android.stardroid.util.Analytics
import com.google.android.stardroid.util.AnalyticsInterface
import com.google.android.stardroid.util.MiscUtil.getTag
import com.google.android.stardroid.util.PreferenceChangeAnalyticsTracker
Expand Down Expand Up @@ -89,11 +88,11 @@ class StardroidApplication : Application() {
}

private fun setUpAnalytics(versionName: String) {
analytics!!.setEnabled(preferences!!.getBoolean(Analytics.PREF_KEY, true))
(analytics ?: return).setEnabled((preferences ?: return).getBoolean(AnalyticsInterface.PREF_KEY, true))

// Ugly hack since this isn't injectable
PreferencesButton.setAnalytics(analytics)
var previousVersion = preferences!!.getString(PREVIOUS_APP_VERSION_PREF, NONE)
var previousVersion = preferences?.getString(PREVIOUS_APP_VERSION_PREF, NONE)
var newUser = false
if (previousVersion == NONE) {
// It's possible a previous version exists, it's just that it wasn't a recent enough
Expand All @@ -108,8 +107,8 @@ class StardroidApplication : Application() {
newUser = true
}
}
analytics!!.setUserProperty(AnalyticsInterface.NEW_USER, java.lang.Boolean.toString(newUser))
preferences!!.edit().putString(PREVIOUS_APP_VERSION_PREF, versionName).commit()
analytics?.setUserProperty(AnalyticsInterface.NEW_USER, java.lang.Boolean.toString(newUser))
preferences!!.edit().putString(PREVIOUS_APP_VERSION_PREF, versionName).apply()
if (previousVersion != versionName) {
// It's either an upgrade or a new installation
Log.d(TAG, "New installation: version $versionName")
Expand All @@ -118,14 +117,14 @@ class StardroidApplication : Application() {

// It will be interesting to see *when* people use Sky Map.
val b = Bundle()
b.putInt(Analytics.START_EVENT_HOUR, Calendar.getInstance()[Calendar.HOUR_OF_DAY])
analytics!!.trackEvent(Analytics.START_EVENT, b)
b.putInt(AnalyticsInterface.START_EVENT_HOUR, Calendar.getInstance()[Calendar.HOUR_OF_DAY])
analytics?.trackEvent(AnalyticsInterface.START_EVENT, b)
preferences!!.registerOnSharedPreferenceChangeListener(preferenceChangeAnalyticsTracker)
}

override fun onTerminate() {
super.onTerminate()
analytics!!.setEnabled(false)
analytics?.setEnabled(false)
}// TODO(jontayler): update to use the info created by gradle.

/**
Expand Down Expand Up @@ -166,27 +165,27 @@ class StardroidApplication : Application() {
private fun performFeatureCheck() {
if (sensorManager == null) {
Log.e(TAG, "No sensor manager")
analytics!!.setUserProperty(Analytics.DEVICE_SENSORS, Analytics.DEVICE_SENSORS_NONE)
analytics?.setUserProperty(AnalyticsInterface.DEVICE_SENSORS, AnalyticsInterface.DEVICE_SENSORS_NONE)
return
}
// Reported available sensors
val reportedSensors: MutableList<String?> = ArrayList()
val reportedSensors: MutableList<String> = ArrayList()
if (hasDefaultSensor(Sensor.TYPE_ACCELEROMETER)) {
reportedSensors.add(Analytics.DEVICE_SENSORS_ACCELEROMETER)
reportedSensors.add(AnalyticsInterface.DEVICE_SENSORS_ACCELEROMETER)
}
if (hasDefaultSensor(Sensor.TYPE_GYROSCOPE)) {
reportedSensors.add(Analytics.DEVICE_SENSORS_GYRO)
reportedSensors.add(AnalyticsInterface.DEVICE_SENSORS_GYRO)
}
if (hasDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD)) {
reportedSensors.add(Analytics.DEVICE_SENSORS_MAGNETIC)
reportedSensors.add(AnalyticsInterface.DEVICE_SENSORS_MAGNETIC)
}
if (hasDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)) {
reportedSensors.add(Analytics.DEVICE_SENSORS_ROTATION)
reportedSensors.add(AnalyticsInterface.DEVICE_SENSORS_ROTATION)
}

// TODO: Change to String.join once we're at API > 26
analytics!!.setUserProperty(
Analytics.DEVICE_SENSORS, TextUtils.join("|", reportedSensors)
analytics?.setUserProperty(
AnalyticsInterface.DEVICE_SENSORS, TextUtils.join("|", reportedSensors)
)

// Check for a particularly strange combo - it would be weird to have a rotation sensor
Expand Down Expand Up @@ -216,9 +215,9 @@ class StardroidApplication : Application() {

// Lastly a dump of all the sensors.
Log.d(TAG, "All sensors:")
val allSensors = sensorManager!!.getSensorList(Sensor.TYPE_ALL)
val allSensors = sensorManager?.getSensorList(Sensor.TYPE_ALL)
val sensorTypes: MutableSet<String> = HashSet()
for (sensor in allSensors) {
for (sensor in allSensors?: emptyList()) {
Log.i(TAG, sensor.name)
sensorTypes.add(getSafeNameForSensor(sensor))
}
Expand All @@ -229,10 +228,7 @@ class StardroidApplication : Application() {
}

private fun hasDefaultSensor(sensorType: Int): Boolean {
if (sensorManager == null) {
return false
}
val sensor = sensorManager!!.getDefaultSensor(sensorType) ?: return false
val sensor = sensorManager?.getDefaultSensor(sensorType) ?: return false
val dummy: SensorEventListener = object : SensorEventListener {
override fun onSensorChanged(event: SensorEvent) {
// Nothing
Expand All @@ -242,13 +238,13 @@ class StardroidApplication : Application() {
// Nothing
}
}
val success = sensorManager!!.registerListener(
val success = sensorManager?.registerListener(
dummy, sensor, SensorManager.SENSOR_DELAY_UI
)
) ?: false
if (!success) {
analytics!!.setUserProperty(Analytics.SENSOR_LIAR, "true")
analytics?.setUserProperty(AnalyticsInterface.SENSOR_LIAR, "true")
}
sensorManager!!.unregisterListener(dummy)
sensorManager?.unregisterListener(dummy)
return success
}

Expand All @@ -263,11 +259,7 @@ class StardroidApplication : Application() {
* on the supported OS level along with some context.
*/
fun getSafeNameForSensor(sensor: Sensor): String {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
"Sensor type: " + sensor.stringType + ": " + sensor.type
} else {
"Sensor type: " + sensor.type
}
return "Sensor type: ${sensor.stringType}: ${sensor.type}"
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
import com.google.android.stardroid.touch.GestureInterpreter;
import com.google.android.stardroid.touch.MapMover;
import com.google.android.stardroid.util.Analytics;
import com.google.android.stardroid.util.AnalyticsInterface;
import com.google.android.stardroid.util.MiscUtil;
import com.google.android.stardroid.util.SensorAccuracyMonitor;
import com.google.android.stardroid.views.ButtonLayerView;
Expand Down Expand Up @@ -618,9 +619,9 @@ private void doSearchWithIntent(Intent searchIntent) {
Log.d(TAG, "Query string " + queryString);
List<SearchResult> results = layerManager.searchByObjectName(queryString);
Bundle b = new Bundle();
b.putString(Analytics.SEARCH_TERM, queryString);
b.putBoolean(Analytics.SEARCH_SUCCESS, results.size() > 0);
analytics.trackEvent(Analytics.SEARCH_EVENT, b);
b.putString(AnalyticsInterface.SEARCH_TERM, queryString);
b.putBoolean(AnalyticsInterface.SEARCH_SUCCESS, results.size() > 0);
analytics.trackEvent(AnalyticsInterface.SEARCH_EVENT, b);
if (results.isEmpty()) {
Log.d(TAG, "No results returned");
noSearchResultsDialogFragment.show(fragmentManager, "No Search Results");
Expand All @@ -630,7 +631,7 @@ private void doSearchWithIntent(Intent searchIntent) {
} else {
Log.d(TAG, "One result returned.");
final SearchResult result = results.get(0);
activateSearchTarget(result.coords(), result.capitalizedName);
activateSearchTarget(result.coords(), result.getCapitalizedName());
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,9 @@ protected void onCreate(Bundle icicle) {
List<GalleryImage> galleryImages = GalleryFactory.getGallery(getResources()).getGalleryImages();
selectedImage = galleryImages.get(position);
ImageView imageView = (ImageView) findViewById(R.id.gallery_image);
imageView.setImageResource(selectedImage.imageId);
imageView.setImageResource(selectedImage.getImageId());
TextView label = (TextView) findViewById(R.id.gallery_image_title);
label.setText(selectedImage.name);
label.setText(selectedImage.getName());
Button backButton = (Button) findViewById(R.id.gallery_image_back_btn);
backButton.setOnClickListener(this::goBack);
Button searchButton = (Button) findViewById(R.id.gallery_image_search_btn);
Expand Down Expand Up @@ -117,7 +117,7 @@ public void doSearch(View source) {

Intent queryIntent = new Intent();
queryIntent.setAction(Intent.ACTION_SEARCH);
queryIntent.putExtra(SearchManager.QUERY, selectedImage.searchTerm);
queryIntent.putExtra(SearchManager.QUERY, selectedImage.getSearchTerm());
queryIntent.setClass(ImageDisplayActivity.this, DynamicStarMapActivity.class);
startActivity(queryIntent);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,9 @@ public View getView(int position, View convertView, ViewGroup parent) {
}
GalleryImage galleryImage = galleryImages.get(position);
ImageView imageView = (ImageView) imagePanel.findViewById(R.id.image_gallery_image);
imageView.setImageResource(galleryImage.imageId);
imageView.setImageResource(galleryImage.getImageId());
TextView imageLabel = (TextView) imagePanel.findViewById(R.id.image_gallery_title);
imageLabel.setText(galleryImage.name);
imageLabel.setText(galleryImage.getName());
return imagePanel;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public void onClick(DialogInterface dialog, int whichButton) {
Log.d(TAG, "Many search results Dialog closed with cancel");
} else {
final SearchResult item = multipleSearchResultsAdaptor.getItem(whichButton);
parentActivity.activateSearchTarget(item.coords(), item.capitalizedName);
parentActivity.activateSearchTarget(item.coords(), item.getCapitalizedName());
}
dialog.dismiss();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,13 @@
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.android.stardroid.gallery;

import java.util.List;
package com.google.android.stardroid.gallery

/**
* A Gallery contains a list of images.
*
* @author John Taylor
*/
public interface Gallery {
List<GalleryImage> getGalleryImages();
}
interface Gallery {
val galleryImages: List<GalleryImage>
}
Loading

0 comments on commit 27acc12

Please sign in to comment.