diff --git a/app/build.gradle b/app/build.gradle index fa2ec3e..c6ad3d9 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,152 +1,150 @@ apply plugin: 'kotlin-kapt' apply plugin: 'kotlin-android' apply plugin: 'com.android.application' android { compileSdk 34 namespace "it.reyboz.bustorino" defaultConfig { applicationId "it.reyboz.bustorino" minSdkVersion 21 targetSdkVersion 34 buildToolsVersion = '34.0.0' versionCode 62 versionName "2.3.1" vectorDrawables.useSupportLibrary = true multiDexEnabled true javaCompileOptions { annotationProcessorOptions { arguments = ["room.schemaLocation": "$projectDir/assets/schemas/".toString()] } } testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" } testOptions { unitTests.returnDefaultValues = true } sourceSets { androidTest.assets.srcDirs += files("$projectDir/assets/schemas/".toString()) } buildTypes { debug { applicationIdSuffix ".debug" versionNameSuffix "-dev" } gitpull{ applicationIdSuffix ".gitdev" versionNameSuffix "-gitdev" } } repositories { mavenCentral() mavenLocal() } dependencies { //new libraries } compileOptions { sourceCompatibility JavaVersion.VERSION_17 targetCompatibility JavaVersion.VERSION_17 } kotlin { jvmToolchain 17 } lint { abortOnError false } androidResources { generateLocaleConfig true } } dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" api "org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version" api "org.jetbrains.kotlinx:kotlinx-coroutines-android:$coroutines_version" implementation 'androidx.legacy:legacy-support-v4:1.0.0' // Guava implementation for DBUpdateWorker implementation 'com.google.guava:guava:29.0-android' implementation "androidx.fragment:fragment-ktx:$fragment_version" implementation "androidx.activity:activity:$activity_version" implementation "androidx.annotation:annotation:1.6.0" implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0" implementation "androidx.appcompat:appcompat:$appcompat_version" implementation "androidx.appcompat:appcompat-resources:$appcompat_version" implementation "androidx.preference:preference:$preference_version" implementation "androidx.work:work-runtime:$work_version" implementation "androidx.work:work-runtime-ktx:$work_version" implementation "com.google.android.material:material:1.11.0" implementation 'androidx.constraintlayout:constraintlayout:2.1.4' implementation "androidx.coordinatorlayout:coordinatorlayout:1.2.0" implementation 'org.jsoup:jsoup:1.15.3' implementation 'com.readystatesoftware.sqliteasset:sqliteassethelper:2.0.1' implementation 'com.android.volley:volley:1.2.1' - - implementation 'org.osmdroid:osmdroid-android:6.1.18' //maplibre implementation 'org.maplibre.gl:android-sdk:11.8.6' implementation 'org.maplibre.gl:android-sdk-turf:6.0.1' implementation 'org.maplibre.gl:android-plugin-annotation-v9:3.0.2' // remember to enable maven repo jitpack.io when wanting to use osmbonuspack //implementation 'com.github.MKergall:osmbonuspack:6.9.0' // ACRA implementation "ch.acra:acra-mail:$acra_version" implementation "ch.acra:acra-dialog:$acra_version" // google transit realtime implementation 'com.google.protobuf:protobuf-java:3.19.6' // mqtt library implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.5' implementation 'com.github.fabmazz:paho.mqtt.android:v1.0.0' // ViewModel implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version" // LiveData implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version" // Lifecycles only (without ViewModel or LiveData) implementation "androidx.lifecycle:lifecycle-runtime-ktx:$lifecycle_version" // Legacy implementation 'androidx.legacy:legacy-support-v4:1.0.0' // Room components implementation "androidx.room:room-runtime:$room_version" implementation "androidx.room:room-ktx:$room_version" kapt "androidx.room:room-compiler:$room_version" //multidex - we need this to build the app implementation "androidx.multidex:multidex:$multidex_version" implementation 'de.siegmar:fastcsv:2.2.2' testImplementation 'junit:junit:4.12' implementation 'junit:junit:4.12' implementation "androidx.test.ext:junit:1.1.5" implementation "androidx.test:core:$androidXTestVersion" implementation "androidx.test:runner:$androidXTestVersion" implementation "androidx.room:room-testing:$room_version" androidTestImplementation "androidx.test.ext:junit:1.1.5" androidTestImplementation "androidx.test:core:$androidXTestVersion" androidTestImplementation "androidx.test:runner:$androidXTestVersion" androidTestImplementation "androidx.test:rules:$androidXTestVersion" androidTestImplementation "androidx.room:room-testing:$room_version" } diff --git a/app/src/main/java/it/reyboz/bustorino/ActivityPrincipal.java b/app/src/main/java/it/reyboz/bustorino/ActivityPrincipal.java index 8d7bb5a..5a2b518 100644 --- a/app/src/main/java/it/reyboz/bustorino/ActivityPrincipal.java +++ b/app/src/main/java/it/reyboz/bustorino/ActivityPrincipal.java @@ -1,809 +1,809 @@ /* BusTO - Arrival times for Turin public transport. Copyright (C) 2021 Fabio Mazza This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino; import android.Manifest; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.net.Uri; import android.os.Bundle; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.FrameLayout; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.widget.Toolbar; import androidx.coordinatorlayout.widget.CoordinatorLayout; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import androidx.preference.PreferenceManager; import androidx.work.WorkInfo; import androidx.work.WorkManager; import com.google.android.material.navigation.NavigationView; import com.google.android.material.snackbar.Snackbar; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import it.reyboz.bustorino.backend.Stop; import it.reyboz.bustorino.backend.utils; import it.reyboz.bustorino.data.DBUpdateWorker; import it.reyboz.bustorino.data.DatabaseUpdate; import it.reyboz.bustorino.data.PreferencesHolder; import it.reyboz.bustorino.data.gtfs.GtfsDatabase; import it.reyboz.bustorino.fragments.*; import it.reyboz.bustorino.middleware.GeneralActivity; import static it.reyboz.bustorino.backend.utils.getBusStopIDFromUri; import static it.reyboz.bustorino.backend.utils.openIceweasel; public class ActivityPrincipal extends GeneralActivity implements FragmentListenerMain { private DrawerLayout mDrawer; private NavigationView mNavView; private ActionBarDrawerToggle drawerToggle; private final static String DEBUG_TAG="BusTO Act Principal"; private final static String TAG_FAVORITES="favorites_frag"; private Snackbar snackbar; private boolean showingMainFragmentFromOther = false; private boolean onCreateComplete = false; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(DEBUG_TAG, "onCreate, savedInstanceState is: "+savedInstanceState); setContentView(R.layout.activity_principal); boolean showingArrivalsFromIntent = false; Toolbar mToolbar = findViewById(R.id.default_toolbar); setSupportActionBar(mToolbar); if (getSupportActionBar()!=null) getSupportActionBar().setDisplayHomeAsUpEnabled(true); else Log.w(DEBUG_TAG, "NO ACTION BAR"); mToolbar.setOnMenuItemClickListener(new ToolbarItemClickListener(this)); mDrawer = findViewById(R.id.drawer_layout); drawerToggle = setupDrawerToggle(mToolbar); // Setup toggle to display hamburger icon with nice animation drawerToggle.setDrawerIndicatorEnabled(true); drawerToggle.syncState(); mDrawer.addDrawerListener(drawerToggle); mDrawer.addDrawerListener(new DrawerLayout.DrawerListener() { @Override public void onDrawerSlide(@NonNull View drawerView, float slideOffset) { } @Override public void onDrawerOpened(@NonNull View drawerView) { hideKeyboard(); } @Override public void onDrawerClosed(@NonNull View drawerView) { } @Override public void onDrawerStateChanged(int newState) { } }); mNavView = findViewById(R.id.nvView); setupDrawerContent(mNavView); /*View header = mNavView.getHeaderView(0); */ //mNavView.getMenu().findItem(R.id.versionFooter). /// LEGACY CODE //---------------------------- START INTENT CHECK QUEUE ------------------------------------ // Intercept calls from URL intent boolean tryedFromIntent = false; String busStopID = null; Uri data = getIntent().getData(); if (data != null) { busStopID = getBusStopIDFromUri(data); Log.d(DEBUG_TAG, "Opening Intent: busStopID: "+busStopID); tryedFromIntent = true; } // Intercept calls from other activities if (!tryedFromIntent) { Bundle b = getIntent().getExtras(); if (b != null) { busStopID = b.getString("bus-stop-ID"); /* * I'm not very sure if you are coming from an Intent. * Some launchers work in strange ways. */ tryedFromIntent = busStopID != null; } } //---------------------------- END INTENT CHECK QUEUE -------------------------------------- if (busStopID == null) { // Show keyboard if can't start from intent // JUST DON'T // showKeyboard(); // You haven't obtained anything... from an intent? if (tryedFromIntent) { // This shows a luser warning Toast.makeText(getApplicationContext(), R.string.insert_bus_stop_number_error, Toast.LENGTH_SHORT).show(); } } else { // If you are here an intent has worked successfully //setBusStopSearchByIDEditText(busStopID); //Log.d(DEBUG_TAG, "Requesting arrivals for stop "+busStopID+" from intent"); requestArrivalsForStopID(busStopID); //this shows the fragment, too showingArrivalsFromIntent = true; } //database check GtfsDatabase gtfsDB = GtfsDatabase.Companion.getGtfsDatabase(this); final int db_version = gtfsDB.getOpenHelper().getReadableDatabase().getVersion(); boolean dataUpdateRequested = false; final SharedPreferences theShPr = getMainSharedPreferences(); final int old_version = PreferencesHolder.getGtfsDBVersion(theShPr); Log.d(DEBUG_TAG, "GTFS Database: old version is "+old_version+ ", new version is "+db_version); if (old_version < db_version){ //decide update conditions in the future if(old_version < 2 && db_version >= 2) { dataUpdateRequested = true; DatabaseUpdate.requestDBUpdateWithWork(this, true, true); } PreferencesHolder.setGtfsDBVersion(theShPr, db_version); } //Try (hopefully) database update if(!dataUpdateRequested) DatabaseUpdate.requestDBUpdateWithWork(this, false, false); /* Watch for database update */ final WorkManager workManager = WorkManager.getInstance(this); workManager.getWorkInfosForUniqueWorkLiveData(DBUpdateWorker.DEBUG_TAG) .observe(this, workInfoList -> { // If there are no matching work info, do nothing if (workInfoList == null || workInfoList.isEmpty()) { return; } Log.d(DEBUG_TAG, "WorkerInfo: "+workInfoList); boolean showProgress = false; for (WorkInfo workInfo : workInfoList) { if (workInfo.getState() == WorkInfo.State.RUNNING) { showProgress = true; break; } } if (showProgress) { createDefaultSnackbar(); } else { if(snackbar!=null) { snackbar.dismiss(); snackbar = null; } } }); // show the main fragment Fragment f = getSupportFragmentManager().findFragmentById(R.id.mainActContentFrame); Log.d(DEBUG_TAG, "OnCreate the fragment is "+f); String vl = PreferenceManager.getDefaultSharedPreferences(this).getString(SettingsFragment.PREF_KEY_STARTUP_SCREEN, ""); //if (vl.length() == 0 || vl.equals("arrivals")) { // showMainFragment(); Log.d(DEBUG_TAG, "The default screen to open is: "+vl); if (showingArrivalsFromIntent){ //do nothing but exclude a case }else if (savedInstanceState==null) { //we are not restarting the activity from nothing if (vl.equals("map")) { requestMapFragment(false); } else if (vl.equals("favorites")) { checkAndShowFavoritesFragment(getSupportFragmentManager(), false); } else if (vl.equals("lines")) { showLinesFragment(getSupportFragmentManager(), false, null); } else { showMainFragment(false); } } onCreateComplete = true; //last but not least, set the good default values setDefaultSettingsValuesWhenMissing(); //check if first run activity (IntroActivity) has been started once or not boolean hasIntroRun = theShPr.getBoolean(PreferencesHolder.PREF_INTRO_ACTIVITY_RUN,false); if(!hasIntroRun){ startIntroductionActivity(); } } private ActionBarDrawerToggle setupDrawerToggle(Toolbar toolbar) { // NOTE: Make sure you pass in a valid toolbar reference. ActionBarDrawToggle() does not require it // and will not render the hamburger icon without it. return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close); } /** * Setup drawer actions * @param navigationView the navigation view on which to set the callbacks */ private void setupDrawerContent(NavigationView navigationView) { navigationView.setNavigationItemSelectedListener( menuItem -> { if (menuItem.getItemId() == R.id.drawer_action_settings) { Log.d("MAINBusTO", "Pressed button preferences"); closeDrawerIfOpen(); startActivity(new Intent(ActivityPrincipal.this, ActivitySettings.class)); return true; } else if(menuItem.getItemId() == R.id.nav_favorites_item){ closeDrawerIfOpen(); //get Fragment checkAndShowFavoritesFragment(getSupportFragmentManager(), true); return true; } else if(menuItem.getItemId() == R.id.nav_arrivals){ closeDrawerIfOpen(); showMainFragment(true); return true; } else if(menuItem.getItemId() == R.id.nav_map_item){ closeDrawerIfOpen(); requestMapFragment(true); return true; } else if (menuItem.getItemId() == R.id.nav_lines_item) { closeDrawerIfOpen(); showLinesFragment(getSupportFragmentManager(), true,null); return true; } else if(menuItem.getItemId() == R.id.drawer_action_info) { closeDrawerIfOpen(); startActivity(new Intent(ActivityPrincipal.this, ActivityAbout.class)); return true; } //selectDrawerItem(menuItem); Log.d(DEBUG_TAG, "pressed item "+menuItem); return true; }); } private void closeDrawerIfOpen(){ if (mDrawer.isDrawerOpen(GravityCompat.START)) mDrawer.closeDrawer(GravityCompat.START); } // `onPostCreate` called when activity start-up is complete after `onStart()` // NOTE 1: Make sure to override the method with only a single `Bundle` argument // Note 2: Make sure you implement the correct `onPostCreate(Bundle savedInstanceState)` method. // There are 2 signatures and only `onPostCreate(Bundle state)` shows the hamburger icon. @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. drawerToggle.syncState(); } @Override public void onConfigurationChanged(@NonNull Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggles drawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.principal_menu, menu); MenuItem experimentsMenuItem = menu.findItem(R.id.action_experiments); SharedPreferences shPr = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); boolean exper_On = shPr.getBoolean(getString(R.string.pref_key_experimental), false); experimentsMenuItem.setVisible(exper_On); return super.onCreateOptionsMenu(menu); } //requesting permissions @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode==STORAGE_PERMISSION_REQ){ final String storagePerm = Manifest.permission.WRITE_EXTERNAL_STORAGE; if (permissionDoneRunnables.containsKey(storagePerm)) { Runnable toRun = permissionDoneRunnables.get(storagePerm); if (toRun != null) toRun.run(); permissionDoneRunnables.remove(storagePerm); } if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.d(DEBUG_TAG, "Permissions check: " + Arrays.toString(permissions)); if (permissionDoneRunnables.containsKey(storagePerm)) { Runnable toRun = permissionDoneRunnables.get(storagePerm); if (toRun != null) toRun.run(); permissionDoneRunnables.remove(storagePerm); } } else { //permission denied showToastMessage(R.string.permission_storage_maps_msg, false); } } } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { int[] cases = {R.id.nav_arrivals, R.id.nav_favorites_item}; Log.d(DEBUG_TAG, "Item pressed"); if (item.getItemId() == android.R.id.home) { mDrawer.openDrawer(GravityCompat.START); return true; } if (drawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { boolean foundFragment = false; Fragment shownFrag = getSupportFragmentManager().findFragmentById(R.id.mainActContentFrame); if (mDrawer.isDrawerOpen(GravityCompat.START)) mDrawer.closeDrawer(GravityCompat.START); else if(shownFrag != null && shownFrag.isVisible() && shownFrag.getChildFragmentManager().getBackStackEntryCount() > 0){ //if we have been asked to show a stop from another fragment, we should go back even in the main if(shownFrag instanceof MainScreenFragment){ //we have to stop the arrivals reload ((MainScreenFragment) shownFrag).cancelReloadArrivalsIfNeeded(); } shownFrag.getChildFragmentManager().popBackStack(); if(showingMainFragmentFromOther && getSupportFragmentManager().getBackStackEntryCount() > 0){ getSupportFragmentManager().popBackStack(); Log.d(DEBUG_TAG, "Popping main back stack also"); } } else if (getSupportFragmentManager().getBackStackEntryCount() > 0) { getSupportFragmentManager().popBackStack(); Log.d(DEBUG_TAG, "Popping main frame backstack for fragments"); } else super.onBackPressed(); } /** * Create and show the SnackBar with the message */ private void createDefaultSnackbar() { View baseView = null; boolean showSnackbar = true; final Fragment frag = getSupportFragmentManager().findFragmentById(R.id.mainActContentFrame); if (frag instanceof ScreenBaseFragment){ baseView = ((ScreenBaseFragment) frag).getBaseViewForSnackBar(); showSnackbar = ((ScreenBaseFragment) frag).showSnackbarOnDBUpdate(); } if (baseView == null) baseView = findViewById(R.id.mainActContentFrame); //if (baseView == null) Log.e(DEBUG_TAG, "baseView null for default snackbar, probably exploding now"); if (baseView !=null && showSnackbar) { this.snackbar = Snackbar.make(baseView, R.string.database_update_msg_inapp, Snackbar.LENGTH_INDEFINITE); if (frag instanceof ScreenBaseFragment){ ((ScreenBaseFragment) frag).setSnackbarPropertiesBeforeShowing(this.snackbar); } this.snackbar.show(); } else{ Log.e(DEBUG_TAG, "Asked to show the snackbar but the baseView is null"); } } /** * Show the fragment by adding it to the backstack * @param fraMan the fragmentManager * @param fragment the fragment */ private static void showMainFragment(FragmentManager fraMan, MainScreenFragment fragment, boolean addToBackStack){ FragmentTransaction ft = fraMan.beginTransaction() .replace(R.id.mainActContentFrame, fragment, MainScreenFragment.FRAGMENT_TAG) .setReorderingAllowed(false) /*.setCustomAnimations( R.anim.slide_in, // enter R.anim.fade_out, // exit R.anim.fade_in, // popEnter R.anim.slide_out // popExit )*/ .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); if (addToBackStack) ft.addToBackStack(null); ft.commit(); } /** * Show the fragment by adding it to the backstack * @param fraMan the fragmentManager * @param arguments args for the fragment */ private static void createShowMainFragment(FragmentManager fraMan,@Nullable Bundle arguments, boolean addToBackStack){ FragmentTransaction ft = fraMan.beginTransaction() .replace(R.id.mainActContentFrame, MainScreenFragment.class, arguments, MainScreenFragment.FRAGMENT_TAG) .setReorderingAllowed(false) /*.setCustomAnimations( R.anim.slide_in, // enter R.anim.fade_out, // exit R.anim.fade_in, // popEnter R.anim.slide_out // popExit )*/ .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); if (addToBackStack) ft.addToBackStack(null); ft.commit(); } private void requestMapFragment(final boolean allowReturn){ // starting from Android 11, we don't need to have the STORAGE permission anymore for the map cache /*if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.R){ //nothing to do Log.d(DEBUG_TAG, "Build codes allow the showing of the map"); createAndShowMapFragment(null, allowReturn); return; } final String permission = Manifest.permission.WRITE_EXTERNAL_STORAGE; int result = askForPermissionIfNeeded(permission, STORAGE_PERMISSION_REQ); Log.d(DEBUG_TAG, "Permission for storage: "+result); switch (result) { case PERMISSION_OK: createAndShowMapFragment(null, allowReturn); break; case PERMISSION_ASKING: permissionDoneRunnables.put(permission, () -> createAndShowMapFragment(null, allowReturn)); break; case PERMISSION_NEG_CANNOT_ASK: String storage_perm = getString(R.string.storage_permission); String text = getString(R.string.too_many_permission_asks, storage_perm); Toast.makeText(getApplicationContext(),text, Toast.LENGTH_LONG).show(); } */ //The permissions are handled in the MapLibreFragment instead createAndShowMapFragment(null, allowReturn); } private static void checkAndShowFavoritesFragment(FragmentManager fragmentManager, boolean addToBackStack){ FragmentTransaction ft = fragmentManager.beginTransaction(); Fragment fragment = fragmentManager.findFragmentByTag(TAG_FAVORITES); if(fragment!=null){ ft.replace(R.id.mainActContentFrame, fragment, TAG_FAVORITES); }else{ //use new method ft.replace(R.id.mainActContentFrame,FavoritesFragment.class,null,TAG_FAVORITES); } if (addToBackStack) ft.addToBackStack("favorites_main"); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .setReorderingAllowed(false); ft.commit(); } private static void showLinesFragment(@NonNull FragmentManager fragmentManager, boolean addToBackStack, @Nullable Bundle fragArgs){ FragmentTransaction ft = fragmentManager.beginTransaction(); Fragment f = fragmentManager.findFragmentByTag(LinesGridShowingFragment.FRAGMENT_TAG); if(f!=null){ ft.replace(R.id.mainActContentFrame, f, LinesGridShowingFragment.FRAGMENT_TAG); }else{ //use new method ft.replace(R.id.mainActContentFrame,LinesGridShowingFragment.class,fragArgs, LinesGridShowingFragment.FRAGMENT_TAG); } if (addToBackStack) ft.addToBackStack("linesGrid"); ft.setReorderingAllowed(true) .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE) .commit(); } private void showMainFragment(boolean addToBackStack){ FragmentManager fraMan = getSupportFragmentManager(); Fragment fragment = fraMan.findFragmentByTag(MainScreenFragment.FRAGMENT_TAG); final MainScreenFragment mainScreenFragment; if (fragment==null | !(fragment instanceof MainScreenFragment)){ createShowMainFragment(fraMan, null, addToBackStack); } else if(!fragment.isVisible()){ mainScreenFragment = (MainScreenFragment) fragment; showMainFragment(fraMan, mainScreenFragment, addToBackStack); Log.d(DEBUG_TAG, "Found the main fragment"); } else{ mainScreenFragment = (MainScreenFragment) fragment; } //return mainScreenFragment; } @Nullable private MainScreenFragment getMainFragmentIfVisible(){ FragmentManager fraMan = getSupportFragmentManager(); Fragment fragment = fraMan.findFragmentByTag(MainScreenFragment.FRAGMENT_TAG); if (fragment!= null && fragment.isVisible()) return (MainScreenFragment) fragment; else return null; } @Override public void showFloatingActionButton(boolean yes) { //TODO } /* public void setDrawerSelectedItem(String fragmentTag){ switch (fragmentTag){ case MainScreenFragment.FRAGMENT_TAG: mNavView.setCheckedItem(R.id.nav_arrivals); break; case MapFragment.FRAGMENT_TAG: break; case FavoritesFragment.FRAGMENT_TAG: mNavView.setCheckedItem(R.id.nav_favorites_item); break; } }*/ @Override public void readyGUIfor(FragmentKind fragmentType) { MainScreenFragment mainFragmentIfVisible = getMainFragmentIfVisible(); if (mainFragmentIfVisible!=null){ mainFragmentIfVisible.readyGUIfor(fragmentType); } int titleResId; switch (fragmentType){ case MAP: mNavView.setCheckedItem(R.id.nav_map_item); titleResId = R.string.map; break; case FAVORITES: mNavView.setCheckedItem(R.id.nav_favorites_item); titleResId = R.string.nav_favorites_text; break; case ARRIVALS: titleResId = R.string.nav_arrivals_text; mNavView.setCheckedItem(R.id.nav_arrivals); break; case STOPS: titleResId = R.string.stop_search_view_title; mNavView.setCheckedItem(R.id.nav_arrivals); break; case MAIN_SCREEN_FRAGMENT: case NEARBY_STOPS: case NEARBY_ARRIVALS: titleResId=R.string.app_name_full; mNavView.setCheckedItem(R.id.nav_arrivals); break; case LINES: titleResId=R.string.lines; mNavView.setCheckedItem(R.id.nav_lines_item); break; default: titleResId = 0; } if(getSupportActionBar()!=null && titleResId!=0) getSupportActionBar().setTitle(titleResId); } @Override public void requestArrivalsForStopID(String ID) { //register if the request came from the main fragment or not MainScreenFragment probableFragment = getMainFragmentIfVisible(); showingMainFragmentFromOther = (probableFragment==null); if (showingMainFragmentFromOther){ FragmentManager fraMan = getSupportFragmentManager(); Fragment fragment = fraMan.findFragmentByTag(MainScreenFragment.FRAGMENT_TAG); Log.d(DEBUG_TAG, "Requested main fragment, not visible. Search by TAG returned: "+fragment); if(fragment!=null){ //the fragment is there but not shown probableFragment = (MainScreenFragment) fragment; // set the flag probableFragment.setSuppressArrivalsReload(true); showMainFragment(fraMan, probableFragment, true); probableFragment.requestArrivalsForStopID(ID); } else { // we have no fragment final Bundle args = new Bundle(); args.putString(MainScreenFragment.PENDING_STOP_SEARCH, ID); //if onCreate is complete, then we are not asking for the first showing fragment boolean addtobackstack = onCreateComplete; createShowMainFragment(fraMan, args ,addtobackstack); } } else { //the MainScreeFragment is shown, nothing to do probableFragment.requestArrivalsForStopID(ID); } mNavView.setCheckedItem(R.id.nav_arrivals); } @Override public void showLineOnMap(String routeGtfsId, @Nullable String stopIDFrom){ readyGUIfor(FragmentKind.LINES); FragmentTransaction tr = getSupportFragmentManager().beginTransaction(); tr.replace(R.id.mainActContentFrame, LinesDetailFragment.class, LinesDetailFragment.Companion.makeArgs(routeGtfsId, stopIDFrom)); tr.addToBackStack("LineonMap-"+routeGtfsId); tr.commit(); } @Override public void toggleSpinner(boolean state) { MainScreenFragment probableFragment = getMainFragmentIfVisible(); if (probableFragment!=null){ probableFragment.toggleSpinner(state); } } @Override public void enableRefreshLayout(boolean yes) { MainScreenFragment probableFragment = getMainFragmentIfVisible(); if (probableFragment!=null){ probableFragment.enableRefreshLayout(yes); } } @Override public void showMapCenteredOnStop(Stop stop) { createAndShowMapFragment(stop, true); } //Map Fragment stuff void createAndShowMapFragment(@Nullable Stop stop, boolean addToBackStack){ final FragmentManager fm = getSupportFragmentManager(); final FragmentTransaction ft = fm.beginTransaction(); - final MapLibreFragment fragment = MapLibreFragment.Companion.newInstance(stop); - ft.replace(R.id.mainActContentFrame, fragment, MapFragmentKt.FRAGMENT_TAG); + final MapLibreFragment fragment = MapLibreFragment.newInstance(stop); + ft.replace(R.id.mainActContentFrame, fragment, MapLibreFragment.FRAGMENT_TAG); if (addToBackStack) ft.addToBackStack(null); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ft.commit(); } void startIntroductionActivity(){ Intent intent = new Intent(ActivityPrincipal.this, ActivityIntro.class); intent.putExtra(ActivityIntro.RESTART_MAIN, false); startActivity(intent); } class ToolbarItemClickListener implements Toolbar.OnMenuItemClickListener{ private final Context activityContext; public ToolbarItemClickListener(Context activityContext) { this.activityContext = activityContext; } @Override public boolean onMenuItemClick(MenuItem item) { final int id = item.getItemId(); if(id == R.id.action_about){ startActivity(new Intent(ActivityPrincipal.this, ActivityAbout.class)); return true; } else if (id == R.id.action_hack) { openIceweasel(getString(R.string.hack_url), activityContext); return true; } else if (id == R.id.action_source){ openIceweasel("https://gitpull.it/source/libre-busto/", activityContext); return true; } else if (id == R.id.action_licence){ openIceweasel("https://www.gnu.org/licenses/gpl-3.0.html", activityContext); return true; } else if (id == R.id.action_experiments) { startActivity(new Intent(ActivityPrincipal.this, ActivityExperiments.class)); return true; } else if (id == R.id.action_tutorial) { startIntroductionActivity(); return true; } return false; } } /** * Adjust setting to match the default ones */ private void setDefaultSettingsValuesWhenMissing(){ SharedPreferences mainSharedPref = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = mainSharedPref.edit(); //Main fragment to show String screen = mainSharedPref.getString(SettingsFragment.PREF_KEY_STARTUP_SCREEN, ""); boolean edit = false; if (screen.isEmpty()){ editor.putString(SettingsFragment.PREF_KEY_STARTUP_SCREEN, "arrivals"); edit=true; } //Fetchers final Set setSelected = mainSharedPref.getStringSet(SettingsFragment.KEY_ARRIVALS_FETCHERS_USE, new HashSet<>()); if (setSelected.isEmpty()){ String[] defaultVals = getResources().getStringArray(R.array.arrivals_sources_values_default); editor.putStringSet(SettingsFragment.KEY_ARRIVALS_FETCHERS_USE, utils.convertArrayToSet(defaultVals)); edit=true; } //Live bus positions final String keySourcePositions=getString(R.string.pref_positions_source); final String positionsSource = mainSharedPref.getString(keySourcePositions, ""); if(positionsSource.isEmpty()){ String[] defaultVals = getResources().getStringArray(R.array.positions_source_values); editor.putString(keySourcePositions, defaultVals[0]); edit=true; } //Map style final String mapStylePref = mainSharedPref.getString(SettingsFragment.LIBREMAP_STYLE_PREF_KEY, ""); if(mapStylePref.isEmpty()){ final String[] defaultVals = getResources().getStringArray(R.array.map_style_pref_values); editor.putString(SettingsFragment.LIBREMAP_STYLE_PREF_KEY, defaultVals[0]); edit=true; } if (edit){ editor.commit(); } } } diff --git a/app/src/main/java/it/reyboz/bustorino/backend/GPSPoint.java b/app/src/main/java/it/reyboz/bustorino/backend/GPSPoint.java index df3c74b..2757985 100644 --- a/app/src/main/java/it/reyboz/bustorino/backend/GPSPoint.java +++ b/app/src/main/java/it/reyboz/bustorino/backend/GPSPoint.java @@ -1,34 +1,29 @@ package it.reyboz.bustorino.backend; -import org.osmdroid.api.IGeoPoint; -public class GPSPoint implements IGeoPoint { +public class GPSPoint { public final double latitude; public final double longitude; public GPSPoint(double latitude, double longitude) { this.latitude = latitude; this.longitude = longitude; } - @Override public int getLatitudeE6() { return (int) (latitude*1e6d); } - @Override public int getLongitudeE6() { return (int) (longitude*1e6d); } - @Override public double getLatitude() { return latitude; } - @Override public double getLongitude() { return longitude; } } diff --git a/app/src/main/java/it/reyboz/bustorino/backend/RealtimeVehicle.java b/app/src/main/java/it/reyboz/bustorino/backend/RealtimeVehicle.java index f7daeab..cab1bb1 100644 --- a/app/src/main/java/it/reyboz/bustorino/backend/RealtimeVehicle.java +++ b/app/src/main/java/it/reyboz/bustorino/backend/RealtimeVehicle.java @@ -1,66 +1,65 @@ package it.reyboz.bustorino.backend; -import org.osmdroid.util.GeoPoint; public class RealtimeVehicle { - private final GeoPoint location; + private final GPSPoint location; private final float bearing; public final int updateTimestamp; private final String vehicleLabel; private String routeID; - public RealtimeVehicle(GeoPoint location, float bearing, int updateTimestamp, String vehicleLabel) { + public RealtimeVehicle(GPSPoint location, float bearing, int updateTimestamp, String vehicleLabel) { this.location = location; this.bearing = bearing; this.updateTimestamp = updateTimestamp; this.vehicleLabel = vehicleLabel; } - public GeoPoint getLocation() { + public GPSPoint getLocation() { return location; } public float getBearing() { return bearing; } public String getVehicleLabel() { return vehicleLabel; } public String getRouteID() { return routeID; } public void setRouteID(String routeID) { this.routeID = routeID; } /*public enum OccupancyStatus { ABOUT(1), CODING(2), DATABASES(3); private final int value; private static final HashMap map = new HashMap<>(); private OccupancyStatus(int value) { this.value = value; } static { for (OccupancyStatus status : OccupancyStatus.values()) { map.put(status.value, status); } } public static OccupancyStatus valueOf(int status) { return map.get(status); } public int getValue() { return value; } }*/ } diff --git a/app/src/main/java/it/reyboz/bustorino/backend/Stop.java b/app/src/main/java/it/reyboz/bustorino/backend/Stop.java index 63aaee7..b7547ad 100644 --- a/app/src/main/java/it/reyboz/bustorino/backend/Stop.java +++ b/app/src/main/java/it/reyboz/bustorino/backend/Stop.java @@ -1,360 +1,360 @@ /* BusTO (backend components) Copyright (C) 2016 Ludovico Pavesi This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino.backend; import android.location.Location; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import it.reyboz.bustorino.util.LinesNameSorter; -import org.osmdroid.api.IGeoPoint; +import org.jetbrains.annotations.NotNull; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Locale; public class Stop implements Comparable { // remove "final" in case you need to set these from outside the parser\scrapers\fetchers public final @NonNull String ID; private @Nullable String name; private @Nullable String username; public @Nullable String location; public @Nullable Route.Type type; private @Nullable List routesThatStopHere; private final @Nullable Double lat; private final @Nullable Double lon; // leave this non-final private @Nullable String routesThatStopHereString = null; private @Nullable String absurdGTTPlaceName = null; // public @Nullable String gtfsID = null; /** * Hey, look, method overloading! */ public Stop(final @Nullable String name, final @NonNull String ID, @Nullable final String location, @Nullable final Route.Type type, @Nullable final List routesThatStopHere) { this.ID = ID; this.name = name; this.username = null; this.location = (location != null && location.length() == 0) ? null : location; this.type = type; this.routesThatStopHere = routesThatStopHere; this.lat = null; this.lon = null; } /** * Hey, look, method overloading! */ public Stop(final @NonNull String ID) { this.ID = ID; this.name = null; this.username = null; this.location = null; this.type = null; this.routesThatStopHere = null; this.lat = null; this.lon = null; } /** * Constructor that sets EVERYTHING. */ public Stop(@NonNull String ID, @Nullable String name, @Nullable String userName, @Nullable String location, @Nullable Route.Type type, @Nullable List routesThatStopHere, @Nullable Double lat, @Nullable Double lon, @Nullable String gtfsID) { this.ID = ID; this.name = name; this.username = userName; this.location = location; this.type = type; this.routesThatStopHere = routesThatStopHere; this.lat = lat; this.lon = lon; this.gtfsID = gtfsID; } public @Nullable String routesThatStopHereToString() { // M E M O I Z A T I O N if(this.routesThatStopHereString != null) { return this.routesThatStopHereString; } // no string yet? build it! return buildRoutesString(); } @Nullable public String getAbsurdGTTPlaceName() { return absurdGTTPlaceName; } public void setAbsurdGTTPlaceName(@NonNull String absurdGTTPlaceName) { this.absurdGTTPlaceName = absurdGTTPlaceName; } public void setRoutesThatStopHere(@Nullable List routesThatStopHere) { this.routesThatStopHere = routesThatStopHere; } protected void setRoutesThatStopHereString(String routesStopping){ this.routesThatStopHereString = routesStopping; } public int getNumRoutesStopping(){ if(this.routesThatStopHere == null) { return 0; } else { return this.routesThatStopHere.size(); } } @Nullable protected List getRoutesThatStopHere(){ return routesThatStopHere; } protected @Nullable String buildRoutesString() { // no routes => no string if(this.routesThatStopHere == null || this.routesThatStopHere.size() == 0) { return null; } StringBuilder sb = new StringBuilder(); Collections.sort(routesThatStopHere,new LinesNameSorter()); int i, lenMinusOne = routesThatStopHere.size() - 1; for (i = 0; i < lenMinusOne; i++) { sb.append(routesThatStopHere.get(i)).append(", "); } // last one: sb.append(routesThatStopHere.get(i)); this.routesThatStopHereString = sb.toString(); return this.routesThatStopHereString; } @Override public int compareTo(@NonNull Stop other) { int res; int thisAsInt = networkTools.failsafeParseInt(this.ID); int otherAsInt = networkTools.failsafeParseInt(other.ID); // numeric stop IDs if(thisAsInt != 0 && otherAsInt != 0) { return thisAsInt - otherAsInt; } else { // non-numeric res = this.ID.compareTo(other.ID); if (res != 0) { return res; } } // try with name, then if(this.name != null && other.name != null) { res = this.name.compareTo(other.name); } // and give up return res; } /** * Sets a name. * * @param name stop name as string (not null) */ public final void setStopName(@NonNull String name) { this.name = name; } /** * Sets user name. Empty string is converted to null. * * @param name a string of non-zero length, or null */ public final void setStopUserName(@Nullable String name) { if(name == null) { this.username = null; } else if(name.length() == 0) { this.username = null; } else { this.username = name; } } /** * Returns stop name or username (if set).
* - empty string means "already searched everywhere, can't find it"
* - null means "didn't search, yet. Maybe you should try."
* - string means "here's the name.", obviously.
* * @return string if known, null if still unknown */ public final @Nullable String getStopDisplayName() { if(this.username == null) { return this.name; } else { return this.username; } } /** * Same as getStopDisplayName, only returns default name.
* I'd use an @see tag, but Android Studio is incapable of understanding that getStopDefaultName * refers to the method exactly above this one and not some arcane and esoteric unknown symbol. */ public final @Nullable String getStopDefaultName() { return this.name; } /** * Same as getStopDisplayName, only returns user name.
* Also, never an empty string. */ public final @Nullable String getStopUserName() { return this.username; } /** * Gets username and name from other stop if they exist, sets itself accordingly. * * @param other another Stop * @return did we actually set/change anything? */ public final boolean mergeNameFrom(Stop other) { boolean ret = false; if(other.name != null) { if(this.name == null || !this.name.equals(other.name)) { this.name = other.name; ret = true; } } if(other.username != null) { if(this.username == null || !this.username.equals(other.username)) { this.username = other.username; ret = true; } } return ret; } public final @Nullable String getGeoURL() { if(this.lat == null || this.lon == null) { return null; } // Android documentation suggests US for machine readable output (use dot as decimal separator) return String.format(Locale.US, "geo:%f,%f", this.lat, this.lon); } public final @Nullable String getGeoURLWithAddress() { String url = getGeoURL(); if(url == null) { return null; } if(this.location != null) { try { String addThis = "?q=".concat(URLEncoder.encode(this.location, "utf-8")); return url.concat(addThis); } catch (Exception ignored) {} } return url; } @Override public String toString(){ return "id:"+ID+" { name: "+this.name+", lines: "+this.routesThatStopHereToString()+"}"; } @Nullable public Double getLatitude() { return lat; } @Nullable public Double getLongitude() { return lon; } - public Double getDistanceFromLocation(IGeoPoint loc){ + public Double getDistanceFromLocation(@NotNull GPSPoint loc){ return getDistanceFromLocation(loc.getLatitude(), loc.getLongitude()); } public Double getDistanceFromLocation(double latitude, double longitude){ if(this.lat!=null && this.lon !=null) return utils.measuredistanceBetween(this.lat,this.lon,latitude, longitude); else return Double.POSITIVE_INFINITY; } public Bundle toBundle(Bundle bundle) { //Bundle bundle = new Bundle(); if(bundle==null) return null; bundle.putString("ID", ID); bundle.putString("name", name); bundle.putString("username", username); bundle.putString("location", location); bundle.putString("type", (type != null) ? type.name() : null); bundle.putStringArrayList("routesThatStopHere", (routesThatStopHere != null) ? new ArrayList<>(routesThatStopHere) : null); if (lat != null) bundle.putDouble("lat", lat); if (lon != null) bundle.putDouble("lon", lon); if (gtfsID !=null) bundle.putString("gtfsID", gtfsID); return bundle; } public Bundle toBundle(){ return toBundle(new Bundle()); } @Nullable public static Stop fromBundle(Bundle bundle) { String ID = bundle.getString("ID"); if (ID == null) return null; //throw new IllegalArgumentException("ID cannot be null"); String name = bundle.getString("name"); String username = bundle.getString("username"); String location = bundle.getString("location"); String typeStr = bundle.getString("type"); Route.Type type = (typeStr != null) ? Route.Type.valueOf(typeStr) : null; List routesThatStopHere = bundle.getStringArrayList("routesThatStopHere"); Double lat = bundle.containsKey("lat") ? bundle.getDouble("lat") : null; Double lon = bundle.containsKey("lon") ? bundle.getDouble("lon") : null; String gtfsId = bundle.getString("gtfsID"); return new Stop(ID, name, username, location, type, routesThatStopHere, lat, lon, gtfsId); } } diff --git a/app/src/main/java/it/reyboz/bustorino/backend/utils.java b/app/src/main/java/it/reyboz/bustorino/backend/utils.java index ec5567d..9586f2a 100644 --- a/app/src/main/java/it/reyboz/bustorino/backend/utils.java +++ b/app/src/main/java/it/reyboz/bustorino/backend/utils.java @@ -1,391 +1,393 @@ /* BusTO (backend components) Copyright (C) 2019 Fabio Mazza This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino.backend; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.text.Html; import android.text.Spanned; import android.util.Log; import android.util.TypedValue; import androidx.annotation.Nullable; import androidx.preference.PreferenceManager; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import it.reyboz.bustorino.backend.mato.MatoAPIFetcher; import it.reyboz.bustorino.fragments.SettingsFragment; public abstract class utils { private static final double EARTH_RADIUS = 6371.009e3; public static final String SOURCE_CODE_URL ="https://gitpull.it/source/libre-busto/"; public static Double measuredistanceBetween(double lat1,double long1,double lat2,double long2){ + + final double phi1 = Math.toRadians(lat1); final double phi2 = Math.toRadians(lat2); final double deltaPhi = Math.toRadians(lat2-lat1); final double deltaTheta = Math.toRadians(long2-long1); final double a = Math.sin(deltaPhi/2)*Math.sin(deltaPhi/2)+ Math.cos(phi1)*Math.cos(phi2)*Math.sin(deltaTheta/2)*Math.sin(deltaTheta/2); final double c = 2*Math.atan2(Math.sqrt(a),Math.sqrt(1-a)); return Math.abs(EARTH_RADIUS *c); } public static Double angleRawDifferenceFromMeters(double distanceInMeters){ return Math.toDegrees(distanceInMeters/ EARTH_RADIUS); } public static int convertDipToPixelsInt(Context con,double dips) { return (int) (dips * con.getResources().getDisplayMetrics().density + 0.5f); } /** * Convert distance in meters on Earth in degrees of latitude, keeping the same longitude * @param distanceMeters distance in meters * @return angle in degrees */ public static Double latitudeDelta(Double distanceMeters){ final double angleRad = distanceMeters/EARTH_RADIUS; return Math.toDegrees(angleRad); } /** * Convert distance in meters on Earth in degrees of longitude, keeping the same latitude * @param distanceMeters distance in meters * @param latitude the latitude that is fixed * @return angle in degrees */ public static Double longitudeDelta(Double distanceMeters, Double latitude){ final double theta = Math.toRadians(latitude); final double denom = Math.abs(Math.cos(theta)); final double angleRad = 2*Math.asin(Math.sin(distanceMeters / EARTH_RADIUS) / denom); return Math.toDegrees(angleRad); } public static float convertDipToPixels(Context con, float dp){ return convertDipToPixels(con.getResources(), dp); } public static float convertDipToPixels(Resources res, float dp){ return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,res.getDisplayMetrics()); } /* public static int calculateNumColumnsFromSize(View containerView, int pixelsize){ int width = containerView.getWidth(); float ncols = ((float)width)/pixelsize; return (int) Math.floor(ncols); } */ /** * Check if there is an internet connection * @param con context object to get the system service * @return true if we are */ public static boolean isConnected(Context con) { ConnectivityManager connMgr = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); return networkInfo != null && networkInfo.isConnected(); } ///////////////////// INTENT HELPER //////////////////////////////////////////////////////////// /** * Try to extract the bus stop ID from a URi * * @param uri The URL * @return bus stop ID or null */ public static String getBusStopIDFromUri(Uri uri) { String busStopID; // everithing catches fire when passing null to a switch. String host = uri.getHost(); if (host == null) { Log.e("ActivityMain", "Not an URL: " + uri); return null; } switch (host) { case "m.gtt.to.it": // http://m.gtt.to.it/m/it/arrivi.jsp?n=1254 busStopID = uri.getQueryParameter("n"); if (busStopID == null) { Log.e("ActivityMain", "Expected ?n from: " + uri); } break; case "www.gtt.to.it": case "gtt.to.it": // http://www.gtt.to.it/cms/percorari/arrivi?palina=1254 busStopID = uri.getQueryParameter("palina"); if (busStopID == null) { Log.e("ActivityMain", "Expected ?palina from: " + uri); } break; default: Log.e("ActivityMain", "Unexpected intent URL: " + uri); busStopID = null; } return busStopID; } final static Pattern ROMAN_PATTERN = Pattern.compile( "^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$"); private static boolean isRomanNumber(String str){ if(str.isEmpty()) return false; final Matcher matcher = ROMAN_PATTERN.matcher(str); return matcher.find(); } public static String toTitleCase(String givenString, boolean lowercaseRest) { String[] arr = givenString.trim().split(" "); StringBuilder sb = new StringBuilder(); //Log.d("BusTO chars", "String parsing: "+givenString+" in array: "+ Arrays.toString(arr)); for (String s : arr) { if (s.length() > 0) { String[] allsubs = s.split("\\."); boolean addPoint = s.contains("."); /*if (s.contains(".lli")|| s.contains(".LLI")) //Fratelli { DOESN'T ALWAYS WORK addPoint = false; allsubs = new String[]{s}; }*/ boolean first = true; for (String subs : allsubs) { if(first) first=false; else { if (addPoint) sb.append("."); sb.append(" "); } if(isRomanNumber(subs)){ //add and skip the rest sb.append(subs); continue; } //SPLIT ON ', check if contains "D'" if(subs.toLowerCase(Locale.ROOT).startsWith("d'")){ sb.append("D'"); subs = subs.substring(2); } int index = 0; char c = subs.charAt(index); if(subs.length() > 1 && c=='('){ sb.append(c); index += 1; c = subs.charAt(index); } sb.append(Character.toUpperCase(c)); if (lowercaseRest) sb.append(subs.substring(index+1).toLowerCase(Locale.ROOT)); else sb.append(subs.substring(index+1)); } if(addPoint && allsubs.length == 1) sb.append('.'); sb.append(" "); /*sb.append(Character.toUpperCase(arr[i].charAt(0))); if (lowercaseRest) sb.append(arr[i].substring(1).toLowerCase(Locale.ROOT)); else sb.append(arr[i].substring(1)); sb.append(" "); */ } else sb.append(s); } return sb.toString().trim(); } /** * Open an URL in the default browser. * * @param url URL */ public static void openIceweasel(String url, Context context) { Intent browserIntent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); if (browserIntent1.resolveActivity(context.getPackageManager()) != null) { //check we have an activity ready to receive intents (otherwise, there will be a crash) context.startActivity(browserIntent1); } else{ Log.e("BusTO","openIceweasel can't find a browser"); } } /** * Get the default list of fetchers for arrival times * @return array of ArrivalsFetchers to use */ public static ArrivalsFetcher[] getDefaultArrivalsFetchers(){ return new ArrivalsFetcher[]{ new MatoAPIFetcher(), new GTTJSONFetcher(), new FiveTScraperFetcher()}; } /** * Get the default list of fetchers for arrival times * @return array of ArrivalsFetchers to use */ public static List getDefaultArrivalsFetchers(Context context){ SharedPreferences defSharPref = PreferenceManager.getDefaultSharedPreferences(context); final Set setSelected = new HashSet<>(defSharPref.getStringSet(SettingsFragment.KEY_ARRIVALS_FETCHERS_USE, new HashSet<>())); if (setSelected.isEmpty()) { return Arrays.asList(new MatoAPIFetcher(), new GTTJSONFetcher(), new FiveTScraperFetcher()); }else{ ArrayList outFetchers = new ArrayList<>(4); /*for(String s: setSelected){ switch (s){ case "matofetcher": outFetchers.add(new MatoAPIFetcher()); break; case "fivetapifetcher": outFetchers.add(new FiveTAPIFetcher()); break; case "gttjsonfetcher": outFetchers.add(new GTTJSONFetcher()); break; case "fivetscraper": outFetchers.add(new FiveTScraperFetcher()); break; default: throw new IllegalArgumentException(); } }*/ if (setSelected.contains("matofetcher")) { outFetchers.add(new MatoAPIFetcher()); setSelected.remove("matofetcher"); } if (setSelected.contains("fivetapifetcher")) { outFetchers.add(new FiveTAPIFetcher()); setSelected.remove("fivetapifetcher"); } if (setSelected.contains("gttjsonfetcher")){ outFetchers.add(new GTTJSONFetcher()); setSelected.remove("gttjsonfetcher"); } if (setSelected.contains("fivetscraper")) { outFetchers.add(new FiveTScraperFetcher()); setSelected.remove("fivetscraper"); } if(!setSelected.isEmpty()){ Log.e("BusTO-Utils","Getting some fetchers values which are not contemplated: "+setSelected); } return outFetchers; } } /*public String getShorterDirection(String headSign){ String[] parts = headSign.split(","); if (parts.length<=1){ return headSign.trim(); } String first = parts[0].trim(); String second = parts[1].trim(); String firstLower = first.toLowerCase(Locale.ITALIAN); switch (firstLower){ case "circolare destra": case "circolare sinistra": case } }*/ /** * Print the first i lines of the the trace of an exception * https://stackoverflow.com/questions/21706722/fetch-only-first-n-lines-of-a-stack-trace */ /* public static String traceCaller(Exception ex, int i) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); StringBuilder sb = new StringBuilder(); ex.printStackTrace(pw); String ss = sw.toString(); String[] splitted = ss.split("\n"); sb.append("\n"); if(splitted.length > 2 + i) { for(int x = 2; x < i+2; x++) { sb.append(splitted[x].trim()); sb.append("\n"); } return sb.toString(); } return "Trace too Short."; } */ public static String joinList(@Nullable List dat, String separator){ StringBuilder sb = new StringBuilder(); if(dat==null || dat.size()==0) return ""; else if(dat.size()==1) return dat.get(0); sb.append(dat.get(0)); for (int i=1; i Set convertArrayToSet(T[] array) { // Create an empty Set Set set = new HashSet<>(); // Add each element into the set set.addAll(Arrays.asList(array)); // Return the converted Set return set; } public static String giveClassesForArray(T[] array){ StringBuilder sb = new StringBuilder(); for (T f: array){ sb.append(""); sb.append(f.getClass().getSimpleName()); sb.append("; "); } return sb.toString(); } public static Spanned convertHtml(String text) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { return Html.fromHtml(text, Html.FROM_HTML_MODE_COMPACT); } else { return Html.fromHtml(text); } } } diff --git a/app/src/main/java/it/reyboz/bustorino/fragments/LinesDetailFragment.kt b/app/src/main/java/it/reyboz/bustorino/fragments/LinesDetailFragment.kt index 4497770..09dc58a 100644 --- a/app/src/main/java/it/reyboz/bustorino/fragments/LinesDetailFragment.kt +++ b/app/src/main/java/it/reyboz/bustorino/fragments/LinesDetailFragment.kt @@ -1,1567 +1,1567 @@ /* BusTO - Fragments components Copyright (C) 2023 Fabio Mazza This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino.fragments import android.Manifest import android.animation.ObjectAnimator import android.animation.ValueAnimator import android.annotation.SuppressLint import android.content.Context import android.content.SharedPreferences import android.content.res.ColorStateList import android.location.Location import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.LinearInterpolator import android.widget.* import androidx.activity.result.ActivityResultCallback import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.content.res.AppCompatResources import androidx.cardview.widget.CardView import androidx.core.content.ContextCompat import androidx.core.content.res.ResourcesCompat import androidx.core.view.ViewCompat import androidx.fragment.app.viewModels import androidx.preference.PreferenceManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.gson.JsonObject import it.reyboz.bustorino.R import it.reyboz.bustorino.adapters.NameCapitalize import it.reyboz.bustorino.adapters.StopAdapterListener import it.reyboz.bustorino.adapters.StopRecyclerAdapter import it.reyboz.bustorino.backend.FiveTNormalizer import it.reyboz.bustorino.backend.LivePositionTripPattern import it.reyboz.bustorino.backend.Stop import it.reyboz.bustorino.backend.gtfs.GtfsUtils import it.reyboz.bustorino.backend.gtfs.LivePositionUpdate import it.reyboz.bustorino.backend.gtfs.PolylineParser import it.reyboz.bustorino.backend.utils import it.reyboz.bustorino.data.MatoTripsDownloadWorker import it.reyboz.bustorino.data.PreferencesHolder import it.reyboz.bustorino.data.gtfs.MatoPatternWithStops import it.reyboz.bustorino.data.gtfs.TripAndPatternWithStops import it.reyboz.bustorino.map.* import it.reyboz.bustorino.middleware.LocationUtils import it.reyboz.bustorino.util.Permissions import it.reyboz.bustorino.util.ViewUtils import it.reyboz.bustorino.viewmodels.LinesViewModel import it.reyboz.bustorino.viewmodels.LivePositionsViewModel import kotlinx.coroutines.Runnable import org.maplibre.android.camera.CameraPosition import org.maplibre.android.camera.CameraUpdateFactory import org.maplibre.android.geometry.LatLng import org.maplibre.android.geometry.LatLngBounds import org.maplibre.android.location.LocationComponent import org.maplibre.android.location.LocationComponentOptions import org.maplibre.android.maps.MapLibreMap import org.maplibre.android.maps.Style import org.maplibre.android.plugins.annotation.Symbol import org.maplibre.android.plugins.annotation.SymbolManager import org.maplibre.android.plugins.annotation.SymbolOptions import org.maplibre.android.style.expressions.Expression import org.maplibre.android.style.layers.LineLayer import org.maplibre.android.style.layers.Property import org.maplibre.android.style.layers.Property.ICON_ANCHOR_CENTER import org.maplibre.android.style.layers.Property.ICON_ROTATION_ALIGNMENT_MAP import org.maplibre.android.style.layers.PropertyFactory import org.maplibre.android.style.layers.SymbolLayer import org.maplibre.android.style.sources.GeoJsonSource import org.maplibre.geojson.Feature import org.maplibre.geojson.FeatureCollection import org.maplibre.geojson.LineString import org.maplibre.geojson.Point import java.util.concurrent.atomic.AtomicBoolean class LinesDetailFragment() : GeneralMapLibreFragment() { private var lineID = "" private lateinit var patternsSpinner: Spinner private var patternsAdapter: ArrayAdapter? = null //Bottom sheet behavior private lateinit var bottomSheetBehavior: BottomSheetBehavior private var bottomLayout: RelativeLayout? = null private lateinit var stopTitleTextView: TextView private lateinit var stopNumberTextView: TextView private lateinit var linesPassingTextView: TextView private lateinit var arrivalsCard: CardView private lateinit var directionsCard: CardView private lateinit var bottomrightImage: ImageView //private var isBottomSheetShowing = false private var shouldMapLocationBeReactivated = true private var toRunWhenMapReady : Runnable? = null private var mapInitialized = AtomicBoolean(false) //private var patternsSpinnerState: Parcelable? = null private lateinit var currentPatterns: List //private lateinit var map: MapView private var patternShown: MatoPatternWithStops? = null private val viewModel: LinesViewModel by viewModels() private val mapViewModel: MapViewModel by viewModels() private var firstInit = true private var pausedFragment = false private lateinit var switchButton: ImageButton private var favoritesButton: ImageButton? = null private var locationIcon: ImageButton? = null private var isLineInFavorite = false private var appContext: Context? = null private var isLocationPermissionOK = false private val lineSharedPrefMonitor = SharedPreferences.OnSharedPreferenceChangeListener { pref, keychanged -> if(keychanged!=PreferencesHolder.PREF_FAVORITE_LINES || lineID.isEmpty()) return@OnSharedPreferenceChangeListener val newFavorites = pref.getStringSet(PreferencesHolder.PREF_FAVORITE_LINES, HashSet()) newFavorites?.let {favorites-> isLineInFavorite = favorites.contains(lineID) //if the button has been intialized, change the icon accordingly favoritesButton?.let { button-> //avoid crashes if fragment not attached if(context==null) return@let if(isLineInFavorite) { button.setImageDrawable(ResourcesCompat.getDrawable(resources, R.drawable.ic_star_filled, null)) appContext?.let { Toast.makeText(it,R.string.favorites_line_add,Toast.LENGTH_SHORT).show()} } else { button.setImageDrawable(ResourcesCompat.getDrawable(resources, R.drawable.ic_star_outline, null)) appContext?.let {Toast.makeText(it,R.string.favorites_line_remove,Toast.LENGTH_SHORT).show()} } } } } private lateinit var stopsRecyclerView: RecyclerView private lateinit var descripTextView: TextView private var stopIDFromToShow: String? = null //adapter for recyclerView private val stopAdapterListener= object : StopAdapterListener { override fun onTappedStop(stop: Stop?) { if(viewModel.shouldShowMessage) { Toast.makeText(context, R.string.long_press_stop_4_options, Toast.LENGTH_SHORT).show() viewModel.shouldShowMessage=false } stop?.let { fragmentListener.requestArrivalsForStopID(it.ID) } if(stop == null){ Log.e(DEBUG_TAG,"Passed wrong stop") } if(fragmentListener == null){ Log.e(DEBUG_TAG, "Fragment listener is null") } } override fun onLongPressOnStop(stop: Stop?): Boolean { TODO("Not yet implemented") } } private val patternsSorter = Comparator{ p1: MatoPatternWithStops, p2: MatoPatternWithStops -> if(p1.pattern.directionId != p2.pattern.directionId) return@Comparator p1.pattern.directionId - p2.pattern.directionId else return@Comparator -1*(p1.stopsIndices.size - p2.stopsIndices.size) } //map data //style and sources are in GeneralMapLibreFragment private lateinit var locationComponent: LocationComponent private lateinit var polylineSource: GeoJsonSource private lateinit var polyArrowSource: GeoJsonSource private var savedCameraPosition: CameraPosition? = null private var vehShowing = "" private var stopsLayerStarted = false private var lastStopsSizeShown = 0 private var lastUpdateTime:Long = -2 //BUS POSITIONS private val updatesByVehDict = HashMap(5) private val animatorsByVeh = HashMap() private var lastLocation : Location? = null private var enablingPositionFromClick = false private var polyline: LineString? = null private val showUserPositionRequestLauncher = registerForActivityResult( ActivityResultContracts.RequestMultiplePermissions(), ActivityResultCallback { result -> if (result == null) { Log.w(DEBUG_TAG, "Got asked permission but request is null, doing nothing?") } else if (java.lang.Boolean.TRUE == result[Manifest.permission.ACCESS_COARSE_LOCATION] && java.lang.Boolean.TRUE == result[Manifest.permission.ACCESS_FINE_LOCATION]) { // We can use the position, restart location overlay if (context == null || requireContext().getSystemService(Context.LOCATION_SERVICE) == null) return@ActivityResultCallback ///@registerForActivityResult setMapUserLocationEnabled(true, true, enablingPositionFromClick) } else Log.w(DEBUG_TAG, "No location permission") }) //private var stopPosList = ArrayList() //fragment actions private lateinit var fragmentListener: CommonFragmentListener private var showOnTopOfLine = false private var recyclerInitDone = false private var useMQTTPositions = true //position of live markers private val tripMarkersAnimators = HashMap() private val liveBusViewModel: LivePositionsViewModel by viewModels() //extra items to use the LibreMap private lateinit var symbolManager : SymbolManager private var stopActiveSymbol: Symbol? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val args = requireArguments() lineID = args.getString(LINEID_KEY,"") stopIDFromToShow = args.getString(STOPID_FROM_KEY) } @SuppressLint("SetTextI18n") override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { //reset statuses //isBottomSheetShowing = false //stopsLayerStarted = false lastStopsSizeShown = 0 mapInitialized.set(false) val rootView = inflater.inflate(R.layout.fragment_lines_detail, container, false) //lineID = requireArguments().getString(LINEID_KEY, "") arguments?.let { lineID = it.getString(LINEID_KEY, "") } switchButton = rootView.findViewById(R.id.switchImageButton) locationIcon = rootView.findViewById(R.id.locationEnableIcon) favoritesButton = rootView.findViewById(R.id.favoritesButton) stopsRecyclerView = rootView.findViewById(R.id.patternStopsRecyclerView) descripTextView = rootView.findViewById(R.id.lineDescripTextView) descripTextView.visibility = View.INVISIBLE //map stuff mapView = rootView.findViewById(R.id.lineMap) mapView.getMapAsync(this) //init bottom sheet val bottomSheet = rootView.findViewById(R.id.bottom_sheet) bottomLayout = bottomSheet stopTitleTextView = bottomSheet.findViewById(R.id.stopTitleTextView) stopNumberTextView = bottomSheet.findViewById(R.id.stopNumberTextView) linesPassingTextView = bottomSheet.findViewById(R.id.linesPassingTextView) arrivalsCard = bottomSheet.findViewById(R.id.arrivalsCardButton) directionsCard = bottomSheet.findViewById(R.id.directionsCardButton) bottomrightImage = bottomSheet.findViewById(R.id.rightmostImageView) bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet) // Setup close button rootView.findViewById(R.id.btnClose).setOnClickListener { hideStopBottomSheet() } val titleTextView = rootView.findViewById(R.id.titleTextView) titleTextView.text = getString(R.string.line)+" "+FiveTNormalizer.fixShortNameForDisplay( GtfsUtils.getLineNameFromGtfsID(lineID), true) favoritesButton?.isClickable = true favoritesButton?.setOnClickListener { if(lineID.isNotEmpty()) PreferencesHolder.addOrRemoveLineToFavorites(requireContext(),lineID,!isLineInFavorite) } val preferences = PreferencesHolder.getMainSharedPreferences(requireContext()) val favorites = preferences.getStringSet(PreferencesHolder.PREF_FAVORITE_LINES, HashSet()) if(favorites!=null && favorites.contains(lineID)){ favoritesButton?.setImageDrawable(ResourcesCompat.getDrawable(resources, R.drawable.ic_star_filled, null)) isLineInFavorite = true } appContext = requireContext().applicationContext preferences.registerOnSharedPreferenceChangeListener(lineSharedPrefMonitor) patternsSpinner = rootView.findViewById(R.id.patternsSpinner) patternsAdapter = ArrayAdapter(requireContext(), android.R.layout.simple_spinner_dropdown_item, ArrayList()) patternsSpinner.adapter = patternsAdapter initializeRecyclerView() switchButton.setOnClickListener{ if(mapView.visibility == View.VISIBLE){ hideMapAndShowStopList() } else{ hideStopListAndShowMap() } } locationIcon?.let {view -> if(!LocationUtils.isLocationEnabled(requireContext()) || !Permissions.anyLocationPermissionsGranted(requireContext())) setLocationIconEnabled(false) //set click Listener view.setOnClickListener(this::onPositionIconButtonClick) } //set //INITIALIZE VIEW MODELS viewModel.setRouteIDQuery(lineID) liveBusViewModel.setGtfsLineToFilterPos(lineID, null) val keySourcePositions = getString(R.string.pref_positions_source) useMQTTPositions = PreferenceManager.getDefaultSharedPreferences(requireContext()) .getString(keySourcePositions, "mqtt").contentEquals("mqtt") viewModel.patternsWithStopsByRouteLiveData.observe(viewLifecycleOwner){ patterns -> savePatternsToShow(patterns) } /* */ viewModel.stopsForPatternLiveData.observe(viewLifecycleOwner) { stops -> if(mapView.visibility ==View.VISIBLE) patternShown?.let{ // We have the pattern and the stops here, time to display them displayPatternWithStopsOnMap(it,stops, true) } ?:{ Log.w(DEBUG_TAG, "The viewingPattern is null!") } else{ if(stopsRecyclerView.visibility==View.VISIBLE) showStopsInRecyclerView(stops) } } viewModel.gtfsRoute.observe(viewLifecycleOwner){route-> if(route == null){ //need to close the fragment activity?.supportFragmentManager?.popBackStack() return@observe } descripTextView.text = route.longName descripTextView.visibility = View.VISIBLE } /* */ Log.d(DEBUG_TAG,"Data ${viewModel.stopsForPatternLiveData.value}") //listeners patternsSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(p0: AdapterView<*>?, p1: View?, position: Int, p3: Long) { val currentShownPattern = patternShown?.pattern val patternWithStops = currentPatterns[position] Log.d(DEBUG_TAG, "request stops for pattern ${patternWithStops.pattern.code}") setPatternAndReqStops(patternWithStops) if(mapView.visibility == View.VISIBLE) { //Clear buses if we are changing direction currentShownPattern?.let { patt -> if(patt.directionId != patternWithStops.pattern.directionId){ stopAnimations() updatesByVehDict.clear() updatePositionsIcons(true) liveBusViewModel.retriggerPositionUpdate() } } } liveBusViewModel.setGtfsLineToFilterPos(lineID, patternWithStops.pattern) } override fun onNothingSelected(p0: AdapterView<*>?) { } } Log.d(DEBUG_TAG, "Views created!") return rootView } // ------------- UI switch stuff --------- private fun hideMapAndShowStopList(){ mapView.visibility = View.GONE stopsRecyclerView.visibility = View.VISIBLE locationIcon?.visibility = View.GONE viewModel.setMapShowing(false) if(useMQTTPositions) liveBusViewModel.stopMatoUpdates() //map.overlayManager.remove(busPositionsOverlay) switchButton.setImageDrawable(AppCompatResources.getDrawable(requireContext(), R.drawable.ic_map_white_30)) hideStopBottomSheet() if(locationComponent.isLocationComponentEnabled){ locationComponent.isLocationComponentEnabled = false shouldMapLocationBeReactivated = true } else shouldMapLocationBeReactivated = false } private fun hideStopListAndShowMap(){ stopsRecyclerView.visibility = View.GONE mapView.visibility = View.VISIBLE locationIcon?.visibility = View.VISIBLE viewModel.setMapShowing(true) //map.overlayManager.add(busPositionsOverlay) //map. if(useMQTTPositions) liveBusViewModel.requestMatoPosUpdates(GtfsUtils.getLineNameFromGtfsID(lineID)) else liveBusViewModel.requestGTFSUpdates() switchButton.setImageDrawable(AppCompatResources.getDrawable(requireContext(), R.drawable.ic_list_30)) if(shouldMapLocationBeReactivated && Permissions.bothLocationPermissionsGranted(requireContext())){ locationComponent.isLocationComponentEnabled = true } } private fun setLocationIconEnabled(setTrue: Boolean){ if(setTrue) locationIcon?.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.location_circlew_red)) else locationIcon?.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.location_circlew_grey)) } /** * Handles logic of enabling the user location on the map */ @SuppressLint("MissingPermission") private fun setMapUserLocationEnabled(enabled: Boolean, assumePermissions: Boolean, fromClick: Boolean) { if (enabled) { val permissionOk = assumePermissions || Permissions.bothLocationPermissionsGranted(requireContext()) if (permissionOk) { Log.d(DEBUG_TAG, "Permission OK, starting location component, assumed: $assumePermissions") locationComponent.isLocationComponentEnabled = true //locationComponent.cameraMode = CameraMode.TRACKING //CameraMode.TRACKING setLocationIconEnabled(true) if (fromClick) Toast.makeText(context, R.string.location_enabled, Toast.LENGTH_SHORT).show() } else { if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) { //TODO: show dialog for permission rationale Toast.makeText(activity, R.string.enable_position_message_map, Toast.LENGTH_SHORT).show() } Log.d(DEBUG_TAG, "Requesting permission to show user location") enablingPositionFromClick = fromClick showUserPositionRequestLauncher.launch(Permissions.LOCATION_PERMISSIONS) } } else{ locationComponent.isLocationComponentEnabled = false setLocationIconEnabled(false) if (fromClick) { Toast.makeText(requireContext(), R.string.location_disabled, Toast.LENGTH_SHORT).show() //TODO: Cancel the request for the enablement of the position if needed } } } /** * Switch position icon from activ */ private fun onPositionIconButtonClick(view: View){ if(locationComponent.isLocationComponentEnabled) setMapUserLocationEnabled(false, false, true) else{ setMapUserLocationEnabled(true, false, true) } } // ------------- Map Code ------------------------- /** * This method sets up the map and the layers */ override fun onMapReady(mapReady: MapLibreMap) { this.map = mapReady val context = requireContext() - val mjson = Styles.getJsonStyleFromAsset(context, PreferencesHolder.getMapLibreStyleFile(context)) //ViewUtils.loadJsonFromAsset(requireContext(),"map_style_good.json") + val mjson = MapLibreStyles.getJsonStyleFromAsset(context, PreferencesHolder.getMapLibreStyleFile(context)) //ViewUtils.loadJsonFromAsset(requireContext(),"map_style_good.json") activity?.run { val builder = Style.Builder().fromJson(mjson!!) mapReady.setStyle(builder) { style -> mapStyle = style //setupLayers(style) // Start observing data initMapUserLocation(style, mapReady, requireContext()) //if(!stopsLayerStarted) initStopsPolyLineLayers(style, FeatureCollection.fromFeatures(ArrayList()), null, null) /*if(!stopsLayerStarted) { Log.d(DEBUG_TAG, "Stop layer is not started yet") initStopsPolyLineLayers(style, FeatureCollection.fromFeatures(ArrayList()), null) } */ setupBusLayer(style) symbolManager = SymbolManager(mapView,mapReady,style) symbolManager.iconAllowOverlap = true symbolManager.textAllowOverlap = false symbolManager.addClickListener{ _ -> if (stopActiveSymbol!=null){ hideStopBottomSheet() return@addClickListener true } else return@addClickListener false } mapViewModel.stopShowing?.let { openStopInBottomSheet(it) } mapViewModel.stopShowing = null toRunWhenMapReady?.run() toRunWhenMapReady = null mapInitialized.set(true) if(patternShown!=null){ viewModel.stopsForPatternLiveData.value?.let { Log.d(DEBUG_TAG, "Show stops from the cache") displayPatternWithStopsOnMap(patternShown!!, it, true) } } } mapReady.addOnMapClickListener { point -> val screenPoint = mapReady.projection.toScreenLocation(point) val features = mapReady.queryRenderedFeatures(screenPoint, STOPS_LAYER_ID) val busNearby = mapReady.queryRenderedFeatures(screenPoint, BUSES_LAYER_ID) if (features.isNotEmpty()) { val feature = features[0] val id = feature.getStringProperty("id") val name = feature.getStringProperty("name") //Toast.makeText(requireContext(), "Clicked on $name ($id)", Toast.LENGTH_SHORT).show() val stop = viewModel.getStopByID(id) stop?.let { if (isBottomSheetShowing() || vehShowing.isNotEmpty()){ hideStopBottomSheet() } openStopInBottomSheet(it) //move camera if(it.latitude!=null && it.longitude!=null) mapReady.animateCamera(CameraUpdateFactory.newLatLng(LatLng(it.latitude!!,it.longitude!!)),750) } return@addOnMapClickListener true } else if (busNearby.isNotEmpty()){ val feature = busNearby[0] val vehid = feature.getStringProperty("veh") val route = feature.getStringProperty("line") if(isBottomSheetShowing()) hideStopBottomSheet() //if(context!=null){ // Toast.makeText(context, "Veh $vehid on route ${route.slice(0..route.length-2)}", Toast.LENGTH_SHORT).show() //} showVehicleTripInBottomSheet(vehid) updatesByVehDict[vehid]?.let { //if (it.posUpdate.latitude != null && it.longitude != null) mapReady.animateCamera( CameraUpdateFactory.newLatLng(LatLng(it.posUpdate.latitude, it.posUpdate.longitude)), 750 ) } return@addOnMapClickListener true } false } // we start requesting the bus positions now observeBusPositionUpdates() } /*savedMapStateOnPause?.let{ restoreMapStateFromBundle(it) pendingLocationActivation = false Log.d(DEBUG_TAG, "Restored map state from the saved bundle") } */ val zoom = 12.0 val latlngTarget = LatLng(MapLibreFragment.DEFAULT_CENTER_LAT, MapLibreFragment.DEFAULT_CENTER_LON) mapReady.cameraPosition = savedCameraPosition ?:CameraPosition.Builder().target(latlngTarget).zoom(zoom).build() savedCameraPosition = null if(shouldMapLocationBeReactivated) setMapUserLocationEnabled(true, false, false) } private fun observeBusPositionUpdates(){ //live bus positions liveBusViewModel.filteredLocationUpdates.observe(viewLifecycleOwner){ pair -> //Log.d(DEBUG_TAG, "Received ${updates.size} updates for the positions") val updates = pair.first val vehiclesNotOnCorrectDir = pair.second if(mapView.visibility == View.GONE || patternShown ==null){ //DO NOTHING Log.w(DEBUG_TAG, "not doing anything because map is not visible") return@observe } //remove vehicles not on this direction removeVehiclesData(vehiclesNotOnCorrectDir) updateBusPositionsInMap(updates) //if not using MQTT positions if(!useMQTTPositions){ liveBusViewModel.requestDelayedGTFSUpdates(2000) } } //download missing tripIDs liveBusViewModel.tripsGtfsIDsToQuery.observe(viewLifecycleOwner){ //gtfsPosViewModel.downloadTripsFromMato(dat); MatoTripsDownloadWorker.requestMatoTripsDownload( it, requireContext().applicationContext, "BusTO-MatoTripDownload" ) } } private fun isBottomSheetShowing(): Boolean{ return bottomSheetBehavior.state == BottomSheetBehavior.STATE_EXPANDED } /** * Initialize the map location, but do not enable the component */ @SuppressLint("MissingPermission") private fun initMapUserLocation(style: Style, map: MapLibreMap, context: Context){ locationComponent = map.locationComponent val locationComponentOptions = LocationComponentOptions.builder(context) .pulseEnabled(false) .build() val locationComponentActivationOptions = MapLibreUtils.buildLocationComponentActivationOptions(style, locationComponentOptions, context) locationComponent.activateLocationComponent(locationComponentActivationOptions) locationComponent.isLocationComponentEnabled = false lastLocation?.let { if (it.accuracy < 200) locationComponent.forceLocationUpdate(it) } } /** * Update the bottom sheet with the stop information */ override fun openStopInBottomSheet(stop: Stop){ bottomLayout?.let { //lay.findViewById(R.id.stopTitleTextView).text ="${stop.ID} - ${stop.stopDefaultName}" val stopName = stop.stopUserName ?: stop.stopDefaultName stopTitleTextView.text = stopName//stop.stopDefaultName stopNumberTextView.text = stop.ID stopTitleTextView.visibility = View.VISIBLE val string_show = if (stop.numRoutesStopping==0) "" else if (stop.numRoutesStopping <= 1) requireContext().getString(R.string.line_fill, stop.routesThatStopHereToString()) else requireContext().getString(R.string.lines_fill, stop.routesThatStopHereToString()) linesPassingTextView.text = string_show //SET ON CLICK LISTENER arrivalsCard.setOnClickListener{ fragmentListener?.requestArrivalsForStopID(stop.ID) } arrivalsCard.visibility = View.VISIBLE directionsCard.setOnClickListener { ViewUtils.openStopInOutsideApp(stop, context) } context?.let { val colorIcon = ViewUtils.getColorFromTheme(it, android.R.attr.colorAccent)//ResourcesCompat.getColor(resources,R.attr.colorAccent,activity?.theme) ViewCompat.setBackgroundTintList(directionsCard, ColorStateList.valueOf(colorIcon)) } bottomrightImage.setImageDrawable(ResourcesCompat.getDrawable(resources, R.drawable.navigation_right, activity?.theme)) } //add stop marker if (stop.latitude!=null && stop.longitude!=null) { stopActiveSymbol = symbolManager.create( SymbolOptions() .withLatLng(LatLng(stop.latitude!!, stop.longitude!!)) .withIconImage(STOP_ACTIVE_IMG) .withIconAnchor(ICON_ANCHOR_CENTER) ) } Log.d(DEBUG_TAG, "Shown stop $stop in bottom sheet") shownStopInBottomSheet = stop bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED //isBottomSheetShowing = true } // Hide the bottom sheet and remove extra symbol private fun hideStopBottomSheet(){ if (stopActiveSymbol!=null){ symbolManager.delete(stopActiveSymbol) stopActiveSymbol = null } bottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN //isBottomSheetShowing = false //reset states shownStopInBottomSheet = null vehShowing = "" } private fun showVehicleTripInBottomSheet(veh: String){ val data = updatesByVehDict[veh] if(data==null) { Log.w(DEBUG_TAG,"Asked to show vehicle $veh, but it's not present in the updates") return } bottomLayout?.let { val lineName = FiveTNormalizer.fixShortNameForDisplay( GtfsUtils.getLineNameFromGtfsID(data.posUpdate.routeID), true) stopNumberTextView.text = requireContext().getString(R.string.line_fill, lineName) val pat = data.pattern if (pat!=null){ stopTitleTextView.text = pat.headsign stopTitleTextView.visibility = View.VISIBLE Log.d(DEBUG_TAG, "Showing headsign ${pat.headsign} for vehicle $veh") } else { //stopTitleTextView.text = "NN" stopTitleTextView.visibility = View.GONE } linesPassingTextView.text = data.posUpdate.vehicle } arrivalsCard.visibility=View.GONE bottomrightImage.setImageDrawable(ResourcesCompat.getDrawable(resources, R.drawable.ic_magnifying_glass, activity?.theme)) directionsCard.setOnClickListener { data.pattern?.let { if(patternShown?.pattern?.code == it.code){ context?.let { c->Toast.makeText(c, R.string.showing_same_direction, Toast.LENGTH_SHORT).show() } }else showPatternWithCode(it.code) } //TODO // ?: { // context?.let { ctx -> Toast.makeText(ctx,"") } //} } //set color val colorBlue = ResourcesCompat.getColor(resources,R.color.blue_620,activity?.theme) ViewCompat.setBackgroundTintList(directionsCard, ColorStateList.valueOf(colorBlue)) vehShowing = veh bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED //isBottomSheetShowing = true Log.d(DEBUG_TAG, "Shown vehicle $veh in bottom layout") } // ------- MAP LAYERS INITIALIZE ---- /** * Initialize the map layers for the stops */ private fun initStopsPolyLineLayers(style: Style, stopFeatures:FeatureCollection, lineFeature: Feature?, arrowFeatures: FeatureCollection?){ Log.d(DEBUG_TAG, "INIT STOPS CALLED") stopsSource = GeoJsonSource(STOPS_SOURCE_ID) style.addSource(stopsSource) //val context = requireContext() val stopIcon = ResourcesCompat.getDrawable(resources,R.drawable.ball, activity?.theme)!! val imgStop = ResourcesCompat.getDrawable(resources,R.drawable.bus_stop_new, activity?.theme)!! val polyIconArrow = ResourcesCompat.getDrawable(resources, R.drawable.arrow_up_box_fill, activity?.theme)!! //set the image tint //DrawableCompat.setTint(imgBus,ContextCompat.getColor(context,R.color.line_drawn_poly)) // add icon style.addImage(STOP_IMAGE_ID,stopIcon) style.addImage(POLY_ARROW, polyIconArrow) style.addImage(STOP_ACTIVE_IMG, ResourcesCompat.getDrawable(resources, R.drawable.bus_stop_new_highlight, activity?.theme)!!) // Stops layer val stopsLayer = SymbolLayer(STOPS_LAYER_ID, STOPS_SOURCE_ID) stopsLayer.withProperties( PropertyFactory.iconImage(STOP_IMAGE_ID), PropertyFactory.iconAllowOverlap(true), PropertyFactory.iconIgnorePlacement(true) ) polylineSource = GeoJsonSource(POLYLINE_SOURCE) //lineFeature?.let { GeoJsonSource(POLYLINE_SOURCE, it) } ?: GeoJsonSource(POLYLINE_SOURCE) style.addSource(polylineSource) val color=ContextCompat.getColor(requireContext(),R.color.line_drawn_poly) //paint.style = Paint.Style.FILL_AND_STROKE //paint.strokeJoin = Paint.Join.ROUND //paint.strokeCap = Paint.Cap.ROUND val lineLayer = LineLayer(POLYLINE_LAYER, POLYLINE_SOURCE).withProperties( PropertyFactory.lineColor(color), PropertyFactory.lineWidth(5.0f), //originally 13f PropertyFactory.lineOpacity(1.0f), PropertyFactory.lineJoin(Property.LINE_JOIN_ROUND), PropertyFactory.lineCap(Property.LINE_CAP_ROUND) ) polyArrowSource = GeoJsonSource(POLY_ARROWS_SOURCE, arrowFeatures) style.addSource(polyArrowSource) val arrowsLayer = SymbolLayer(POLY_ARROWS_LAYER, POLY_ARROWS_SOURCE).withProperties( PropertyFactory.iconImage(POLY_ARROW), PropertyFactory.iconRotate(Expression.get("bearing")), PropertyFactory.iconRotationAlignment(ICON_ROTATION_ALIGNMENT_MAP) ) val layers = style.layers val lastLayers = layers.filter { l-> l.id.contains("city") } //Log.d(DEBUG_TAG,"Layers:\n ${style.layers.map { l -> l.id }}") Log.d(DEBUG_TAG, "City layers: ${lastLayers.map { l-> l.id }}") if(lastLayers.isNotEmpty()) style.addLayerAbove(lineLayer,lastLayers[0].id) else style.addLayerBelow(lineLayer,"label_country_1") style.addLayerAbove(stopsLayer, POLYLINE_LAYER) style.addLayerAbove(arrowsLayer, POLYLINE_LAYER) stopsLayerStarted = true } /** * Setup the Map Layers */ private fun setupBusLayer(style: Style) { // Buses source busesSource = GeoJsonSource(BUSES_SOURCE_ID) style.addSource(busesSource) style.addImage("bus_symbol",ResourcesCompat.getDrawable(resources, R.drawable.map_bus_position_icon, activity?.theme)!!) // Buses layer val busesLayer = SymbolLayer(BUSES_LAYER_ID, BUSES_SOURCE_ID).apply { withProperties( PropertyFactory.iconImage("bus_symbol"), //PropertyFactory.iconSize(1.2f), PropertyFactory.iconAllowOverlap(true), PropertyFactory.iconIgnorePlacement(true), PropertyFactory.iconRotate(Expression.get("bearing")), PropertyFactory.iconRotationAlignment(ICON_ROTATION_ALIGNMENT_MAP) ) } style.addLayerAbove(busesLayer, STOPS_LAYER_ID) } override fun onAttach(context: Context) { super.onAttach(context) if(context is CommonFragmentListener){ fragmentListener = context } else throw RuntimeException("$context must implement CommonFragmentListener") } private fun stopAnimations(){ for(anim in animatorsByVeh.values){ anim.cancel() } } /** * Save the loaded pattern data, without the stops! */ private fun savePatternsToShow(patterns: List){ currentPatterns = patterns.sortedWith(patternsSorter) patternsAdapter?.let { it.clear() it.addAll(currentPatterns.map { p->"${p.pattern.directionId} - ${p.pattern.headsign}" }) it.notifyDataSetChanged() } // if we are loading from a stop, find it val patternToShow = stopIDFromToShow?.let { sID -> val stopGtfsID = "gtt:$sID" var p: MatoPatternWithStops? = null var pLength = 0 for(patt in currentPatterns){ for(pstop in patt.stopsIndices){ if(pstop.stopGtfsId == stopGtfsID){ //found if (patt.stopsIndices.size>pLength){ p = patt pLength = patt.stopsIndices.size } //break here, we have determined this pattern has the stop we're looking for break } } } p } if(stopIDFromToShow!=null){ if(patternToShow==null) Log.w(DEBUG_TAG, "We had to show the pattern from stop $stopIDFromToShow, but we didn't find it") else Log.d(DEBUG_TAG, "Requesting to show pattern from stop $stopIDFromToShow, found pattern ${patternToShow.pattern.code}") } //unset the stopID to show if(patternToShow!=null) { //showPattern(patternToShow) patternShown = patternToShow stopIDFromToShow = null } patternShown?.let { showPattern(it) } } /** * Called when the position of the spinner is updated */ private fun setPatternAndReqStops(patternWithStops: MatoPatternWithStops){ Log.d(DEBUG_TAG, "Requesting stops for pattern ${patternWithStops.pattern.code}") viewModel.selectedPatternLiveData.value = patternWithStops viewModel.currentPatternStops.value = patternWithStops.stopsIndices.sortedBy { i-> i.order } patternShown = patternWithStops viewModel.requestStopsForPatternWithStops(patternWithStops) } private fun showPattern(patternWs: MatoPatternWithStops){ //Log.d(DEBUG_TAG, "Finding pattern to show: ${patternWs.pattern.code}") var pos = -2 val code = patternWs.pattern.code.trim() for (k in currentPatterns.indices) { if (currentPatterns[k].pattern.code.trim() == code) { pos = k break } } Log.d(DEBUG_TAG, "Requesting stops fro pattern $code in position: $pos") if (pos !=-2) patternsSpinner.setSelection(pos) else Log.e(DEBUG_TAG, "Pattern with code $code not found!!") //request pattern stops from DB //setPatternAndReqStops(patternWs) } private fun zoomToCurrentPattern(){ if(polyline==null) return val NULL_VALUE = -4000.0 var maxLat = NULL_VALUE var minLat = NULL_VALUE var minLong = NULL_VALUE var maxLong = NULL_VALUE polyline?.let { for(p in it.coordinates()){ val lat = p.latitude() val lon = p.longitude() // get max latitude if(maxLat == NULL_VALUE) maxLat =lat else if (maxLat < lat) maxLat = lat // find min latitude if (minLat ==NULL_VALUE) minLat = lat else if (minLat > lat) minLat = lat if(maxLong == NULL_VALUE || maxLong < lon ) maxLong = lon if (minLong == NULL_VALUE || minLong > lon) minLong = lon } val padding = 50 // Pixel di padding intorno ai limiti Log.d(DEBUG_TAG, "Setting limits of bounding box of line: $minLat -> $maxLat, $minLong -> $maxLong") val bbox = LatLngBounds.from(maxLat,maxLong, minLat, minLong) //map.zoomToBoundingBox(BoundingBox(maxLat+del, maxLong+del, minLat-del, minLong-del), false) map?.animateCamera(CameraUpdateFactory.newLatLngBounds(bbox, padding)) } } private fun displayPatternWithStopsOnMap(patternWs: MatoPatternWithStops, stopsToSort: List, zoomToPattern: Boolean){ if(!mapInitialized.get()){ //set the runnable and do nothing else Log.d(DEBUG_TAG, "Delaying pattern display to when map is Ready: ${patternWs.pattern.code}") toRunWhenMapReady = Runnable { displayPatternWithStopsOnMap(patternWs, stopsToSort, zoomToPattern) } return } Log.d(DEBUG_TAG, "Got the stops: ${stopsToSort.map { s->s.gtfsID }}}") patternShown = patternWs //Problem: stops are not sorted val stopOrderD = patternWs.stopsIndices.withIndex().associate{it.value.stopGtfsId to it.index} val stopsSorted = stopsToSort.sortedBy { s-> stopOrderD[s.gtfsID] } val pattern = patternWs.pattern val pointsList = PolylineParser.decodePolyline(pattern.patternGeometryPoly, pattern.patternGeometryLength) val pointsToShow = pointsList.map { Point.fromLngLat(it.longitude, it.latitude) } Log.d(DEBUG_TAG, "The polyline has ${pointsToShow.size} points to display") polyline = LineString.fromLngLats(pointsToShow) val lineFeature = Feature.fromGeometry(polyline) //Log.d(DEBUG_TAG, "Polyline in JSON is: ${lineFeature.toJson()}") // --- STOPS--- val features = ArrayList() for (s in stopsSorted){ if (s.latitude!=null && s.longitude!=null) { val loc = if (showOnTopOfLine) findOptimalPosition(s, pointsList) else LatLng(s.latitude!!, s.longitude!!) features.add( Feature.fromGeometry( Point.fromLngLat(loc.longitude, loc.latitude), JsonObject().apply { addProperty("id", s.ID) addProperty("name", s.stopDefaultName) //addProperty("routes", s.routesThatStopHereToString()) // Add routes array to JSON object } ) ) } } // -- ARROWS -- //val splitPolyline = MapLibreUtils.splitPolyWhenDistanceTooBig(pointsList, 200.0) val arrowFeatures = ArrayList() val pointsIndexToShowIcon = MapLibreUtils.findPointsToPutDirectionMarkers(pointsList, stopsSorted, 750.0) for (idx in pointsIndexToShowIcon){ val pnow = pointsList[idx] val otherp = if(idx>1) pointsList[idx-1] else pointsList[idx+1] val bearing = if (idx>1) MapLibreUtils.getBearing(pointsList[idx-1], pnow) else MapLibreUtils.getBearing(pnow, pointsList[idx+1]) arrowFeatures.add(Feature.fromGeometry( Point.fromLngLat((pnow.longitude+otherp.longitude)/2, (pnow.latitude+otherp.latitude)/2 ), //average JsonObject().apply { addProperty("bearing", bearing) } )) } Log.d(DEBUG_TAG,"Have put ${features.size} stops to display") // if the layer is already started, substitute the stops inside, otherwise start it if (stopsLayerStarted) { stopsSource.setGeoJson(FeatureCollection.fromFeatures(features)) polylineSource.setGeoJson(lineFeature) polyArrowSource.setGeoJson(FeatureCollection.fromFeatures(arrowFeatures)) lastStopsSizeShown = features.size } else map?.let { Log.d(DEBUG_TAG, "Map stop layer is not started yet, init layer") initStopsPolyLineLayers(mapStyle, FeatureCollection.fromFeatures(features),lineFeature, FeatureCollection.fromFeatures(arrowFeatures)) Log.d(DEBUG_TAG,"Started stops layer on map") lastStopsSizeShown = features.size stopsLayerStarted = true } ?:{ Log.e(DEBUG_TAG, "Stops layer is not started!!") } /* OLD CODE for(s in stops){ val gp = val marker = MarkerUtils.makeMarker( gp, s.ID, s.stopDefaultName, s.routesThatStopHereToString(), map,stopTouchResponder, stopIcon, R.layout.linedetail_stop_infowindow, R.color.line_drawn_poly ) marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER) stopsOverlay.add(marker) } */ //POINTS LIST IS NOT IN ORDER ANY MORE //if(!map.overlayManager.contains(stopsOverlay)){ // map.overlayManager.add(stopsOverlay) //} if(zoomToPattern) zoomToCurrentPattern() //map.invalidate() } private fun initializeRecyclerView(){ val llManager = LinearLayoutManager(context) llManager.orientation = LinearLayoutManager.VERTICAL stopsRecyclerView.layoutManager = llManager } private fun showStopsInRecyclerView(stops: List){ Log.d(DEBUG_TAG, "Setting stops from: "+viewModel.currentPatternStops.value) val orderBy = viewModel.currentPatternStops.value!!.withIndex().associate{it.value.stopGtfsId to it.index} val stopsSorted = stops.sortedBy { s -> orderBy[s.gtfsID] } val numStops = stopsSorted.size Log.d(DEBUG_TAG, "RecyclerView adapter is: ${stopsRecyclerView.adapter}") val setNewAdapter = true if(setNewAdapter){ stopsRecyclerView.adapter = StopRecyclerAdapter( stopsSorted, stopAdapterListener, StopRecyclerAdapter.Use.LINES, NameCapitalize.FIRST ) } } /** * This method fixes the display of the pattern, to be used when clicking on a bus */ private fun showPatternWithCode(patternId: String){ //var index = 0 Log.d(DEBUG_TAG, "Showing pattern with code $patternId ") for (i in currentPatterns.indices){ val pattStop = currentPatterns[i] if(pattStop.pattern.code == patternId){ Log.d(DEBUG_TAG, "Pattern found in position $i") //setPatternAndReqStops(pattStop) patternsSpinner.setSelection(i) break } } } private fun removeVehiclesData(vehs: List){ for(v in vehs){ if (updatesByVehDict.contains(v)) updatesByVehDict.remove(v) } } /** * Update function for the bus positions * Takes the processed updates and saves them accordingly * Copied from MapLibreFragment, removing the labels */ private fun updateBusPositionsInMap(incomingData: HashMap>){ val vehsNew = HashSet(incomingData.values.map { up -> up.first.vehicle }) val vehsOld = HashSet(updatesByVehDict.keys) Log.d(DEBUG_TAG, "In fragment, have ${incomingData.size} updates to show") var countUpds = 0 //val symbolsToUpdate = ArrayList() for (upsWithTrp in incomingData.values){ val pos = upsWithTrp.first val patternStops = upsWithTrp.second val vehID = pos.vehicle var animate = false if (vehsOld.contains(vehID)){ //update position only if the starting or the stopping position of the animation are in the view val oldPos = updatesByVehDict[vehID]?.posUpdate val oldPattern = updatesByVehDict[vehID]?.pattern var avoidShowingUpdateBecauseIsImpossible = false oldPos?.let{ if(it.routeID!=pos.routeID) { val dist = LatLng(it.latitude, it.longitude).distanceTo(LatLng(pos.latitude, pos.longitude)) val speed = dist*3.6 / (pos.timestamp - it.timestamp) //this should be in km/h Log.w(DEBUG_TAG, "Vehicle $vehID changed route from ${oldPos.routeID} to ${pos.routeID}, distance: $dist, speed: $speed") if (speed > 120 || speed < 0){ avoidShowingUpdateBecauseIsImpossible = true } } } if (avoidShowingUpdateBecauseIsImpossible){ // DO NOT SHOW THIS SHIT Log.w(DEBUG_TAG, "Update for vehicle $vehID skipped") continue } val samePosition = oldPos?.let { (it.latitude==pos.latitude)&&(it.longitude == pos.longitude) }?:false val setPattern = (oldPattern==null) && (patternStops!=null) if((!samePosition)|| setPattern) { //TODO RESTORE THIS PART /*val isPositionInBounds = isInsideVisibleRegion( pos.latitude, pos.longitude, true ) || (oldPos?.let { isInsideVisibleRegion(it.latitude,it.longitude,true) } ?: false) */ val skip = true if (skip) { //animate = true // set the pattern data too updatesByVehDict[vehID]!!.pattern = patternStops?.pattern //this moves both the icon and the label animateNewPositionMove(pos) } else { //update updatesByVehDict[vehID] = LivePositionTripPattern(pos,patternStops?.pattern) /*busLabelSymbolsByVeh[vehID]?.let { it.latLng = LatLng(pos.latitude, pos.longitude) symbolsToUpdate.add(it) }*/ //if(vehShowing==vehID) // map?.animateCamera(CameraUpdateFactory.newLatLng(LatLng(pos.latitude, pos.longitude)),500) //TODO: Follow the vehicle } } countUpds++ } else{ //not inside // update it simply updatesByVehDict[vehID] = LivePositionTripPattern(pos, patternStops?.pattern) //createLabelForVehicle(pos) //if(vehShowing==vehID) // map?.animateCamera(CameraUpdateFactory.newLatLng(LatLng(pos.latitude, pos.longitude)),500) } if (vehID == vehShowing){ //update the data showVehicleTripInBottomSheet(vehID) } } //symbolManager.update(symbolsToUpdate) //remove old positions Log.d(DEBUG_TAG, "Updated $countUpds vehicles") vehsOld.removeAll(vehsNew) //now vehsOld contains the vehicles id for those that have NOT been updated val currentTimeStamp = System.currentTimeMillis() /1000 for(vehID in vehsOld){ //remove after 2 minutes of inactivity if (updatesByVehDict[vehID]!!.posUpdate.timestamp - currentTimeStamp > 2*60){ updatesByVehDict.remove(vehID) //removeVehicleLabel(vehID) } } //update UI updatePositionsIcons(false) } /** * This is the tricky part, animating the transitions * Basically, we need to set the new positions with the data and redraw them all */ private fun animateNewPositionMove(positionUpdate: LivePositionUpdate){ if (positionUpdate.vehicle !in updatesByVehDict.keys) return val vehID = positionUpdate.vehicle val currentUpdate = updatesByVehDict[positionUpdate.vehicle] currentUpdate?.let { it -> //cancel current animation on vehicle animatorsByVeh[vehID]?.cancel() val posUp = it.posUpdate val currentPos = LatLng(posUp.latitude, posUp.longitude) val newPos = LatLng(positionUpdate.latitude, positionUpdate.longitude) val valueAnimator = ValueAnimator.ofObject(MapLibreUtils.LatLngEvaluator(), currentPos, newPos) valueAnimator.addUpdateListener(object : ValueAnimator.AnimatorUpdateListener { private var latLng: LatLng? = null override fun onAnimationUpdate(animation: ValueAnimator) { latLng = animation.animatedValue as LatLng //update position on animation val update = updatesByVehDict[positionUpdate.vehicle]!! latLng?.let { ll-> update.posUpdate.latitude = ll.latitude update.posUpdate.longitude = ll.longitude updatePositionsIcons(false) } } }) /*valueAnimator.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { super.onAnimationStart(animation) //val update = positionsByVehDict[positionUpdate.vehicle]!! //remove the label at the start of the animation //removeVehicleLabel(vehID) val annot = busLabelSymbolsByVeh[vehID] annot?.let { sym -> sym.textOpacity = 0.0f symbolsToUpdate.add(sym) } } override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) /*val annot = busLabelSymbolsByVeh[vehID] annot?.let { sym -> sym.textOpacity = 1.0f sym.latLng = newPos //LatLng(newPos) symbolsToUpdate.add(sym) } */ } }) */ animatorsByVeh[vehID]?.cancel() //set the new position as the current one but with the old lat and lng positionUpdate.latitude = posUp.latitude positionUpdate.longitude = posUp.longitude updatesByVehDict[vehID]!!.posUpdate = positionUpdate valueAnimator.duration = 300 valueAnimator.interpolator = LinearInterpolator() valueAnimator.start() animatorsByVeh[vehID] = valueAnimator } ?: { Log.e(DEBUG_TAG, "Have to run animation for veh ${positionUpdate.vehicle} but not in the dict, adding") //updatesByVehDict[positionUpdate.vehicle] = positionUpdate } } /** * Update the bus positions displayed on the map, from the existing data */ private fun updatePositionsIcons(forced: Boolean){ //avoid frequent updates val currentTime = System.currentTimeMillis() if(!forced && currentTime - lastUpdateTime < 60){ //DO NOT UPDATE THE MAP return } val features = ArrayList()//stops.mapNotNull { stop -> //stop.latitude?.let { lat -> // stop.longitude?.let { lon -> for (dat in updatesByVehDict.values){ //if (s.latitude!=null && s.longitude!=null) val pos = dat.posUpdate val point = Point.fromLngLat(pos.longitude, pos.latitude) features.add( Feature.fromGeometry( point, JsonObject().apply { addProperty("veh", pos.vehicle) addProperty("trip", pos.tripID) addProperty("bearing", pos.bearing ?:0.0f) addProperty("line", pos.routeID) } ) ) /*busLabelSymbolsByVeh[pos.vehicle]?.let { it.latLng = LatLng(pos.latitude, pos.longitude) symbolsToUpdate.add(it) } */ } busesSource.setGeoJson(FeatureCollection.fromFeatures(features)) //update labels, clear cache to be used //symbolManager.update(symbolsToUpdate) //symbolsToUpdate.clear() lastUpdateTime = System.currentTimeMillis() } override fun onResume() { super.onResume() Log.d(DEBUG_TAG, "Resetting paused from onResume") mapView.onResume() pausedFragment = false val keySourcePositions = getString(R.string.pref_positions_source) useMQTTPositions = PreferenceManager.getDefaultSharedPreferences(requireContext()) .getString(keySourcePositions, "mqtt").contentEquals("mqtt") //separate paths if(useMQTTPositions) liveBusViewModel.requestMatoPosUpdates(GtfsUtils.getLineNameFromGtfsID(lineID)) else liveBusViewModel.requestGTFSUpdates() if(mapViewModel.currentLat.value!=MapViewModel.INVALID) { Log.d(DEBUG_TAG, "mapViewModel posi: ${mapViewModel.currentLat.value}, ${mapViewModel.currentLong.value}"+ " zoom ${mapViewModel.currentZoom.value}") //THIS WAS A FIX FOR THE OLD OSMDROID MAP /*val controller = map.controller viewLifecycleOwner.lifecycleScope.launch { delay(100) Log.d(DEBUG_TAG, "zooming back to point") controller.animateTo(GeoPoint(mapViewModel.currentLat.value!!, mapViewModel.currentLong.value!!), mapViewModel.currentZoom.value!!,null,null) //controller.setCenter(GeoPoint(mapViewModel.currentLat.value!!, mapViewModel.currentLong.value!!)) //controller.setZoom(mapViewModel.currentZoom.value!!) } */ } //initialize GUI here fragmentListener.readyGUIfor(FragmentKind.LINES) } override fun onPause() { super.onPause() mapView.onPause() if(useMQTTPositions) liveBusViewModel.stopMatoUpdates() pausedFragment = true //save map val camera = map?.cameraPosition camera?.let {cam-> mapViewModel.currentLat.value = cam.target?.latitude ?: -400.0 mapViewModel.currentLong.value = cam.target?.longitude ?: -400.0 mapViewModel.currentZoom.value = cam.zoom } } override fun onStart() { super.onStart() mapView.onStart() } override fun onDestroy() { super.onDestroy() mapView.onDestroy() } override fun onStop() { super.onStop() mapView.onStop() shownStopInBottomSheet?.let { mapViewModel.stopShowing = it } shouldMapLocationBeReactivated = locationComponent.isLocationComponentEnabled } override fun onDestroyView() { map?.run { Log.d(DEBUG_TAG, "Saving camera position") savedCameraPosition = cameraPosition } super.onDestroyView() Log.d(DEBUG_TAG, "Destroying the views") /*mapStyle.removeLayer(STOPS_LAYER_ID) mapStyle?.removeSource(STOPS_SOURCE_ID) mapStyle.removeLayer(POLYLINE_LAYER) mapStyle.removeSource(POLYLINE_SOURCE) */ //stopsLayerStarted = false } override fun onMapDestroy() { mapStyle.removeLayer(STOPS_LAYER_ID) mapStyle.removeSource(STOPS_SOURCE_ID) mapStyle.removeLayer(POLYLINE_LAYER) mapStyle.removeSource(POLYLINE_SOURCE) mapStyle.removeLayer(BUSES_LAYER_ID) mapStyle.removeSource(BUSES_SOURCE_ID) map?.locationComponent?.isLocationComponentEnabled = false } override fun getBaseViewForSnackBar(): View? { return null } companion object { private const val LINEID_KEY="lineID" private const val STOPID_FROM_KEY="stopID" private const val STOPS_SOURCE_ID = "stops-source" private const val STOPS_LAYER_ID = "stops-layer" private const val STOP_ACTIVE_IMG = "stop_active_img" private const val STOP_IMAGE_ID = "stop-img" private const val POLYLINE_LAYER = "polyline-layer" private const val POLYLINE_SOURCE = "polyline-source" private const val POLY_ARROWS_LAYER = "arrows-layer" private const val POLY_ARROWS_SOURCE = "arrows-source" private const val POLY_ARROW ="poly-arrow-img" private const val DEBUG_TAG="BusTO-LineDetalFragment" fun makeArgs(lineID: String, stopIDFrom: String?): Bundle{ val b = Bundle() b.putString(LINEID_KEY, lineID) b.putString(STOPID_FROM_KEY, stopIDFrom) return b } fun newInstance(lineID: String?, stopIDFrom: String?) = LinesDetailFragment().apply { lineID?.let { arguments = makeArgs(it, stopIDFrom) } } @JvmStatic private fun findOptimalPosition(stop: Stop, pointsList: MutableList): LatLng{ if(stop.latitude==null || stop.longitude ==null|| pointsList.isEmpty()) throw IllegalArgumentException() val sLat = stop.latitude!! val sLong = stop.longitude!! if(pointsList.size < 2) return pointsList[0] pointsList.sortBy { utils.measuredistanceBetween(sLat, sLong, it.latitude, it.longitude) } val p1 = pointsList[0] val p2 = pointsList[1] if (p1.longitude == p2.longitude){ //Log.e(DEBUG_TAG, "Same longitude") return LatLng(sLat, p1.longitude) } else if (p1.latitude == p2.latitude){ //Log.d(DEBUG_TAG, "Same latitude") return LatLng(p2.latitude,sLong) } val m = (p1.latitude - p2.latitude) / (p1.longitude - p2.longitude) val minv = (p1.longitude-p2.longitude)/(p1.latitude - p2.latitude) val cR = p1.latitude - p1.longitude * m val longNew = (minv * sLong + sLat -cR ) / (m+minv) val latNew = (m*longNew + cR) //Log.d(DEBUG_TAG,"Stop ${stop.ID} old pos: ($sLat, $sLong), new pos ($latNew,$longNew)") return LatLng(latNew,longNew) } private const val DEFAULT_CENTER_LAT = 45.12 private const val DEFAULT_CENTER_LON = 7.6858 } enum class BottomShowing{ STOP, VEHICLE } } \ No newline at end of file diff --git a/app/src/main/java/it/reyboz/bustorino/fragments/MapFragment.java b/app/src/main/java/it/reyboz/bustorino/fragments/MapFragment.java deleted file mode 100644 index 8173f7c..0000000 --- a/app/src/main/java/it/reyboz/bustorino/fragments/MapFragment.java +++ /dev/null @@ -1,837 +0,0 @@ -/* - BusTO - Fragments components - Copyright (C) 2020 Andrea Ugo - Copyright (C) 2021 Fabio Mazza - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - */ -package it.reyboz.bustorino.fragments; - -import android.Manifest; -import android.animation.ObjectAnimator; -import android.annotation.SuppressLint; -import android.content.Context; - -import android.graphics.drawable.Drawable; -import android.location.Location; -import android.location.LocationManager; -import android.os.Bundle; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageButton; -import android.widget.Toast; - -import androidx.activity.result.ActivityResultLauncher; -import androidx.activity.result.contract.ActivityResultContracts; -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; -import androidx.coordinatorlayout.widget.CoordinatorLayout; -import androidx.core.content.res.ResourcesCompat; -import androidx.lifecycle.ViewModelProvider; -import androidx.preference.PreferenceManager; - -import it.reyboz.bustorino.backend.gtfs.LivePositionUpdate; -import it.reyboz.bustorino.backend.mato.MQTTMatoClient; -import it.reyboz.bustorino.backend.utils; -import it.reyboz.bustorino.data.gtfs.MatoPattern; -import it.reyboz.bustorino.data.gtfs.TripAndPatternWithStops; -import it.reyboz.bustorino.map.*; -import it.reyboz.bustorino.viewmodels.LivePositionsViewModel; -import it.reyboz.bustorino.viewmodels.StopsMapViewModel; -import org.osmdroid.api.IGeoPoint; -import org.osmdroid.api.IMapController; -import org.osmdroid.config.Configuration; -import org.osmdroid.events.DelayedMapListener; -import org.osmdroid.events.MapListener; -import org.osmdroid.events.ScrollEvent; -import org.osmdroid.events.ZoomEvent; -import org.osmdroid.tileprovider.tilesource.TileSourceFactory; -import org.osmdroid.util.BoundingBox; -import org.osmdroid.util.GeoPoint; -import org.osmdroid.views.MapView; -import org.osmdroid.views.overlay.FolderOverlay; -import org.osmdroid.views.overlay.Marker; -import org.osmdroid.views.overlay.infowindow.InfoWindow; -import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider; - -import java.util.*; - -import kotlin.Pair; -import it.reyboz.bustorino.R; -import it.reyboz.bustorino.backend.Stop; -import it.reyboz.bustorino.middleware.GeneralActivity; -import it.reyboz.bustorino.util.Permissions; - -import static it.reyboz.bustorino.fragments.SettingsFragment.LIVE_POSITIONS_PREF_MQTT_VALUE; - -public class MapFragment extends ScreenBaseFragment { - - //private static final String TAG = "Busto-MapActivity"; - private static final String MAP_CURRENT_ZOOM_KEY = "map-current-zoom"; - private static final String MAP_CENTER_LAT_KEY = "map-center-lat"; - private static final String MAP_CENTER_LON_KEY = "map-center-lon"; - private static final String FOLLOWING_LOCAT_KEY ="following"; - - public static final String BUNDLE_LATIT = "lat"; - public static final String BUNDLE_LONGIT = "lon"; - public static final String BUNDLE_NAME = "name"; - public static final String BUNDLE_ID = "ID"; - public static final String BUNDLE_ROUTES_STOPPING = "routesStopping"; - - public static final String FRAGMENT_TAG="BusTOMapFragment"; - - - private static final double DEFAULT_CENTER_LAT = 45.0708; - private static final double DEFAULT_CENTER_LON = 7.6858; - private static final double POSITION_FOUND_ZOOM = 18.3; - public static final double NO_POSITION_ZOOM = 17.1; - - private static final String DEBUG_TAG=FRAGMENT_TAG; - - protected FragmentListenerMain listenerMain; - - private HashSet shownStops = null; - - - private MapView map = null; - public Context ctx; - private LocationOverlay mLocationOverlay = null; - private FolderOverlay stopsFolderOverlay = null; - private Bundle savedMapState = null; - protected ImageButton btCenterMap; - protected ImageButton btFollowMe; - - protected CoordinatorLayout coordLayout; - private boolean hasMapStartFinished = false; - private boolean followingLocation = false; - - //the ViewModel from which we get the stop to display in the map - private StopsMapViewModel stopsViewModel; - - //private GtfsPositionsViewModel gtfsPosViewModel; //= new ViewModelProvider(this).get(MapViewModel.class); - private LivePositionsViewModel livePositionsViewModel; - private Boolean useMQTTViewModel = true; - - private final HashMap busPositionMarkersByTrip = new HashMap<>(); - private FolderOverlay busPositionsOverlay = null; - - private final HashMap tripMarkersAnimators = new HashMap<>(); - - protected final CustomInfoWindow.TouchResponder responder = new CustomInfoWindow.TouchResponder() { - @Override - public void onActionUp(@NonNull String stopID, @Nullable String stopName) { - if (listenerMain!= null){ - Log.d(DEBUG_TAG, "Asked to show arrivals for stop ID: "+stopID); - listenerMain.requestArrivalsForStopID(stopID); - } - } - }; - protected final LocationOverlay.OverlayCallbacks locationCallbacks = new LocationOverlay.OverlayCallbacks() { - @Override - public void onDisableFollowMyLocation() { - updateGUIForLocationFollowing(false); - followingLocation=false; - } - - @Override - public void onEnableFollowMyLocation() { - updateGUIForLocationFollowing(true); - followingLocation=true; - } - }; - - private final ActivityResultLauncher positionRequestLauncher = - registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), result -> { - if (result == null){ - Log.w(DEBUG_TAG, "Got asked permission but request is null, doing nothing?"); - } - else if(Boolean.TRUE.equals(result.get(Manifest.permission.ACCESS_COARSE_LOCATION)) && - Boolean.TRUE.equals(result.get(Manifest.permission.ACCESS_FINE_LOCATION))){ - - map.getOverlays().remove(mLocationOverlay); - startLocationOverlay(true, map); - if(getContext()==null || getContext().getSystemService(Context.LOCATION_SERVICE)==null) - return; - LocationManager locationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE); - @SuppressLint("MissingPermission") - Location userLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); - if (userLocation != null) { - map.getController().setZoom(POSITION_FOUND_ZOOM); - GeoPoint startPoint = new GeoPoint(userLocation); - setLocationFollowing(true); - map.getController().setCenter(startPoint); - } - } - else Log.w(DEBUG_TAG,"No location permission"); - }); - - public MapFragment() { - } - public static MapFragment getInstance(){ - return new MapFragment(); - } - public static MapFragment getInstance(@NonNull Stop stop){ - MapFragment fragment= new MapFragment(); - Bundle args = new Bundle(); - args.putDouble(BUNDLE_LATIT, stop.getLatitude()); - args.putDouble(BUNDLE_LONGIT, stop.getLongitude()); - args.putString(BUNDLE_NAME, stop.getStopDisplayName()); - args.putString(BUNDLE_ID, stop.ID); - args.putString(BUNDLE_ROUTES_STOPPING, stop.routesThatStopHereToString()); - fragment.setArguments(args); - - return fragment; - } - //public static MapFragment getInstance(@NonNull Stop stop){ - // return getInstance(stop.getLatitude(), stop.getLongitude(), stop.getStopDisplayName(), stop.ID); - //} - - - @Nullable - @Override - public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { - //use the same layout as the activity - View root = inflater.inflate(R.layout.fragment_map, container, false); - if (getContext() == null){ - throw new IllegalStateException(); - } - ctx = getContext().getApplicationContext(); - Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(ctx)); - map = root.findViewById(R.id.map); - map.setTileSource(TileSourceFactory.MAPNIK); - //map.setTilesScaledToDpi(true); - map.setFlingEnabled(true); - - // add ability to zoom with 2 fingers - map.setMultiTouchControls(true); - - btCenterMap = root.findViewById(R.id.centerMapImageButton); - btFollowMe = root.findViewById(R.id.followUserImageButton); - coordLayout = root.findViewById(R.id.coord_layout); - - //setup FolderOverlay - stopsFolderOverlay = new FolderOverlay(); - //setup Bus Markers Overlay - busPositionsOverlay = new FolderOverlay(); - //reset shown bus updates - busPositionMarkersByTrip.clear(); - tripMarkersAnimators.clear(); - //set map not done - hasMapStartFinished = false; - - String keySourcePositions=getString(R.string.pref_positions_source); - useMQTTViewModel = ( - PreferenceManager.getDefaultSharedPreferences(requireContext()) - .getString(keySourcePositions,LIVE_POSITIONS_PREF_MQTT_VALUE).contentEquals(LIVE_POSITIONS_PREF_MQTT_VALUE)); - - - //Start map from bundle - if (savedInstanceState !=null) - startMap(getArguments(), savedInstanceState); - else startMap(getArguments(), savedMapState); - //set listeners - map.addMapListener(new DelayedMapListener(new MapListener() { - - @Override - public boolean onScroll(ScrollEvent paramScrollEvent) { - requestStopsToShow(); - //Log.d(DEBUG_TAG, "Scrolling"); - //if (moveTriggeredByCode) moveTriggeredByCode =false; - //else setLocationFollowing(false); - return true; - } - - @Override - public boolean onZoom(ZoomEvent event) { - requestStopsToShow(); - return true; - } - - })); - - - btCenterMap.setOnClickListener(v -> { - //Log.i(TAG, "centerMap clicked "); - if(Permissions.bothLocationPermissionsGranted(getContext())) { - final GeoPoint myPosition = mLocationOverlay.getMyLocation(); - map.getController().animateTo(myPosition); - } else - Toast.makeText(getContext(), R.string.enable_position_message_map, Toast.LENGTH_SHORT) - .show(); - }); - - btFollowMe.setOnClickListener(v -> { - //Log.i(TAG, "btFollowMe clicked "); - if(Permissions.bothLocationPermissionsGranted(getContext())) - setLocationFollowing(!followingLocation); - else - Toast.makeText(getContext(), R.string.enable_position_message_map, Toast.LENGTH_SHORT) - .show(); - }); - - - return root; - } - - @Override - public void onAttach(@NonNull Context context) { - super.onAttach(context); - - ViewModelProvider provider = new ViewModelProvider(this); - //gtfsPosViewModel = provider.get(GtfsPositionsViewModel.class); - livePositionsViewModel = provider.get(LivePositionsViewModel.class); - stopsViewModel = provider.get(StopsMapViewModel.class); - - - if (context instanceof FragmentListenerMain) { - listenerMain = (FragmentListenerMain) context; - } else { - throw new RuntimeException(context.toString() - + " must implement FragmentListenerMain"); - } - } - @Override - public void onDetach() { - super.onDetach(); - listenerMain = null; - //stop animations - - // setupOnAttached = true; - Log.w(DEBUG_TAG, "Fragment detached"); - } - - @Override - public void onPause() { - super.onPause(); - Log.w(DEBUG_TAG, "On pause called mapfrag"); - saveMapState(); - for (ObjectAnimator animator : tripMarkersAnimators.values()) { - if(animator!=null && animator.isRunning()){ - animator.cancel(); - } - } - tripMarkersAnimators.clear(); - if(useMQTTViewModel) livePositionsViewModel.stopMatoUpdates(); - - } - - /** - * Save the map state inside the fragment - * (calls saveMapState(bundle)) - */ - private void saveMapState(){ - savedMapState = new Bundle(); - saveMapState(savedMapState); - } - - /** - * Save the state of the map to restore it to a later time - * @param bundle the bundle in which to save the data - */ - private void saveMapState(Bundle bundle){ - Log.d(DEBUG_TAG, "Saving state, location following: "+followingLocation); - bundle.putBoolean(FOLLOWING_LOCAT_KEY, followingLocation); - if (map == null){ - //The map is null, it can happen? - Log.e(DEBUG_TAG, "Cannot save map center, map is null"); - return; - } - final IGeoPoint loc = map.getMapCenter(); - bundle.putDouble(MAP_CENTER_LAT_KEY, loc.getLatitude()); - bundle.putDouble(MAP_CENTER_LON_KEY, loc.getLongitude()); - bundle.putDouble(MAP_CURRENT_ZOOM_KEY, map.getZoomLevelDouble()); - } - - - @Override - public void onResume() { - super.onResume(); - //TODO: cleanup duplicate code (maybe merging the positions classes?) - if(listenerMain!=null) listenerMain.readyGUIfor(FragmentKind.MAP); - /// choose which to use - String keySourcePositions=getString(R.string.pref_positions_source); - useMQTTViewModel = PreferenceManager.getDefaultSharedPreferences(requireContext()) - .getString(keySourcePositions,LIVE_POSITIONS_PREF_MQTT_VALUE).contentEquals( - LIVE_POSITIONS_PREF_MQTT_VALUE); - if(livePositionsViewModel !=null) { - //gtfsPosViewModel.requestUpdates(); - if(useMQTTViewModel) - livePositionsViewModel.requestMatoPosUpdates(MQTTMatoClient.LINES_ALL); - else - livePositionsViewModel.requestGTFSUpdates(); - //mapViewModel.testCascade(); - livePositionsViewModel.isLastWorkResultGood().observe(this, d -> - Log.d(DEBUG_TAG, "Last trip download result is "+d)); - livePositionsViewModel.getTripsGtfsIDsToQuery().observe(this, dat -> { - Log.i(DEBUG_TAG, "Have these trips IDs missing from the DB, to be queried: "+dat); - livePositionsViewModel.downloadTripsFromMato(dat); - /*MatoTripsDownloadWorker.Companion.requestMatoTripsDownload(dat, - requireContext().getApplicationContext(), - "BusTO-MatoTripDownload"); - - */ - }); - } /*else if(gtfsPosViewModel!=null){ - gtfsPosViewModel.requestUpdates(); - gtfsPosViewModel.getTripsGtfsIDsToQuery().observe(this, dat -> { - Log.i(DEBUG_TAG, "Have these trips IDs missing from the DB, to be queried: "+dat); - //gtfsPosViewModel.downloadTripsFromMato(dat); - MatoTripsDownloadWorker.Companion.downloadTripsFromMato(dat,getContext().getApplicationContext(), - "BusTO-MatoTripDownload"); - }); - } - */ - else Log.e(DEBUG_TAG, "livePositionsViewModel is null at onResume"); - - //rerequest stop - stopsViewModel.requestStopsInBoundingBox(map.getBoundingBox()); - } - - private void startRequestsPositions(){ - if (livePositionsViewModel != null) { - //should always be the case - livePositionsViewModel.getUpdatesWithTripAndPatterns().observe(getViewLifecycleOwner(), data -> { - Log.d(DEBUG_TAG, "Have " + data.size() + " trip updates, has Map start finished: " + hasMapStartFinished); - if (hasMapStartFinished) updateBusPositionsInMap(data); - - if(!isDetached() && !useMQTTViewModel) - livePositionsViewModel.requestDelayedGTFSUpdates(3000); - - }); - - } else { - Log.e(DEBUG_TAG, "PositionsViewModel is null"); - } - } - - @Override - public void onSaveInstanceState(@NonNull Bundle outState) { - saveMapState(outState); - - super.onSaveInstanceState(outState); - } - - //own methods - - /** - * Switch following the location on and off - * @param value true if we want to follow location - */ - public void setLocationFollowing(Boolean value){ - followingLocation = value; - if(mLocationOverlay==null || getContext() == null || map ==null) - //nothing else to do - return; - if (value){ - mLocationOverlay.enableFollowLocation(); - } else { - mLocationOverlay.disableFollowLocation(); - } - } - - /** - * Do all the stuff you need to do on the gui, when parameter is changed to value - * @param following value - */ - protected void updateGUIForLocationFollowing(boolean following){ - if (following) - btFollowMe.setImageResource(R.drawable.ic_follow_me_on); - else - btFollowMe.setImageResource(R.drawable.ic_follow_me); - - } - - /** - * Build the location overlay. Enable only when - * a) we know we have the permission - * b) the location map is set - */ - private void startLocationOverlay(boolean enableLocation, MapView map){ - if(getActivity()== null) throw new IllegalStateException("Cannot enable LocationOverlay now"); - // Location Overlay - // from OpenBikeSharing (THANK GOD) - Log.d(DEBUG_TAG, "Starting position overlay"); - GpsMyLocationProvider imlp = new GpsMyLocationProvider(getActivity().getBaseContext()); - imlp.setLocationUpdateMinDistance(5); - imlp.setLocationUpdateMinTime(2000); - - final LocationOverlay overlay = new LocationOverlay(imlp,map, locationCallbacks); - if (enableLocation) overlay.enableMyLocation(); - overlay.setOptionsMenuEnabled(true); - - //map.getOverlays().add(this.mLocationOverlay); - this.mLocationOverlay = overlay; - map.getOverlays().add(mLocationOverlay); - } - - public void startMap(Bundle incoming, Bundle savedInstanceState) { - //Check that we're attached - GeneralActivity activity = getActivity() instanceof GeneralActivity ? (GeneralActivity) getActivity() : null; - if(getContext()==null|| activity==null){ - //we are not attached - Log.e(DEBUG_TAG, "Calling startMap when not attached"); - return; - }else{ - Log.d(DEBUG_TAG, "Starting map from scratch"); - } - //clear previous overlays - map.getOverlays().clear(); - - - //parse incoming bundle - GeoPoint marker = null; - String name = null; - String ID = null; - String routesStopping = ""; - if (incoming != null) { - double lat = incoming.getDouble(BUNDLE_LATIT); - double lon = incoming.getDouble(BUNDLE_LONGIT); - marker = new GeoPoint(lat, lon); - name = incoming.getString(BUNDLE_NAME); - ID = incoming.getString(BUNDLE_ID); - routesStopping = incoming.getString(BUNDLE_ROUTES_STOPPING, ""); - } - - - //ask for location permission - if(!Permissions.bothLocationPermissionsGranted(activity)){ - if(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)){ - //TODO: show dialog for permission rationale - Toast.makeText(activity, R.string.enable_position_message_map, Toast.LENGTH_SHORT).show(); - } - positionRequestLauncher.launch(Permissions.LOCATION_PERMISSIONS); - - } - - shownStops = new HashSet<>(); - // move the map on the marker position or on a default view point: Turin, Piazza Castello - // and set the start zoom - IMapController mapController = map.getController(); - GeoPoint startPoint = null; - startLocationOverlay(Permissions.bothLocationPermissionsGranted(activity), - map); - // set the center point - if (marker != null) { - //startPoint = marker; - mapController.setZoom(POSITION_FOUND_ZOOM); - setLocationFollowing(false); - // put the center a little bit off (animate later) - startPoint = new GeoPoint(marker); - startPoint.setLatitude(marker.getLatitude()+ utils.angleRawDifferenceFromMeters(20)); - startPoint.setLongitude(marker.getLongitude()-utils.angleRawDifferenceFromMeters(20)); - //don't need to do all the rest since we want to show a point - } else if (savedInstanceState != null && savedInstanceState.containsKey(MAP_CURRENT_ZOOM_KEY)) { - mapController.setZoom(savedInstanceState.getDouble(MAP_CURRENT_ZOOM_KEY)); - mapController.setCenter(new GeoPoint(savedInstanceState.getDouble(MAP_CENTER_LAT_KEY), - savedInstanceState.getDouble(MAP_CENTER_LON_KEY))); - Log.d(DEBUG_TAG, "Location following from savedInstanceState: "+savedInstanceState.getBoolean(FOLLOWING_LOCAT_KEY)); - setLocationFollowing(savedInstanceState.getBoolean(FOLLOWING_LOCAT_KEY)); - } else { - Log.d(DEBUG_TAG, "No position found from intent or saved state"); - boolean found = false; - LocationManager locationManager = - (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE); - //check for permission - if (locationManager != null && Permissions.bothLocationPermissionsGranted(activity)) { - - @SuppressLint("MissingPermission") - Location userLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); - - if (userLocation != null) { - double distan = utils.measuredistanceBetween(userLocation.getLatitude(), userLocation.getLongitude(), - DEFAULT_CENTER_LAT, DEFAULT_CENTER_LON); - if (distan < 100_000.0) { - mapController.setZoom(POSITION_FOUND_ZOOM); - startPoint = new GeoPoint(userLocation); - found = true; - setLocationFollowing(true); - } - } - } - if(!found){ - startPoint = new GeoPoint(DEFAULT_CENTER_LAT, DEFAULT_CENTER_LON); - mapController.setZoom(NO_POSITION_ZOOM); - setLocationFollowing(false); - } - } - - // set the minimum zoom level - map.setMinZoomLevel(15.0); - //add contingency check (shouldn't happen..., but) - - if (startPoint != null) { - mapController.setCenter(startPoint); - } - - - //add stops overlay - //map.getOverlays().add(mLocationOverlay); - map.getOverlays().add(this.stopsFolderOverlay); - - Log.d(DEBUG_TAG, "Requesting stops load"); - // This is not necessary, by setting the center we already move - // the map and we trigger a stop request - //requestStopsToShow(); - if (marker != null) { - // make a marker with the info window open for the searched marker - //TODO: make Stop Bundle-able - Marker stopMarker = makeMarker(marker, ID , name, routesStopping,true); - map.getController().animateTo(marker); - } - //add the overlays with the bus stops - if(busPositionsOverlay == null){ - //Log.i(DEBUG_TAG, "Null bus positions overlay,redo"); - busPositionsOverlay = new FolderOverlay(); - } - startRequestsPositions(); - if(stopsViewModel !=null){ - - stopsViewModel.getStopsInBoundingBox().observe(getViewLifecycleOwner(), - this::showStopsMarkers - ); - } else Log.d(DEBUG_TAG, "Cannot observe new stops in map, stopsViewModel is null"); - map.getOverlays().add(this.busPositionsOverlay); - //set map as started - hasMapStartFinished = true; - } - - /** - * Start a request to load the stops that are in the current view - * from the database - */ - private void requestStopsToShow(){ - // get the top, bottom, left and right screen's coordinate - BoundingBox bb = map.getBoundingBox(); - Log.d(DEBUG_TAG, "Requesting stops in bounding box, stopViewModel is null "+(stopsViewModel==null)); - if(stopsViewModel!=null){ - stopsViewModel.requestStopsInBoundingBox(bb); - } - /*double latFrom = bb.getLatSouth(); - double latTo = bb.getLatNorth(); - double lngFrom = bb.getLonWest(); - double lngTo = bb.getLonEast(); - if (stopFetcher!= null && stopFetcher.getStatus()!= AsyncTask.Status.FINISHED) - stopFetcher.cancel(true); - stopFetcher = new AsyncStopFetcher(this); - stopFetcher.execute( - new AsyncStopFetcher.BoundingBoxLimit(lngFrom,lngTo,latFrom, latTo)); - - */ - } - - private void updateBusMarker(final Marker marker, final LivePositionUpdate posUpdate, @Nullable boolean justCreated){ - GeoPoint position; - final String updateID = posUpdate.getTripID(); - if(!justCreated){ - position = marker.getPosition(); - if(posUpdate.getLatitude()!=position.getLatitude() || posUpdate.getLongitude()!=position.getLongitude()){ - GeoPoint newpos = new GeoPoint(posUpdate.getLatitude(), posUpdate.getLongitude()); - ObjectAnimator valueAnimator = MarkerUtils.makeMarkerAnimator( - map, marker, newpos, MarkerUtils.LINEAR_ANIMATION, 1200); - valueAnimator.setAutoCancel(true); - tripMarkersAnimators.put(updateID,valueAnimator); - valueAnimator.start(); - } - //marker.setPosition(new GeoPoint(posUpdate.getLatitude(), posUpdate.getLongitude())); - } else { - - position = new GeoPoint(posUpdate.getLatitude(), posUpdate.getLongitude()); - marker.setPosition(position); - } - - if(posUpdate.getBearing()!=null) - marker.setRotation(posUpdate.getBearing()*(-1.f)); - } - - private void updateBusPositionsInMap(HashMap> tripsPatterns){ - Log.d(DEBUG_TAG, "Updating positions of the buses"); - //if(busPositionsOverlay == null) busPositionsOverlay = new FolderOverlay(); - final ArrayList noPatternsTrips = new ArrayList<>(); - for(String tripID: tripsPatterns.keySet()) { - final Pair pair = tripsPatterns.get(tripID); - if (pair == null) continue; - final LivePositionUpdate update = pair.getFirst(); - final TripAndPatternWithStops tripWithPatternStops = pair.getSecond(); - - - //check if Marker is already created - if (busPositionMarkersByTrip.containsKey(tripID)){ - //need to change the position of the marker - final Marker marker = busPositionMarkersByTrip.get(tripID); - assert marker!=null; - updateBusMarker(marker, update, false); - if(marker.getInfoWindow()!=null && marker.getInfoWindow() instanceof BusInfoWindow){ - BusInfoWindow window = (BusInfoWindow) marker.getInfoWindow(); - if(tripWithPatternStops != null) { - //Log.d(DEBUG_TAG, "Update pattern for trip: "+tripID); - window.setPatternAndDraw(tripWithPatternStops.getPattern()); - } - - } - } else{ - //marker is not there, need to make it - if(map==null) Log.e(DEBUG_TAG, "Creating marker with null map, things will explode"); - final Marker marker = new Marker(map); - - /*final Drawable mDrawable = DrawableUtils.Companion.getScaledDrawableResources( - getResources(), - R.drawable.point_heading_icon, - R.dimen.map_icons_size, R.dimen.map_icons_size); - - */ - //String route = GtfsUtils.getLineNameFromGtfsID(update.getRouteID()); - final Drawable mdraw = ResourcesCompat.getDrawable(getResources(),R.drawable.map_bus_position_icon, null); - /*final Drawable mdraw = DrawableUtils.Companion.writeOnDrawable(getResources(), - R.drawable.point_heading_icon, - R.color.white, - route,12); - - */ - assert mdraw != null; - //mdraw.setBounds(0,0,28,28); - marker.setIcon(mdraw); - if(tripWithPatternStops == null){ - noPatternsTrips.add(tripID); - } - MatoPattern markerPattern = null; - if(tripWithPatternStops != null && tripWithPatternStops.getPattern()!=null) - markerPattern = tripWithPatternStops.getPattern(); - marker.setInfoWindow(new BusInfoWindow(map, update, markerPattern , false, (pattern) -> { })); - marker.setInfoWindowAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER); - marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER); - - updateBusMarker(marker, update, true); - // the overlay is null when it's not attached yet?5 - // cannot recreate it because it becomes null very soon - // if(busPositionsOverlay == null) busPositionsOverlay = new FolderOverlay(); - //save the marker - if(busPositionsOverlay!=null) { - busPositionsOverlay.add(marker); - busPositionMarkersByTrip.put(tripID, marker); - } - - } - } - if(noPatternsTrips.size()>0){ - Log.i(DEBUG_TAG, "These trips have no matching pattern: "+noPatternsTrips); - } - } - - /** - * Add stops as Markers on the map - * @param stops the list of stops that must be included - */ - protected void showStopsMarkers(List stops){ - if (getContext() == null || stops == null){ - //we are not attached - return; - } - boolean good = true; - - for (Stop stop : stops) { - if (shownStops.contains(stop.ID)){ - continue; - } - if(stop.getLongitude()==null || stop.getLatitude()==null) - continue; - - shownStops.add(stop.ID); - if(!map.isShown()){ - if(good) - Log.d(DEBUG_TAG, "Need to show stop but map is not shown, probably detached already"); - good = false; - continue; - } else if(map.getRepository() == null){ - Log.e(DEBUG_TAG, "Map view repository is null"); - } - GeoPoint marker = new GeoPoint(stop.getLatitude(), stop.getLongitude()); - - Marker stopMarker = makeMarker(marker, stop, false); - stopsFolderOverlay.add(stopMarker); - if (!map.getOverlays().contains(stopsFolderOverlay)) { - Log.w(DEBUG_TAG, "Map doesn't have folder overlay"); - } - good=true; - } - //Log.d(DEBUG_TAG,"We have " +stopsFolderOverlay.getItems().size()+" stops in the folderOverlay"); - //force redraw of markers - map.invalidate(); - } - - public Marker makeMarker(GeoPoint geoPoint, Stop stop, boolean isStartMarker){ - return makeMarker(geoPoint,stop.ID, - stop.getStopDefaultName(), - stop.routesThatStopHereToString(), isStartMarker); - } - - public Marker makeMarker(GeoPoint geoPoint, String stopID, String stopName, - String routesStopping, boolean isStartMarker) { - - // add a marker - final Marker marker = new Marker(map); - - // set custom info window as info window - CustomInfoWindow popup = new CustomInfoWindow(map, stopID, stopName, routesStopping, - responder, R.layout.linedetail_stop_infowindow, R.color.red_darker); - marker.setInfoWindow(popup); - - // make the marker clickable - marker.setOnMarkerClickListener((thisMarker, mapView) -> { - if (thisMarker.isInfoWindowOpen()) { - // on second click - Log.w(DEBUG_TAG, "Pressed on the click marker"); - } else { - // on first click - - // hide all opened info window - InfoWindow.closeAllInfoWindowsOn(map); - // show this particular info window - thisMarker.showInfoWindow(); - // move the map to its position - map.getController().animateTo(thisMarker.getPosition()); - } - - return true; - }); - - // set its position - marker.setPosition(geoPoint); - marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER); - // add to it an icon - //marker.setIcon(getResources().getDrawable(R.drawable.bus_marker)); - - marker.setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.bus_stop, ctx.getTheme())); - // add to it a title - marker.setTitle(stopName); - // set the description as the ID - marker.setSnippet(stopID); - - // show popup info window of the searched marker - if (isStartMarker) { - marker.showInfoWindow(); - //map.getController().animateTo(marker.getPosition()); - } - - return marker; - } - - @Nullable - @Override - public View getBaseViewForSnackBar() { - return coordLayout; - } - -} diff --git a/app/src/main/java/it/reyboz/bustorino/fragments/MapFragmentKt.kt b/app/src/main/java/it/reyboz/bustorino/fragments/MapFragmentKt.kt deleted file mode 100644 index 4cad925..0000000 --- a/app/src/main/java/it/reyboz/bustorino/fragments/MapFragmentKt.kt +++ /dev/null @@ -1,750 +0,0 @@ -/* - BusTO - Fragments components - Copyright (C) 2020 Andrea Ugo - Copyright (C) 2021 Fabio Mazza - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - */ -package it.reyboz.bustorino.fragments - -import android.Manifest -import android.animation.ObjectAnimator -import android.annotation.SuppressLint -import android.content.Context -import android.location.LocationManager -import android.os.Bundle -import android.util.Log -import android.view.LayoutInflater -import android.view.View -import android.view.ViewGroup -import android.widget.ImageButton -import android.widget.Toast -import androidx.activity.result.ActivityResultCallback -import androidx.activity.result.contract.ActivityResultContracts -import androidx.coordinatorlayout.widget.CoordinatorLayout -import androidx.core.content.res.ResourcesCompat -import androidx.fragment.app.viewModels -import androidx.preference.PreferenceManager -import it.reyboz.bustorino.R -import it.reyboz.bustorino.backend.Stop -import it.reyboz.bustorino.backend.gtfs.LivePositionUpdate -import it.reyboz.bustorino.backend.mato.MQTTMatoClient -import it.reyboz.bustorino.backend.utils -import it.reyboz.bustorino.data.gtfs.MatoPattern -import it.reyboz.bustorino.data.gtfs.TripAndPatternWithStops -import it.reyboz.bustorino.map.BusInfoWindow -import it.reyboz.bustorino.map.CustomInfoWindow -import it.reyboz.bustorino.map.CustomInfoWindow.TouchResponder -import it.reyboz.bustorino.map.LocationOverlay -import it.reyboz.bustorino.map.LocationOverlay.OverlayCallbacks -import it.reyboz.bustorino.map.MarkerUtils -import it.reyboz.bustorino.middleware.GeneralActivity -import it.reyboz.bustorino.util.Permissions -import it.reyboz.bustorino.viewmodels.LivePositionsViewModel -import it.reyboz.bustorino.viewmodels.StopsMapViewModel -import org.osmdroid.config.Configuration -import org.osmdroid.events.DelayedMapListener -import org.osmdroid.events.MapListener -import org.osmdroid.events.ScrollEvent -import org.osmdroid.events.ZoomEvent -import org.osmdroid.tileprovider.tilesource.TileSourceFactory -import org.osmdroid.util.GeoPoint -import org.osmdroid.views.MapView -import org.osmdroid.views.overlay.FolderOverlay -import org.osmdroid.views.overlay.Marker -import org.osmdroid.views.overlay.infowindow.InfoWindow -import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider - -open class MapFragmentKt : ScreenBaseFragment() { - protected var listenerMain: FragmentListenerMain? = null - private var shownStops: HashSet? = null - private lateinit var map: MapView - var ctx: Context? = null - private lateinit var mLocationOverlay: LocationOverlay - private lateinit var stopsFolderOverlay: FolderOverlay - private var savedMapState: Bundle? = null - protected lateinit var btCenterMap: ImageButton - protected lateinit var btFollowMe: ImageButton - protected var coordLayout: CoordinatorLayout? = null - private var hasMapStartFinished = false - private var followingLocation = false - - //the ViewModel from which we get the stop to display in the map - private val stopsViewModel: StopsMapViewModel by viewModels() - - //private GtfsPositionsViewModel gtfsPosViewModel; //= new ViewModelProvider(this).get(MapViewModel.class); - private val livePositionsViewModel: LivePositionsViewModel by viewModels() - private var useMQTTViewModel = true - private val busPositionMarkersByTrip = HashMap() - private var busPositionsOverlay: FolderOverlay? = null - private val tripMarkersAnimators = HashMap() - protected val responder = TouchResponder { stopID, stopName -> - if (listenerMain != null) { - Log.d(DEBUG_TAG, "Asked to show arrivals for stop ID: $stopID") - listenerMain!!.requestArrivalsForStopID(stopID) - } - } - protected val locationCallbacks: OverlayCallbacks = object : OverlayCallbacks { - override fun onDisableFollowMyLocation() { - updateGUIForLocationFollowing(false) - followingLocation = false - } - - override fun onEnableFollowMyLocation() { - updateGUIForLocationFollowing(true) - followingLocation = true - } - } - private val positionRequestLauncher = - registerForActivityResult, Map>( - ActivityResultContracts.RequestMultiplePermissions(), - ActivityResultCallback { result -> - if (result == null) { - Log.w(DEBUG_TAG, "Got asked permission but request is null, doing nothing?") - } else if (java.lang.Boolean.TRUE == result[Manifest.permission.ACCESS_COARSE_LOCATION] - && java.lang.Boolean.TRUE == result[Manifest.permission.ACCESS_FINE_LOCATION]) { - // We can use the position, restart location overlay - map.overlays.remove(mLocationOverlay) - startLocationOverlay(true, map) - if (context == null || requireContext().getSystemService(Context.LOCATION_SERVICE) == null) - return@ActivityResultCallback ///@registerForActivityResult - val locationManager = - requireContext().getSystemService(Context.LOCATION_SERVICE) as LocationManager - @SuppressLint("MissingPermission") val userLocation = - locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) - if (userLocation != null) { - map!!.controller.setZoom(POSITION_FOUND_ZOOM) - val startPoint = GeoPoint(userLocation) - setLocationFollowing(true) - map!!.controller.setCenter(startPoint) - } - } else Log.w(DEBUG_TAG, "No location permission") - }) - - //public static MapFragment getInstance(@NonNull Stop stop){ - // return getInstance(stop.getLatitude(), stop.getLongitude(), stop.getStopDisplayName(), stop.ID); - //} - override fun onCreateView( - inflater: LayoutInflater, - container: ViewGroup?, - savedInstanceState: Bundle? - ): View? { - //use the same layout as the activity - val root = inflater.inflate(R.layout.fragment_map, container, false) - val context = requireContext() - ctx = context.applicationContext - Configuration.getInstance().load(ctx, PreferenceManager.getDefaultSharedPreferences(context)) - map = root.findViewById(R.id.map) - map.setTileSource(TileSourceFactory.MAPNIK) - //map.setTilesScaledToDpi(true); - map.setFlingEnabled(true) - - // add ability to zoom with 2 fingers - map.setMultiTouchControls(true) - btCenterMap = root.findViewById(R.id.centerMapImageButton) - btFollowMe = root.findViewById(R.id.followUserImageButton) - coordLayout = root.findViewById(R.id.coord_layout) - - //setup FolderOverlay - stopsFolderOverlay = FolderOverlay() - //setup Bus Markers Overlay - busPositionsOverlay = FolderOverlay() - //reset shown bus updates - busPositionMarkersByTrip.clear() - tripMarkersAnimators.clear() - //set map not done - hasMapStartFinished = false - val keySourcePositions = getString(R.string.pref_positions_source) - useMQTTViewModel = PreferenceManager.getDefaultSharedPreferences(requireContext()) - .getString(keySourcePositions, SettingsFragment.LIVE_POSITIONS_PREF_MQTT_VALUE) - .contentEquals(SettingsFragment.LIVE_POSITIONS_PREF_MQTT_VALUE) - - - //Start map from bundle - if (savedInstanceState != null) startMap(arguments, savedInstanceState) else startMap( - arguments, savedMapState - ) - //set listeners - map.addMapListener(DelayedMapListener(object : MapListener { - override fun onScroll(paramScrollEvent: ScrollEvent): Boolean { - requestStopsToShow() - //Log.d(DEBUG_TAG, "Scrolling"); - //if (moveTriggeredByCode) moveTriggeredByCode =false; - //else setLocationFollowing(false); - return true - } - - override fun onZoom(event: ZoomEvent): Boolean { - requestStopsToShow() - return true - } - })) - btCenterMap.setOnClickListener(View.OnClickListener { v: View? -> - //Log.i(TAG, "centerMap clicked "); - if (Permissions.bothLocationPermissionsGranted(context)) { - val myPosition = mLocationOverlay!!.myLocation - map.getController().animateTo(myPosition) - } else Toast.makeText(context, R.string.enable_position_message_map, Toast.LENGTH_SHORT) - .show() - }) - btFollowMe.setOnClickListener(View.OnClickListener { v: View? -> - //Log.i(TAG, "btFollowMe clicked "); - if (Permissions.bothLocationPermissionsGranted(context)) setLocationFollowing(!followingLocation) else Toast.makeText( - context, R.string.enable_position_message_map, Toast.LENGTH_SHORT - ) - .show() - }) - return root - } - - override fun onAttach(context: Context) { - super.onAttach(context) - listenerMain = if (context is FragmentListenerMain) { - context - } else { - throw RuntimeException( - context.toString() - + " must implement FragmentListenerMain" - ) - } - } - - override fun onDetach() { - super.onDetach() - listenerMain = null - - Log.w(DEBUG_TAG, "Fragment detached") - } - - override fun onPause() { - super.onPause() - Log.w(DEBUG_TAG, "On pause called mapfrag") - saveMapState() - for (animator in tripMarkersAnimators.values) { - if (animator != null && animator.isRunning) { - animator.cancel() - } - } - tripMarkersAnimators.clear() - if (useMQTTViewModel) livePositionsViewModel.stopMatoUpdates() - } - - /** - * Save the map state inside the fragment - * (calls saveMapState(bundle)) - */ - private fun saveMapState() { - savedMapState = Bundle() - saveMapState(savedMapState!!) - } - - /** - * Save the state of the map to restore it to a later time - * @param bundle the bundle in which to save the data - */ - private fun saveMapState(bundle: Bundle) { - Log.d(DEBUG_TAG, "Saving state, location following: $followingLocation") - bundle.putBoolean(FOLLOWING_LOCAT_KEY, followingLocation) - if (map == null) { - //The map is null, it can happen? - Log.e(DEBUG_TAG, "Cannot save map center, map is null") - return - } - val loc = map!!.mapCenter - bundle.putDouble(MAP_CENTER_LAT_KEY, loc.latitude) - bundle.putDouble(MAP_CENTER_LON_KEY, loc.longitude) - bundle.putDouble(MAP_CURRENT_ZOOM_KEY, map!!.zoomLevelDouble) - } - - override fun onResume() { - super.onResume() - //TODO: cleanup duplicate code (maybe merging the positions classes?) - if (listenerMain != null) listenerMain!!.readyGUIfor(FragmentKind.MAP) - /// choose which to use - val keySourcePositions = getString(R.string.pref_positions_source) - useMQTTViewModel = PreferenceManager.getDefaultSharedPreferences(requireContext()) - .getString(keySourcePositions, SettingsFragment.LIVE_POSITIONS_PREF_MQTT_VALUE) - .contentEquals( - SettingsFragment.LIVE_POSITIONS_PREF_MQTT_VALUE - ) - //gtfsPosViewModel.requestUpdates(); - if (useMQTTViewModel) livePositionsViewModel.requestMatoPosUpdates(MQTTMatoClient.LINES_ALL) - else livePositionsViewModel.requestGTFSUpdates() - //mapViewModel.testCascade(); - livePositionsViewModel.isLastWorkResultGood.observe(this) { d: Boolean -> - Log.d( - DEBUG_TAG, "Last trip download result is $d" - ) - } - livePositionsViewModel.tripsGtfsIDsToQuery.observe(this) { dat: List -> - Log.i(DEBUG_TAG, "Have these trips IDs missing from the DB, to be queried: $dat") - livePositionsViewModel.downloadTripsFromMato(dat) - } - - //rerequest stop - stopsViewModel!!.requestStopsInBoundingBox(map!!.boundingBox) - } - - private fun startRequestsPositions() { - if (livePositionsViewModel != null) { - //should always be the case - livePositionsViewModel!!.updatesWithTripAndPatterns.observe(viewLifecycleOwner) { data: HashMap> -> - Log.d( - DEBUG_TAG, - "Have " + data.size + " trip updates, has Map start finished: " + hasMapStartFinished - ) - if (hasMapStartFinished) updateBusPositionsInMap(data) - if (!isDetached && !useMQTTViewModel) livePositionsViewModel!!.requestDelayedGTFSUpdates( - 3000 - ) - } - } else { - Log.e(DEBUG_TAG, "PositionsViewModel is null") - } - } - - override fun onSaveInstanceState(outState: Bundle) { - saveMapState(outState) - super.onSaveInstanceState(outState) - } - //own methods - /** - * Switch following the location on and off - * @param value true if we want to follow location - */ - fun setLocationFollowing(value: Boolean) { - followingLocation = value - if (mLocationOverlay == null || context == null || map == null) //nothing else to do - return - if (value) { - mLocationOverlay!!.enableFollowLocation() - } else { - mLocationOverlay!!.disableFollowLocation() - } - } - - /** - * Do all the stuff you need to do on the gui, when parameter is changed to value - * @param following value - */ - protected fun updateGUIForLocationFollowing(following: Boolean) { - if (following) btFollowMe!!.setImageResource(R.drawable.ic_follow_me_on) else btFollowMe!!.setImageResource( - R.drawable.ic_follow_me - ) - } - - /** - * Build the location overlay. Enable only when - * a) we know we have the permission - * b) the location map is set - */ - private fun startLocationOverlay(enableLocation: Boolean, map: MapView?) { - checkNotNull(activity) { "Cannot enable LocationOverlay now" } - // Location Overlay - // from OpenBikeSharing (THANK GOD) - Log.d(DEBUG_TAG, "Starting position overlay") - val imlp = GpsMyLocationProvider(requireActivity().baseContext) - imlp.locationUpdateMinDistance = 5f - imlp.locationUpdateMinTime = 2000 - val overlay = LocationOverlay(imlp, map, locationCallbacks) - if (enableLocation) overlay.enableMyLocation() - overlay.isOptionsMenuEnabled = true - - //map.getOverlays().add(this.mLocationOverlay); - mLocationOverlay = overlay - map!!.overlays.add(mLocationOverlay) - } - - fun startMap(incoming: Bundle?, savedInstanceState: Bundle?) { - //Check that we're attached - val activity = if (activity is GeneralActivity) activity as GeneralActivity? else null - if (context == null || activity == null) { - //we are not attached - Log.e(DEBUG_TAG, "Calling startMap when not attached") - return - } else { - Log.d(DEBUG_TAG, "Starting map from scratch") - } - //clear previous overlays - map!!.overlays.clear() - - - //parse incoming bundle - var marker: GeoPoint? = null - var name: String? = null - var ID: String? = null - var routesStopping: String? = "" - if (incoming != null) { - val lat = incoming.getDouble(BUNDLE_LATIT) - val lon = incoming.getDouble(BUNDLE_LONGIT) - marker = GeoPoint(lat, lon) - name = incoming.getString(BUNDLE_NAME) - ID = incoming.getString(BUNDLE_ID) - routesStopping = incoming.getString(BUNDLE_ROUTES_STOPPING, "") - } - - - //ask for location permission - if (!Permissions.bothLocationPermissionsGranted(activity)) { - if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) { - //TODO: show dialog for permission rationale - Toast.makeText(activity, R.string.enable_position_message_map, Toast.LENGTH_SHORT) - .show() - } - positionRequestLauncher.launch(Permissions.LOCATION_PERMISSIONS) - } - shownStops = HashSet() - // move the map on the marker position or on a default view point: Turin, Piazza Castello - // and set the start zoom - val mapController = map!!.controller - var startPoint: GeoPoint? = null - startLocationOverlay( - Permissions.bothLocationPermissionsGranted(activity), - map - ) - // set the center point - if (marker != null) { - //startPoint = marker; - mapController.setZoom(POSITION_FOUND_ZOOM) - setLocationFollowing(false) - // put the center a little bit off (animate later) - startPoint = GeoPoint(marker) - startPoint.latitude = marker.latitude + utils.angleRawDifferenceFromMeters(20.0) - startPoint.longitude = marker.longitude - utils.angleRawDifferenceFromMeters(20.0) - //don't need to do all the rest since we want to show a point - } else if (savedInstanceState != null && savedInstanceState.containsKey(MAP_CURRENT_ZOOM_KEY)) { - mapController.setZoom(savedInstanceState.getDouble(MAP_CURRENT_ZOOM_KEY)) - mapController.setCenter( - GeoPoint( - savedInstanceState.getDouble(MAP_CENTER_LAT_KEY), - savedInstanceState.getDouble(MAP_CENTER_LON_KEY) - ) - ) - Log.d( - DEBUG_TAG, - "Location following from savedInstanceState: " + savedInstanceState.getBoolean( - FOLLOWING_LOCAT_KEY - ) - ) - setLocationFollowing(savedInstanceState.getBoolean(FOLLOWING_LOCAT_KEY)) - } else { - Log.d(DEBUG_TAG, "No position found from intent or saved state") - var found = false - val locationManager = - requireContext().getSystemService(Context.LOCATION_SERVICE) as LocationManager - //check for permission - if (Permissions.bothLocationPermissionsGranted(activity)) { - @SuppressLint("MissingPermission") val userLocation = - locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) - if (userLocation != null) { - val distan = utils.measuredistanceBetween( - userLocation.latitude, userLocation.longitude, - DEFAULT_CENTER_LAT, DEFAULT_CENTER_LON - ) - if (distan < 100000.0) { - mapController.setZoom(POSITION_FOUND_ZOOM) - startPoint = GeoPoint(userLocation) - found = true - setLocationFollowing(true) - } - } - } - if (!found) { - startPoint = GeoPoint(DEFAULT_CENTER_LAT, DEFAULT_CENTER_LON) - mapController.setZoom(NO_POSITION_ZOOM) - setLocationFollowing(false) - } - } - - // set the minimum zoom level - map!!.minZoomLevel = 15.0 - //add contingency check (shouldn't happen..., but) - if (startPoint != null) { - mapController.setCenter(startPoint) - } - - - //add stops overlay - //map.getOverlays().add(mLocationOverlay); - map!!.overlays.add(stopsFolderOverlay) - Log.d(DEBUG_TAG, "Requesting stops load") - // This is not necessary, by setting the center we already move - // the map and we trigger a stop request - //requestStopsToShow(); - if (marker != null) { - // make a marker with the info window open for the searched marker - //TODO: make Stop Bundle-able - val stopMarker = makeMarker(marker, ID, name, routesStopping, true) - map!!.controller.animateTo(marker) - } - //add the overlays with the bus stops - if (busPositionsOverlay == null) { - //Log.i(DEBUG_TAG, "Null bus positions overlay,redo"); - busPositionsOverlay = FolderOverlay() - } - startRequestsPositions() - if (stopsViewModel != null) { - stopsViewModel!!.stopsInBoundingBox.observe(viewLifecycleOwner) { stops: List? -> - showStopsMarkers( - stops - ) - } - } else Log.d(DEBUG_TAG, "Cannot observe new stops in map, stopsViewModel is null") - map!!.overlays.add(busPositionsOverlay) - //set map as started - hasMapStartFinished = true - } - - /** - * Start a request to load the stops that are in the current view - * from the database - */ - private fun requestStopsToShow() { - // get the top, bottom, left and right screen's coordinate - val bb = map!!.boundingBox - Log.d( - DEBUG_TAG, - "Requesting stops in bounding box, stopViewModel is null " + (false) - ) - stopsViewModel.requestStopsInBoundingBox(bb) - - } - - private fun updateBusMarker( - marker: Marker?, - posUpdate: LivePositionUpdate, - justCreated: Boolean - ) { - val position: GeoPoint - val updateID = posUpdate.tripID - if (!justCreated) { - position = marker!!.position - if (posUpdate.latitude != position.latitude || posUpdate.longitude != position.longitude) { - val newpos = GeoPoint(posUpdate.latitude, posUpdate.longitude) - val valueAnimator = MarkerUtils.makeMarkerAnimator( - map, marker, newpos, MarkerUtils.LINEAR_ANIMATION, 1200 - ) - valueAnimator.setAutoCancel(true) - tripMarkersAnimators[updateID] = valueAnimator - valueAnimator.start() - } - //marker.setPosition(new GeoPoint(posUpdate.getLatitude(), posUpdate.getLongitude())); - } else { - position = GeoPoint(posUpdate.latitude, posUpdate.longitude) - marker!!.position = position - } - marker.rotation = posUpdate.bearing?.let { it*-1f } ?: 0.0f - } - - private fun updateBusPositionsInMap(tripsPatterns: HashMap>) { - Log.d(DEBUG_TAG, "Updating positions of the buses") - //if(busPositionsOverlay == null) busPositionsOverlay = new FolderOverlay(); - val noPatternsTrips = ArrayList() - for (tripID in tripsPatterns.keys) { - val (update, tripWithPatternStops) = tripsPatterns[tripID] ?: continue - - - //check if Marker is already created - if (busPositionMarkersByTrip.containsKey(tripID)) { - //need to change the position of the marker - val marker = busPositionMarkersByTrip[tripID]!! - updateBusMarker(marker, update, false) - if (marker.infoWindow != null && marker.infoWindow is BusInfoWindow) { - val window = marker.infoWindow as BusInfoWindow - if (tripWithPatternStops != null) { - //Log.d(DEBUG_TAG, "Update pattern for trip: "+tripID); - window.setPatternAndDraw(tripWithPatternStops.pattern) - } - } - } else { - //marker is not there, need to make it - val marker = Marker(map) - - /*final Drawable mDrawable = DrawableUtils.Companion.getScaledDrawableResources( - getResources(), - R.drawable.point_heading_icon, - R.dimen.map_icons_size, R.dimen.map_icons_size); - - */ - //String route = GtfsUtils.getLineNameFromGtfsID(update.getRouteID()); - val mdraw = - ResourcesCompat.getDrawable(resources, R.drawable.map_bus_position_icon, null)!! - //mdraw.setBounds(0,0,28,28); - marker.icon = mdraw - if (tripWithPatternStops == null) { - noPatternsTrips.add(tripID) - } - var markerPattern: MatoPattern? = null - if (tripWithPatternStops != null && tripWithPatternStops.pattern != null) markerPattern = - tripWithPatternStops.pattern - marker.infoWindow = - BusInfoWindow(map!!, update, markerPattern, false) { pattern: MatoPattern? -> } - marker.setInfoWindowAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER) - marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER) - updateBusMarker(marker, update, true) - // the overlay is null when it's not attached yet?5 - // cannot recreate it because it becomes null very soon - // if(busPositionsOverlay == null) busPositionsOverlay = new FolderOverlay(); - //save the marker - if (busPositionsOverlay != null) { - busPositionsOverlay!!.add(marker) - busPositionMarkersByTrip[tripID] = marker - } - } - } - if (noPatternsTrips.size > 0) { - Log.i(DEBUG_TAG, "These trips have no matching pattern: $noPatternsTrips") - } - } - - /** - * Add stops as Markers on the map - * @param stops the list of stops that must be included - */ - protected fun showStopsMarkers(stops: List?) { - if (context == null || stops == null) { - //we are not attached - return - } - var good = true - for (stop in stops) { - if (shownStops!!.contains(stop.ID)) { - continue - } - if (stop.longitude == null || stop.latitude == null) continue - shownStops!!.add(stop.ID) - if (!map!!.isShown) { - if (good) Log.d( - DEBUG_TAG, - "Need to show stop but map is not shown, probably detached already" - ) - good = false - continue - } else if (map!!.repository == null) { - Log.e(DEBUG_TAG, "Map view repository is null") - } - val marker = GeoPoint(stop.latitude!!, stop.longitude!!) - val stopMarker = makeMarker(marker, stop, false) - stopsFolderOverlay!!.add(stopMarker) - if (!map!!.overlays.contains(stopsFolderOverlay)) { - Log.w(DEBUG_TAG, "Map doesn't have folder overlay") - } - good = true - } - //Log.d(DEBUG_TAG,"We have " +stopsFolderOverlay.getItems().size()+" stops in the folderOverlay"); - //force redraw of markers - map!!.invalidate() - } - - fun makeMarker(geoPoint: GeoPoint?, stop: Stop, isStartMarker: Boolean): Marker { - return makeMarker( - geoPoint, stop.ID, - stop.stopDefaultName, - stop.routesThatStopHereToString(), isStartMarker - ) - } - - fun makeMarker( - geoPoint: GeoPoint?, stopID: String?, stopName: String?, - routesStopping: String?, isStartMarker: Boolean - ): Marker { - - // add a marker - val marker = Marker(map) - - // set custom info window as info window - val popup = CustomInfoWindow( - map, stopID, stopName, routesStopping, - responder, R.layout.linedetail_stop_infowindow, R.color.red_darker - ) - marker.infoWindow = popup - - // make the marker clickable - marker.setOnMarkerClickListener { thisMarker: Marker, mapView: MapView? -> - if (thisMarker.isInfoWindowOpen) { - // on second click - Log.w(DEBUG_TAG, "Pressed on the click marker") - } else { - // on first click - - // hide all opened info window - InfoWindow.closeAllInfoWindowsOn(map) - // show this particular info window - thisMarker.showInfoWindow() - // move the map to its position - map!!.controller.animateTo(thisMarker.position) - } - true - } - - // set its position - marker.position = geoPoint - marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER) - // add to it an icon - //marker.setIcon(getResources().getDrawable(R.drawable.bus_marker)); - marker.icon = ResourcesCompat.getDrawable(resources, R.drawable.bus_stop, ctx!!.theme) - // add to it a title - marker.title = stopName - // set the description as the ID - marker.snippet = stopID - - // show popup info window of the searched marker - if (isStartMarker) { - marker.showInfoWindow() - //map.getController().animateTo(marker.getPosition()); - } - return marker - } - - override fun getBaseViewForSnackBar(): View? { - return coordLayout - } - - companion object { - //private static final String TAG = "Busto-MapActivity"; - private const val MAP_CURRENT_ZOOM_KEY = "map-current-zoom" - private const val MAP_CENTER_LAT_KEY = "map-center-lat" - private const val MAP_CENTER_LON_KEY = "map-center-lon" - private const val FOLLOWING_LOCAT_KEY = "following" - const val BUNDLE_LATIT = "lat" - const val BUNDLE_LONGIT = "lon" - const val BUNDLE_NAME = "name" - const val BUNDLE_ID = "ID" - const val BUNDLE_ROUTES_STOPPING = "routesStopping" - const val FRAGMENT_TAG = "BusTOMapFragment" - private const val DEFAULT_CENTER_LAT = 45.0708 - private const val DEFAULT_CENTER_LON = 7.6858 - private const val POSITION_FOUND_ZOOM = 18.3 - const val NO_POSITION_ZOOM = 17.1 - private const val DEBUG_TAG = FRAGMENT_TAG - - @JvmStatic - fun getInstance(): MapFragmentKt { - return MapFragmentKt() - } - @JvmStatic - fun getInstance(stop: Stop): MapFragmentKt { - val fragment = MapFragmentKt() - val args = Bundle() - args.putDouble(MapFragment.BUNDLE_LATIT, stop.latitude!!) - args.putDouble(MapFragment.BUNDLE_LONGIT, stop.longitude!!) - args.putString(MapFragment.BUNDLE_NAME, stop.stopDisplayName) - args.putString(MapFragment.BUNDLE_ID, stop.ID) - args.putString(MapFragment.BUNDLE_ROUTES_STOPPING, stop.routesThatStopHereToString()) - fragment.arguments = args - - return fragment - } - } -} diff --git a/app/src/main/java/it/reyboz/bustorino/fragments/MapLibreFragment.kt b/app/src/main/java/it/reyboz/bustorino/fragments/MapLibreFragment.kt index 3d84f56..dbc0444 100644 --- a/app/src/main/java/it/reyboz/bustorino/fragments/MapLibreFragment.kt +++ b/app/src/main/java/it/reyboz/bustorino/fragments/MapLibreFragment.kt @@ -1,1148 +1,1141 @@ package it.reyboz.bustorino.fragments import android.Manifest import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.ValueAnimator import android.annotation.SuppressLint import android.content.Context -import android.content.Intent import android.graphics.Color import android.location.Location import android.location.LocationListener import android.location.LocationManager -import android.net.Uri import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.animation.LinearInterpolator import android.widget.ImageButton import android.widget.RelativeLayout import android.widget.TextView import android.widget.Toast import androidx.activity.result.ActivityResultCallback import androidx.activity.result.contract.ActivityResultContracts import androidx.cardview.widget.CardView import androidx.core.content.ContextCompat import androidx.core.content.res.ResourcesCompat import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.preference.PreferenceManager import com.google.android.material.bottomsheet.BottomSheetBehavior -import com.google.gson.Gson import com.google.gson.JsonObject import it.reyboz.bustorino.R import it.reyboz.bustorino.backend.Stop import it.reyboz.bustorino.backend.gtfs.LivePositionUpdate import it.reyboz.bustorino.backend.mato.MQTTMatoClient import it.reyboz.bustorino.data.PreferencesHolder import it.reyboz.bustorino.data.gtfs.TripAndPatternWithStops import it.reyboz.bustorino.fragments.SettingsFragment.LIVE_POSITIONS_PREF_MQTT_VALUE import it.reyboz.bustorino.map.MapLibreUtils -import it.reyboz.bustorino.map.Styles +import it.reyboz.bustorino.map.MapLibreStyles import it.reyboz.bustorino.util.Permissions import it.reyboz.bustorino.util.ViewUtils import it.reyboz.bustorino.viewmodels.LivePositionsViewModel import it.reyboz.bustorino.viewmodels.StopsMapViewModel -import org.maplibre.android.MapLibre import org.maplibre.android.camera.CameraPosition import org.maplibre.android.camera.CameraUpdateFactory import org.maplibre.android.geometry.LatLng import org.maplibre.android.geometry.LatLngBounds import org.maplibre.android.location.LocationComponent import org.maplibre.android.location.LocationComponentOptions import org.maplibre.android.location.modes.CameraMode import org.maplibre.android.maps.MapLibreMap -import org.maplibre.android.maps.MapView -import org.maplibre.android.maps.OnMapReadyCallback import org.maplibre.android.maps.Style import org.maplibre.android.plugins.annotation.Symbol -import org.maplibre.android.plugins.annotation.SymbolManager -import org.maplibre.android.plugins.annotation.SymbolOptions import org.maplibre.android.style.expressions.Expression -import org.maplibre.android.style.layers.Property import org.maplibre.android.style.layers.Property.* import org.maplibre.android.style.layers.PropertyFactory import org.maplibre.android.style.layers.SymbolLayer import org.maplibre.android.style.sources.GeoJsonSource import org.maplibre.geojson.Feature import org.maplibre.geojson.FeatureCollection import org.maplibre.geojson.Point // TODO: Rename parameter arguments, choose names that match // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val STOP_TO_SHOW = "stoptoshow" /** * A simple [Fragment] subclass. * Use the [MapLibreFragment.newInstance] factory method to * create an instance of this fragment. */ class MapLibreFragment : GeneralMapLibreFragment() { protected var fragmentListener: CommonFragmentListener? = null private lateinit var locationComponent: LocationComponent private var lastLocation: Location? = null private val stopsViewModel: StopsMapViewModel by viewModels() private var stopsShowing = ArrayList(0) private var isBottomSheetShowing = false //private lateinit var symbolManager: SymbolManager // Sources for stops and buses are in GeneralMapLibreFragment private var stopsLayerStarted = false private var lastStopsSizeShown = 0 private var lastBBox = LatLngBounds.from(2.0, 2.0, 1.0,1.0) private var mapInitCompleted =false private var stopsRedrawnTimes = 0 //bottom Sheet behavior private lateinit var bottomSheetBehavior: BottomSheetBehavior private var bottomLayout: RelativeLayout? = null private lateinit var stopTitleTextView: TextView private lateinit var stopNumberTextView: TextView private lateinit var linesPassingTextView: TextView private lateinit var arrivalsCard: CardView private lateinit var directionsCard: CardView //private var stopActiveSymbol: Symbol? = null // Location stuff private lateinit var locationManager: LocationManager private lateinit var showUserPositionButton: ImageButton private lateinit var centerUserButton: ImageButton private lateinit var followUserButton: ImageButton private var followingUserLocation = false private var pendingLocationActivation = false private var ignoreCameraMovementForFollowing = true private var enablingPositionFromClick = false private val positionRequestLauncher = registerForActivityResult, Map>( ActivityResultContracts.RequestMultiplePermissions(), ActivityResultCallback { result -> if (result == null) { Log.w(DEBUG_TAG, "Got asked permission but request is null, doing nothing?") } else if (java.lang.Boolean.TRUE == result[Manifest.permission.ACCESS_COARSE_LOCATION] && java.lang.Boolean.TRUE == result[Manifest.permission.ACCESS_FINE_LOCATION]) { // We can use the position, restart location overlay Log.d(DEBUG_TAG, "HAVE THE PERMISSIONS") if (context == null || requireContext().getSystemService(Context.LOCATION_SERVICE) == null) return@ActivityResultCallback ///@registerForActivityResult val locationManager = requireContext().getSystemService(Context.LOCATION_SERVICE) as LocationManager @SuppressLint("MissingPermission") val userLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) if (userLocation != null) { if(LatLng(userLocation.latitude, userLocation.longitude).distanceTo(DEFAULT_LATLNG) >= MAX_DIST_KM*1000){ setMapLocationEnabled(true, true, false) } } else requestInitialUserLocation() } else{ Toast.makeText(requireContext(),"User location disabled", Toast.LENGTH_SHORT).show() Log.w(DEBUG_TAG, "No location permission") } }) private val showUserPositionRequestLauncher = registerForActivityResult, Map>( ActivityResultContracts.RequestMultiplePermissions(), ActivityResultCallback { result -> if (result == null) { Log.w(DEBUG_TAG, "Got asked permission but request is null, doing nothing?") } else if (java.lang.Boolean.TRUE == result[Manifest.permission.ACCESS_COARSE_LOCATION] && java.lang.Boolean.TRUE == result[Manifest.permission.ACCESS_FINE_LOCATION]) { // We can use the position, restart location overlay if (context == null || requireContext().getSystemService(Context.LOCATION_SERVICE) == null) return@ActivityResultCallback ///@registerForActivityResult setMapLocationEnabled(true, true, enablingPositionFromClick) } else Log.w(DEBUG_TAG, "No location permission") }) //BUS POSITIONS private var useMQTTViewModel = true private val livePositionsViewModel : LivePositionsViewModel by viewModels() private val positionsByVehDict = HashMap(5) private val animatorsByVeh = HashMap() private var lastUpdateTime : Long = -1 //private var busLabelSymbolsByVeh = HashMap() private val symbolsToUpdate = ArrayList() private var initialStopToShow : Stop? = null private var initialStopShown = false //shown stuff //private var savedStateOnStop : Bundle? = null private val showBusLayer = true override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { initialStopToShow = Stop.fromBundle(arguments) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment val rootView = inflater.inflate(R.layout.fragment_map_libre, container, false) //reset the counter lastStopsSizeShown = 0 stopsRedrawnTimes = 0 stopsLayerStarted = false symbolsToUpdate.clear() // Init layout view // Init the MapView mapView = rootView.findViewById(R.id.libreMapView) val restoreBundle = stopsViewModel.savedState if(restoreBundle!=null){ mapView.onCreate(restoreBundle) } else mapView.onCreate(savedInstanceState) mapView.getMapAsync(this) //{ //map -> //map.setStyle("https://demotiles.maplibre.org/style.json") } //init bottom sheet val bottomSheet = rootView.findViewById(R.id.bottom_sheet) bottomLayout = bottomSheet stopTitleTextView = bottomSheet.findViewById(R.id.stopTitleTextView) stopNumberTextView = bottomSheet.findViewById(R.id.stopNumberTextView) linesPassingTextView = bottomSheet.findViewById(R.id.linesPassingTextView) arrivalsCard = bottomSheet.findViewById(R.id.arrivalsCardButton) directionsCard = bottomSheet.findViewById(R.id.directionsCardButton) showUserPositionButton = rootView.findViewById(R.id.locationEnableIcon) showUserPositionButton.setOnClickListener(this::switchUserLocationStatus) followUserButton = rootView.findViewById(R.id.followUserImageButton) centerUserButton = rootView.findViewById(R.id.centerMapImageButton) bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet) bottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN arrivalsCard.setOnClickListener { if(context!=null){ Toast.makeText(context,"ARRIVALS", Toast.LENGTH_SHORT).show() } } centerUserButton.setOnClickListener { if(context!=null && locationComponent.isLocationComponentEnabled) { val location = locationComponent.lastKnownLocation location?.let { mapView.getMapAsync { map -> map.animateCamera(CameraUpdateFactory.newCameraPosition( CameraPosition.Builder().target(LatLng(location.latitude, location.longitude)).build()), 500) } } } } followUserButton.setOnClickListener { // onClick user following button if(context!=null && locationComponent.isLocationComponentEnabled){ if(followingUserLocation) locationComponent.cameraMode = CameraMode.NONE else locationComponent.cameraMode = CameraMode.TRACKING // CameraMode.TRACKING makes the camera move and jump to the location setFollowingUser(!followingUserLocation) } } locationManager = requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager if (Permissions.bothLocationPermissionsGranted(requireContext())) { requestInitialUserLocation() } else{ if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) { //TODO: show dialog for permission rationale Toast.makeText(activity, R.string.enable_position_message_map, Toast.LENGTH_SHORT) .show() } positionRequestLauncher.launch(Permissions.LOCATION_PERMISSIONS) } // Setup close button rootView.findViewById(R.id.btnClose).setOnClickListener { hideStopBottomSheet() } Log.d(DEBUG_TAG, "Fragment View Created!") //TODO: Reshow last open stop when switching back to the map fragment return rootView } /** * This method sets up the map and the layers */ override fun onMapReady(mapReady: MapLibreMap) { this.map = mapReady val context = requireContext() - val mjson = Styles.getJsonStyleFromAsset(context, PreferencesHolder.getMapLibreStyleFile(context)) + val mjson = MapLibreStyles.getJsonStyleFromAsset(context, PreferencesHolder.getMapLibreStyleFile(context)) //ViewUtils.loadJsonFromAsset(requireContext(),"map_style_good.json") activity?.run { val builder = Style.Builder().fromJson(mjson!!) mapReady.setStyle(builder) { style -> mapStyle = style //setupLayers(style) // Start observing data observeStops() initMapLocation(style, mapReady, requireContext()) //init stop layer with this val stopsInCache = stopsViewModel.getAllStopsLoaded() if(stopsInCache.isEmpty()) initStopsLayer(style, FeatureCollection.fromFeatures(ArrayList())) else displayStops(stopsInCache) if(showBusLayer) setupBusLayer(style) /*symbolManager = SymbolManager(mapView,mapReady,style, null, "symbol-transit-airfield") symbolManager.iconAllowOverlap = true symbolManager.textAllowOverlap = false symbolManager.textIgnorePlacement =true */ /*symbolManager.addClickListener{ _ -> if (stopActiveSymbol!=null){ hideStopBottomSheet() return@addClickListener true } else return@addClickListener false } */ } mapReady.addOnCameraIdleListener { map?.let { val newBbox = it.projection.visibleRegion.latLngBounds if ((newBbox.center==lastBBox.center) && (newBbox.latitudeSpan==lastBBox.latitudeSpan) && (newBbox.longitudeSpan==lastBBox.latitudeSpan)){ //do nothing } else { stopsViewModel.loadStopsInLatLngBounds(newBbox) lastBBox = newBbox } } } mapReady.addOnCameraMoveStartedListener { map?.let { setFollowingUser(it.locationComponent.cameraMode == CameraMode.TRACKING) } //setFollowingUser() } mapReady.addOnMapClickListener { point -> onMapClickReact(point) } mapInitCompleted = true // we start requesting the bus positions now startRequestingPositions() } savedMapStateOnPause?.let{ restoreMapStateFromBundle(it) pendingLocationActivation = false Log.d(DEBUG_TAG, "Restored map state from the saved bundle") } //reset saved State at the end if( savedMapStateOnPause == null) { //set initial position val zoom = 15.0 //center position val latlngTarget = initialStopToShow?.let { LatLng(it.latitude!!, it.longitude!!) } ?: LatLng(DEFAULT_CENTER_LAT, DEFAULT_CENTER_LON) mapReady.cameraPosition = CameraPosition.Builder().target(latlngTarget).zoom(zoom).build() } //reset saved state savedMapStateOnPause = null } private fun onMapClickReact(point: LatLng): Boolean{ map?.let { mapReady -> val screenPoint = mapReady.projection.toScreenLocation(point) val features = mapReady.queryRenderedFeatures(screenPoint, STOPS_LAYER_ID) val busNearby = mapReady.queryRenderedFeatures(screenPoint, BUSES_LAYER_ID) if (features.isNotEmpty()) { val feature = features[0] val id = feature.getStringProperty("id") val name = feature.getStringProperty("name") //Toast.makeText(requireContext(), "Clicked on $name ($id)", Toast.LENGTH_SHORT).show() val stop = stopsViewModel.getStopByID(id) stop?.let { newstop -> val sameStopClicked = shownStopInBottomSheet?.let { newstop.ID==it.ID } ?: false if (isBottomSheetShowing) { hideStopBottomSheet() } if(!sameStopClicked){ openStopInBottomSheet(newstop) //isBottomSheetShowing = true //move camera if (newstop.latitude != null && newstop.longitude != null) //mapReady.cameraPosition = CameraPosition.Builder().target(LatLng(it.latitude!!, it.longitude!!)).build() mapReady.animateCamera( CameraUpdateFactory.newLatLng(LatLng(newstop.latitude!!, newstop.longitude!!)), 750 ) } } return true } else if (busNearby.isNotEmpty()) { val feature = busNearby[0] val vehid = feature.getStringProperty("veh") val route = feature.getStringProperty("line") Toast.makeText(context, "Veh $vehid on route $route", Toast.LENGTH_SHORT).show() return true } } return false } private fun initStopsLayer(style: Style, features:FeatureCollection){ stopsSource = GeoJsonSource(STOPS_SOURCE_ID,features) style.addSource(stopsSource) // add icon style.addImage(STOP_IMAGE_ID, ResourcesCompat.getDrawable(resources,R.drawable.bus_stop_new, activity?.theme)!!) style.addImage(STOP_ACTIVE_IMG, ResourcesCompat.getDrawable(resources, R.drawable.bus_stop_new_highlight, activity?.theme)!!) style.addImage("ball",ResourcesCompat.getDrawable(resources, R.drawable.ball, activity?.theme)!!) // Stops layer val stopsLayer = SymbolLayer(STOPS_LAYER_ID, STOPS_SOURCE_ID) stopsLayer.withProperties( PropertyFactory.iconImage(STOP_IMAGE_ID), PropertyFactory.iconAnchor(ICON_ANCHOR_CENTER), PropertyFactory.iconAllowOverlap(true), PropertyFactory.iconIgnorePlacement(true) ) style.addLayerBelow(stopsLayer, "symbol-transit-airfield") //"label_country_1") this with OSM Bright selectedStopSource = GeoJsonSource(SEL_STOP_SOURCE, FeatureCollection.fromFeatures(ArrayList())) style.addSource(selectedStopSource) val selStopLayer = SymbolLayer(SEL_STOP_LAYER, SEL_STOP_SOURCE) selStopLayer.withProperties( PropertyFactory.iconImage(STOP_ACTIVE_IMG), PropertyFactory.iconAllowOverlap(true), PropertyFactory.iconIgnorePlacement(true), PropertyFactory.iconAnchor(ICON_ANCHOR_CENTER), ) style.addLayerAbove(selStopLayer, STOPS_LAYER_ID) stopsLayerStarted = true } /** * Setup the Map Layers */ private fun setupBusLayer(style: Style) { // Buses source busesSource = GeoJsonSource(BUSES_SOURCE_ID) style.addSource(busesSource) style.addImage("bus_symbol",ResourcesCompat.getDrawable(resources, R.drawable.map_bus_position_icon, activity?.theme)!!) // Buses layer val busesLayer = SymbolLayer(BUSES_LAYER_ID, BUSES_SOURCE_ID).apply { withProperties( PropertyFactory.iconImage("bus_symbol"), PropertyFactory.iconSize(1.2f), PropertyFactory.iconAllowOverlap(true), PropertyFactory.iconIgnorePlacement(true), PropertyFactory.iconRotate(Expression.get("bearing")), PropertyFactory.iconRotationAlignment(ICON_ROTATION_ALIGNMENT_MAP), PropertyFactory.textAnchor(TEXT_ANCHOR_CENTER), PropertyFactory.textAllowOverlap(true), PropertyFactory.textField(Expression.get("line")), PropertyFactory.textColor(Color.WHITE), PropertyFactory.textRotationAlignment(TEXT_ROTATION_ALIGNMENT_VIEWPORT), PropertyFactory.textSize(12f), PropertyFactory.textFont(arrayOf("noto_sans_regular")) ) } style.addLayerAbove(busesLayer, STOPS_LAYER_ID) //Line names layer /*vehiclesLabelsSource = GeoJsonSource(LABELS_SOURCE) style.addSource(vehiclesLabelsSource) val textLayer = SymbolLayer(LABELS_LAYER_ID, LABELS_SOURCE).apply { withProperties( PropertyFactory.textField("label"), PropertyFactory.textSize(30f), //PropertyFactory.textHaloColor(Color.BLACK), //PropertyFactory.textHaloWidth(1f), PropertyFactory.textAnchor(TEXT_ANCHOR_CENTER), PropertyFactory.textAllowOverlap(true), PropertyFactory.textField(Expression.get("line")), PropertyFactory.textColor(Color.WHITE), PropertyFactory.textRotationAlignment(TEXT_ROTATION_ALIGNMENT_VIEWPORT), PropertyFactory.textSize(12f) ) } style.addLayerAbove(textLayer, BUSES_LAYER_ID) */ } /** * Update the bottom sheet with the stop information */ override fun openStopInBottomSheet(stop: Stop){ bottomLayout?.let { //lay.findViewById(R.id.stopTitleTextView).text ="${stop.ID} - ${stop.stopDefaultName}" val stopName = stop.stopUserName ?: stop.stopDefaultName stopTitleTextView.text = stopName//stop.stopDefaultName stopNumberTextView.text = stop.ID val string_show = if (stop.numRoutesStopping==0) "" else if (stop.numRoutesStopping <= 1) requireContext().getString(R.string.line_fill, stop.routesThatStopHereToString()) else requireContext().getString(R.string.lines_fill, stop.routesThatStopHereToString()) linesPassingTextView.text = string_show //SET ON CLICK LISTENER arrivalsCard.setOnClickListener{ fragmentListener?.requestArrivalsForStopID(stop.ID) } directionsCard.setOnClickListener { ViewUtils.openStopInOutsideApp(stop, context) } } //add stop marker if (stop.latitude!=null && stop.longitude!=null) { /*stopActiveSymbol = symbolManager.create( SymbolOptions() .withLatLng(LatLng(stop.latitude!!, stop.longitude!!)) .withIconImage(STOP_ACTIVE_IMG) .withIconAnchor(ICON_ANCHOR_CENTER) //.withTextFont(arrayOf("noto_sans_regular"))) */ Log.d(DEBUG_TAG, "Showing stop: ${stop.ID}") val list = ArrayList() list.add(stopToGeoJsonFeature(stop)) selectedStopSource.setGeoJson( FeatureCollection.fromFeatures(list) ) } shownStopInBottomSheet = stop bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED isBottomSheetShowing = true } override fun onAttach(context: Context) { super.onAttach(context) fragmentListener = if (context is CommonFragmentListener) { context } else { throw RuntimeException( context.toString() + " must implement FragmentListenerMain" ) } } override fun onDetach() { super.onDetach() fragmentListener = null } override fun onStart() { super.onStart() mapView.onStart() } override fun onResume() { super.onResume() mapView.onResume() val keySourcePositions = getString(R.string.pref_positions_source) if(showBusLayer) { useMQTTViewModel = PreferenceManager.getDefaultSharedPreferences(requireContext()) .getString(keySourcePositions, LIVE_POSITIONS_PREF_MQTT_VALUE) .contentEquals(LIVE_POSITIONS_PREF_MQTT_VALUE) if (useMQTTViewModel) livePositionsViewModel.requestMatoPosUpdates(MQTTMatoClient.LINES_ALL) else livePositionsViewModel.requestGTFSUpdates() //mapViewModel.testCascade(); livePositionsViewModel.isLastWorkResultGood.observe(this) { d: Boolean -> Log.d( DEBUG_TAG, "Last trip download result is $d" ) } livePositionsViewModel.tripsGtfsIDsToQuery.observe(this) { dat: List -> Log.i(DEBUG_TAG, "Have these trips IDs missing from the DB, to be queried: $dat") livePositionsViewModel.downloadTripsFromMato(dat) } } fragmentListener?.readyGUIfor(FragmentKind.MAP) } override fun onPause() { super.onPause() mapView.onPause() Log.d(DEBUG_TAG, "Fragment paused") savedMapStateOnPause = saveMapStateInBundle() if (useMQTTViewModel) livePositionsViewModel.stopMatoUpdates() } override fun onStop() { super.onStop() mapView.onStop() Log.d(DEBUG_TAG, "Fragment stopped!") stopsViewModel.savedState = Bundle().let { mapView.onSaveInstanceState(it) it } } override fun onDestroy() { super.onDestroy() mapView.onDestroy() Log.d(DEBUG_TAG, "Destroyed map Fragment!!") } override fun onMapDestroy() { mapStyle.removeLayer(STOPS_LAYER_ID) mapStyle.removeSource(STOPS_SOURCE_ID) mapStyle.removeLayer(BUSES_LAYER_ID) mapStyle.removeSource(BUSES_SOURCE_ID) map?.locationComponent?.isLocationComponentEnabled = false } override fun getBaseViewForSnackBar(): View? { return mapView } private fun observeStops() { // Observe stops stopsViewModel.stopsToShow.observe(viewLifecycleOwner) { stops -> stopsShowing = ArrayList(stops) displayStops(stopsShowing) initialStopToShow?.let{ s-> //show the stop in the bottom sheet if(!initialStopShown) { openStopInBottomSheet(s) initialStopShown = true } } } } /** * Add the stops to the layers */ private fun displayStops(stops: List?) { if (stops.isNullOrEmpty()) return if (stops.size==lastStopsSizeShown){ Log.d(DEBUG_TAG, "Not updating, have same number of stops. After 3 times") return } /*if(stops.size> lastStopsSizeShown){ stopsRedrawnTimes = 0 } else{ stopsRedrawnTimes++ } */ val features = ArrayList()//stops.mapNotNull { stop -> //stop.latitude?.let { lat -> // stop.longitude?.let { lon -> for (s in stops){ if (s.latitude!=null && s.longitude!=null) features.add(stopToGeoJsonFeature(s)) } Log.d(DEBUG_TAG,"Have put ${features.size} stops to display") // if the layer is already started, substitute the stops inside, otherwise start it if (stopsLayerStarted) { stopsSource.setGeoJson(FeatureCollection.fromFeatures(features)) lastStopsSizeShown = features.size } else map?.let { Log.d(DEBUG_TAG, "Map stop layer is not started yet, init layer") initStopsLayer(mapStyle, FeatureCollection.fromFeatures(features)) Log.d(DEBUG_TAG,"Started stops layer on map") lastStopsSizeShown = features.size stopsLayerStarted = true } } // Hide the bottom sheet and remove extra symbol private fun hideStopBottomSheet(){ /*if (stopActiveSymbol!=null){ symbolManager.delete(stopActiveSymbol) stopActiveSymbol = null } */ //empty the source selectedStopSource.setGeoJson(FeatureCollection.fromFeatures(ArrayList())) bottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN //remove initial stop if(initialStopToShow!=null){ initialStopToShow = null } //set showing isBottomSheetShowing = false shownStopInBottomSheet = null } // --------------- BUS LOCATIONS STUFF -------------------------- /** * Start requesting position updates */ private fun startRequestingPositions() { livePositionsViewModel.updatesWithTripAndPatterns.observe(viewLifecycleOwner) { data: HashMap> -> Log.d( DEBUG_TAG, "Have " + data.size + " trip updates, has Map start finished: " + mapInitCompleted ) if (mapInitCompleted) updateBusPositionsInMap(data) if (!isDetached && !useMQTTViewModel) livePositionsViewModel.requestDelayedGTFSUpdates( 3000 ) } } private fun isInsideVisibleRegion(latitude: Double, longitude: Double, nullValue: Boolean): Boolean{ var isInside = nullValue val visibleRegion = map?.projection?.visibleRegion visibleRegion?.let { val bounds = it.latLngBounds isInside = bounds.contains(LatLng(latitude, longitude)) } return isInside } /*private fun createLabelForVehicle(positionUpdate: LivePositionUpdate){ val symOpt = SymbolOptions() .withLatLng(LatLng(positionUpdate.latitude, positionUpdate.longitude)) .withTextColor("#ffffff") .withTextField(positionUpdate.routeID.substringBeforeLast('U')) .withTextSize(13f) .withTextAnchor(TEXT_ANCHOR_CENTER) .withTextFont(arrayOf( "noto_sans_regular"))//"noto_sans_regular", "sans-serif")) //"noto_sans_regular")) val newSymbol = symbolManager.create(symOpt ) Log.d(DEBUG_TAG, "Symbol for veh ${positionUpdate.vehicle}: $newSymbol") busLabelSymbolsByVeh[positionUpdate.vehicle] = newSymbol } private fun removeVehicleLabel(vehicle: String){ busLabelSymbolsByVeh[vehicle]?.let { symbolManager.delete(it) busLabelSymbolsByVeh.remove(vehicle) } } */ /** * Update function for the bus positions * Takes the processed updates and saves them accordingly */ private fun updateBusPositionsInMap(incomingData: HashMap>){ val vehsNew = HashSet(incomingData.values.map { up -> up.first.vehicle }) val vehsOld = HashSet(positionsByVehDict.keys) val symbolsToUpdate = ArrayList() for (upsWithTrp in incomingData.values){ val pos = upsWithTrp.first val vehID = pos.vehicle var animate = false if (vehsOld.contains(vehID)){ //update position only if the starting or the stopping position of the animation are in the view val oldPos = positionsByVehDict[vehID] var avoidShowingUpdateBecauseIsImpossible = false oldPos?.let{ if(oldPos.routeID!=pos.routeID) { val dist = LatLng(it.latitude, it.longitude).distanceTo(LatLng(pos.latitude, pos.longitude)) val speed = dist*3.6 / (pos.timestamp - it.timestamp) //this should be in km/h Log.w(DEBUG_TAG, "Vehicle $vehID changed route from ${oldPos.routeID} to ${pos.routeID}, distance: $dist, speed: $speed") if (speed > 120 || speed < 0){ avoidShowingUpdateBecauseIsImpossible = true } } } if (avoidShowingUpdateBecauseIsImpossible){ // DO NOT SHOW THIS SHIT Log.w(DEBUG_TAG, "Update for vehicle $vehID skipped") continue } val samePosition = oldPos?.let { (oldPos.latitude==pos.latitude)&&(oldPos.longitude == pos.longitude) }?:false if(!samePosition) { val isPositionInBounds = isInsideVisibleRegion( pos.latitude, pos.longitude, true ) || (oldPos?.let { isInsideVisibleRegion(it.latitude,it.longitude,true) } ?: false) if (isPositionInBounds) { //animate = true //this moves both the icon and the label moveVehicleToNewPosition(pos) } else { positionsByVehDict[vehID] = pos /*busLabelSymbolsByVeh[vehID]?.let { it.latLng = LatLng(pos.latitude, pos.longitude) symbolsToUpdate.add(it) } */ } } } else if(pos.latitude>0 && pos.longitude>0) { //we should not have to check for this // update it simply positionsByVehDict[vehID] = pos //createLabelForVehicle(pos) }else{ Log.w(DEBUG_TAG, "Update ignored for veh $vehID on line ${pos.routeID}, lat: ${pos.latitude}, lon ${pos.longitude}") } } // symbolManager.update(symbolsToUpdate) //remove old positions vehsOld.removeAll(vehsNew) //now vehsOld contains the vehicles id for those that have NOT been updated val currentTimeStamp = System.currentTimeMillis() /1000 for(vehID in vehsOld){ //remove after 2 minutes of inactivity if (positionsByVehDict[vehID]!!.timestamp - currentTimeStamp > 2*60){ positionsByVehDict.remove(vehID) //removeVehicleLabel(vehID) } } //update UI updatePositionsIcons() } /** * This is the tricky part, animating the transitions * Basically, we need to set the new positions with the data and redraw them all */ private fun moveVehicleToNewPosition(positionUpdate: LivePositionUpdate){ if (positionUpdate.vehicle !in positionsByVehDict.keys) return val vehID = positionUpdate.vehicle val currentUpdate = positionsByVehDict[positionUpdate.vehicle] currentUpdate?.let { it -> //cancel current animation on vehicle animatorsByVeh[vehID]?.cancel() val currentPos = LatLng(it.latitude, it.longitude) val newPos = LatLng(positionUpdate.latitude, positionUpdate.longitude) val valueAnimator = ValueAnimator.ofObject(MapLibreUtils.LatLngEvaluator(), currentPos, newPos) valueAnimator.addUpdateListener(object : ValueAnimator.AnimatorUpdateListener { private var latLng: LatLng? = null override fun onAnimationUpdate(animation: ValueAnimator) { latLng = animation.animatedValue as LatLng //update position on animation val update = positionsByVehDict[positionUpdate.vehicle]!! latLng?.let { ll-> update.latitude = ll.latitude update.longitude = ll.longitude updatePositionsIcons() } } }) valueAnimator.addListener(object : AnimatorListenerAdapter() { override fun onAnimationStart(animation: Animator) { super.onAnimationStart(animation) //val update = positionsByVehDict[positionUpdate.vehicle]!! //remove the label at the start of the animation /*val annot = busLabelSymbolsByVeh[vehID] annot?.let { sym -> sym.textOpacity = 0.0f symbolsToUpdate.add(sym) } */ } override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) //recreate the label at the end of the animation //createLabelForVehicle(positionUpdate) /*val annot = busLabelSymbolsByVeh[vehID] annot?.let { sym -> sym.textOpacity = 1.0f sym.latLng = newPos //LatLng(newPos) symbolsToUpdate.add(sym) } */ } }) //set the new position as the current one but with the old lat and lng positionUpdate.latitude = currentUpdate.latitude positionUpdate.longitude = currentUpdate.longitude positionsByVehDict[vehID] = positionUpdate valueAnimator.duration = 300 valueAnimator.interpolator = LinearInterpolator() valueAnimator.start() animatorsByVeh[vehID] = valueAnimator } ?: { Log.e(DEBUG_TAG, "Have to run animation for veh ${positionUpdate.vehicle} but not in the dict, adding") positionsByVehDict[positionUpdate.vehicle] = positionUpdate } } /** * Update the bus positions displayed on the map, from the existing data */ private fun updatePositionsIcons(){ //avoid frequent updates val currentTime = System.currentTimeMillis() if(currentTime - lastUpdateTime < 60){ //DO NOT UPDATE THE MAP return } val features = ArrayList()//stops.mapNotNull { stop -> //stop.latitude?.let { lat -> // stop.longitude?.let { lon -> for (pos in positionsByVehDict.values){ //if (s.latitude!=null && s.longitude!=null) val point = Point.fromLngLat(pos.longitude, pos.latitude) features.add( Feature.fromGeometry( point, JsonObject().apply { addProperty("veh", pos.vehicle) addProperty("trip", pos.tripID) addProperty("bearing", pos.bearing ?:0.0f) addProperty("line", pos.routeID.substringBeforeLast('U')) } ) ) /*busLabelSymbolsByVeh[pos.vehicle]?.let { it.latLng = LatLng(pos.latitude, pos.longitude) symbolsToUpdate.add(it) } */ } //this updates the positions busesSource.setGeoJson(FeatureCollection.fromFeatures(features)) //update labels, clear cache to be used //symbolManager.update(symbolsToUpdate) symbolsToUpdate.clear() lastUpdateTime = System.currentTimeMillis() } // ------ LOCATION STUFF ----- @SuppressLint("MissingPermission") private fun requestInitialUserLocation() { val provider : String = LocationManager.GPS_PROVIDER//getBestLocationProvider() //provider.let { setLocationIconEnabled(true) Toast.makeText(requireContext(), R.string.position_searching_message, Toast.LENGTH_SHORT).show() pendingLocationActivation = true locationManager.requestSingleUpdate(provider, object : LocationListener { override fun onLocationChanged(location: Location) { val userLatLng = LatLng(location.latitude, location.longitude) val distanceToTarget = userLatLng.distanceTo(DEFAULT_LATLNG) if (distanceToTarget <= MAX_DIST_KM*1000.0) { map?.let{ // if we are still waiting for the position to enable if(pendingLocationActivation) setMapLocationEnabled(true, true, false) } } else { Toast.makeText(context, "You are too far, not showing the position", Toast.LENGTH_SHORT).show() } } override fun onProviderDisabled(provider: String) {} override fun onProviderEnabled(provider: String) {} @Deprecated("Deprecated in Java") override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {} }, null) } /** * Initialize the map location, but do not enable the component */ @SuppressLint("MissingPermission") private fun initMapLocation(style: Style, map: MapLibreMap, context: Context){ locationComponent = map.locationComponent val locationComponentOptions = LocationComponentOptions.builder(context) .pulseEnabled(true) .build() val locationComponentActivationOptions = MapLibreUtils.buildLocationComponentActivationOptions(style, locationComponentOptions, context) locationComponent.activateLocationComponent(locationComponentActivationOptions) locationComponent.isLocationComponentEnabled = false lastLocation?.let { if (it.accuracy < 200) locationComponent.forceLocationUpdate(it) } } /** * Handles logic of enabling the user location on the map */ @SuppressLint("MissingPermission") private fun setMapLocationEnabled(enabled: Boolean, assumePermissions: Boolean, fromClick: Boolean) { if (enabled) { val permissionOk = assumePermissions || Permissions.bothLocationPermissionsGranted(requireContext()) if (permissionOk) { Log.d(DEBUG_TAG, "Permission OK, starting location component, assumed: $assumePermissions") locationComponent.isLocationComponentEnabled = true if (initialStopToShow==null) { locationComponent.cameraMode = CameraMode.TRACKING //CameraMode.TRACKING setFollowingUser(true) } setLocationIconEnabled(true) if (fromClick) Toast.makeText(context, R.string.location_enabled, Toast.LENGTH_SHORT).show() } else { if (shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)) { //TODO: show dialog for permission rationale Toast.makeText(activity, R.string.enable_position_message_map, Toast.LENGTH_SHORT).show() } Log.d(DEBUG_TAG, "Requesting permission to show user location") enablingPositionFromClick = fromClick showUserPositionRequestLauncher.launch(Permissions.LOCATION_PERMISSIONS) } } else{ locationComponent.isLocationComponentEnabled = false setFollowingUser(false) setLocationIconEnabled(false) if (fromClick) { Toast.makeText(requireContext(), R.string.location_disabled, Toast.LENGTH_SHORT).show() if(pendingLocationActivation) pendingLocationActivation=false //Cancel the request for the enablement of the position } } } private fun setLocationIconEnabled(enabled: Boolean){ if (enabled) showUserPositionButton.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.location_circlew_red)) else showUserPositionButton.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.location_circlew_grey)) } /** * Helper method for GUI */ private fun updateFollowingIcon(enabled: Boolean){ if(enabled) followUserButton.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.ic_follow_me_on)) else followUserButton.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.ic_follow_me)) } private fun setFollowingUser(following: Boolean){ updateFollowingIcon(following) followingUserLocation = following if(following) ignoreCameraMovementForFollowing = true } private fun switchUserLocationStatus(view: View?){ if(pendingLocationActivation || locationComponent.isLocationComponentEnabled) setMapLocationEnabled(false, false, true) else{ Log.d(DEBUG_TAG, "Request enable location") setMapLocationEnabled(true, false, true) } } companion object { private const val STOPS_SOURCE_ID = "stops-source" private const val STOPS_LAYER_ID = "stops-layer" private const val STOPS_LAYER_SEL_ID ="stops-layer-selected" private const val LABELS_LAYER_ID = "bus-labels-layer" private const val LABELS_SOURCE = "labels-source" private const val STOP_IMAGE_ID ="bus-stop-icon" const val DEFAULT_CENTER_LAT = 45.0708 const val DEFAULT_CENTER_LON = 7.6858 private val DEFAULT_LATLNG = LatLng(DEFAULT_CENTER_LAT, DEFAULT_CENTER_LON) private const val POSITION_FOUND_ZOOM = 16.5 private const val NO_POSITION_ZOOM = 17.1 private const val MAX_DIST_KM = 90.0 private const val DEBUG_TAG = "BusTO-MapLibreFrag" private const val STOP_ACTIVE_IMG = "Stop-active" + const val FRAGMENT_TAG = "BusTOMapFragment" + private const val LOCATION_PERMISSION_REQUEST_CODE = 981202 /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param stop Eventual stop to center the map into * @return A new instance of fragment MapLibreFragment. */ @JvmStatic fun newInstance(stop: Stop?) = MapLibreFragment().apply { arguments = Bundle().let { // Cannot use Parcelable as it requires higher version of Android //stop?.let{putParcelable(STOP_TO_SHOW, it)} stop?.toBundle(it) } } } } \ No newline at end of file diff --git a/app/src/main/java/it/reyboz/bustorino/map/BusInfoWindow.kt b/app/src/main/java/it/reyboz/bustorino/map/BusInfoWindow.kt deleted file mode 100644 index 571f38d..0000000 --- a/app/src/main/java/it/reyboz/bustorino/map/BusInfoWindow.kt +++ /dev/null @@ -1,111 +0,0 @@ -/* - BusTO - Map components - Copyright (C) 2023 Fabio Mazza - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - */ -package it.reyboz.bustorino.map - -import android.annotation.SuppressLint -import android.view.View.* -import android.widget.ImageView -import android.widget.TextView -import androidx.constraintlayout.widget.ConstraintLayout -import androidx.core.view.marginEnd -import it.reyboz.bustorino.R -import it.reyboz.bustorino.backend.gtfs.LivePositionUpdate -import it.reyboz.bustorino.backend.gtfs.GtfsUtils -import it.reyboz.bustorino.backend.utils -import it.reyboz.bustorino.data.gtfs.MatoPattern -import org.osmdroid.views.MapView -import org.osmdroid.views.overlay.infowindow.BasicInfoWindow - -@SuppressLint("ClickableViewAccessibility") -class BusInfoWindow(map: MapView, - private val routeName: String, - private val vehicleLabel: String, - var pattern: MatoPattern?, - val showClose: Boolean, - private val touchUp: onTouchUp - ): - BasicInfoWindow(R.layout.bus_info_window,map) { - - init { - mView.setOnTouchListener { view, motionEvent -> - touchUp.onActionUp(pattern) - close() - //mView.performClick() - true - - } - } - constructor(map: MapView, update: LivePositionUpdate, pattern: MatoPattern?, showClose: Boolean, touchUp: onTouchUp, ): - this(map, - GtfsUtils.getLineNameFromGtfsID(update.routeID), - update.vehicle, - pattern, - showClose, - touchUp - ) - - - override fun onOpen(item: Any?) { - // super.onOpen(item) - val titleView = mView.findViewById(R.id.businfo_title) - val descrView = mView.findViewById(R.id.businfo_description) - val subdescrView = mView.findViewById(R.id.businfo_subdescription) - - val iconClose = mView.findViewById(R.id.closeIcon) - - //val nameRoute = GtfsUtils.getLineNameFromGtfsID(update.lineGtfsId) - - titleView.text = (mView.resources.getString(R.string.line_fill, routeName) - ) - subdescrView.text = vehicleLabel - //mView.resources.getString(R.string.vehicle_fill, vehicleLabel) - - - if(pattern!=null){ - descrView.text = pattern!!.headsign - descrView.visibility = VISIBLE - } else{ - descrView.visibility = GONE - } - if(!showClose){ - iconClose.visibility = GONE - val ctx = titleView.context - val layPars = (titleView.layoutParams as ConstraintLayout.LayoutParams).apply { - marginStart= 0 //utils.convertDipToPixelsInt(ctx, 8.0)//8.dpToPixels() - topMargin=utils.convertDipToPixelsInt(ctx, 4.0) - marginEnd=0 - bottomMargin=0 - } - //titleView.layoutParams = layPars - } - } - - fun setPatternAndDraw(pattern: MatoPattern?){ - if(pattern==null){ - return - } - this.pattern = pattern - if(isOpen){ - onOpen(pattern) - } - } - - fun interface onTouchUp{ - fun onActionUp(pattern: MatoPattern?) - } -} \ No newline at end of file diff --git a/app/src/main/java/it/reyboz/bustorino/map/BusPositionUtils.kt b/app/src/main/java/it/reyboz/bustorino/map/BusPositionUtils.kt deleted file mode 100644 index 9e6d7f7..0000000 --- a/app/src/main/java/it/reyboz/bustorino/map/BusPositionUtils.kt +++ /dev/null @@ -1,41 +0,0 @@ -package it.reyboz.bustorino.map - -import android.animation.ObjectAnimator -import android.util.Log -import androidx.core.content.res.ResourcesCompat -import it.reyboz.bustorino.backend.gtfs.LivePositionUpdate -import it.reyboz.bustorino.data.gtfs.MatoPattern -import it.reyboz.bustorino.data.gtfs.TripAndPatternWithStops -import org.osmdroid.util.GeoPoint -import org.osmdroid.views.MapView -import org.osmdroid.views.overlay.Marker - -class BusPositionUtils { - companion object{ - @JvmStatic - public fun updateBusPositionMarker(map: MapView, marker: Marker?, posUpdate: LivePositionUpdate, - tripMarkersAnimators: HashMap, - justCreated: Boolean) { - val position: GeoPoint - val updateID = posUpdate.tripID - if (!justCreated) { - position = marker!!.position - if (posUpdate.latitude != position.latitude || posUpdate.longitude != position.longitude) { - val newpos = GeoPoint(posUpdate.latitude, posUpdate.longitude) - val valueAnimator = MarkerUtils.makeMarkerAnimator( - map, marker, newpos, MarkerUtils.LINEAR_ANIMATION, 1200 - ) - valueAnimator.setAutoCancel(true) - tripMarkersAnimators.put(updateID, valueAnimator) - valueAnimator.start() - } - //marker.setPosition(new GeoPoint(posUpdate.getLatitude(), posUpdate.getLongitude())); - } else { - position = GeoPoint(posUpdate.latitude, posUpdate.longitude) - marker!!.position = position - } - //if (posUpdate.bearing != null) marker.rotation = posUpdate.bearing * -1f - marker.rotation = posUpdate.bearing?.let { it*-1f } ?: 0.0f - } - } -} \ No newline at end of file diff --git a/app/src/main/java/it/reyboz/bustorino/map/CustomInfoWindow.java b/app/src/main/java/it/reyboz/bustorino/map/CustomInfoWindow.java deleted file mode 100644 index 0a8fd47..0000000 --- a/app/src/main/java/it/reyboz/bustorino/map/CustomInfoWindow.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - BusTO - Map components - Copyright (C) 2020 Andrea Ugo - Copyright (C) 2021 Fabio Mazza - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - */ -package it.reyboz.bustorino.map; - -import android.annotation.SuppressLint; -import android.os.Build; -import android.view.MotionEvent; -import android.view.View; - -import android.widget.ImageView; -import android.widget.TextView; - -import androidx.annotation.NonNull; -import androidx.annotation.Nullable; - -import androidx.core.content.ContextCompat; -import org.osmdroid.views.MapView; -import org.osmdroid.views.overlay.infowindow.BasicInfoWindow; - -import it.reyboz.bustorino.R; - -public class CustomInfoWindow extends BasicInfoWindow { - //TODO: Make the action on the Click customizable - private final TouchResponder touchResponder; - private final String stopID, name, routesStopping; - - private final int colorResID; - //final DisplayMetrics metrics; - - @Override - public void onOpen(Object item) { - super.onOpen(item); - TextView descr_textView = mView.findViewById(R.id.bubble_description); - CharSequence text = descr_textView.getText(); - TextView titleTV = mView.findViewById(R.id.bubble_title); - titleTV.setTextColor(ContextCompat.getColor(mView.getContext(),colorResID)); - //Log.d("BusTO-MapInfoWindow", "Descrip: "+text+", title "+(titleTV==null? "null": titleTV.getText())); - - if (text==null || !text.toString().isEmpty()){ - descr_textView.setVisibility(View.VISIBLE); - } else - descr_textView.setVisibility(View.GONE); - - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { - mView.setElevation(3.2f); - } - TextView subDescriptTextView = mView.findViewById(R.id.bubble_subdescription); - if (routesStopping!=null && !routesStopping.isEmpty()){ - subDescriptTextView.setText(routesStopping); - subDescriptTextView.setVisibility(View.VISIBLE); - } - - //check if there is a close image - ImageView image = mView.findViewById(R.id.closeIcon); - if (image != null) { - image.setOnClickListener( view -> close()); - } - - } - public CustomInfoWindow(MapView mapView, String stopID, String name, String routesStopping, - TouchResponder responder){ - - this(mapView, stopID, name, routesStopping, responder,R.layout.map_popup, R.color.red_darker); - } - - @SuppressLint("ClickableViewAccessibility") - public CustomInfoWindow(MapView mapView, - String stopID, - String name, - String routesStopping, - TouchResponder responder, - int layoutId, - int colorResId) { - // get the personalized layout - super(layoutId, mapView); - touchResponder =responder; - this.stopID = stopID; - this.name = name; - this.routesStopping = routesStopping; - colorResID = colorResId; - - //metrics = Resources.getSystem().getDisplayMetrics(); - - // make clickable - mView.setOnTouchListener((View v, MotionEvent e) -> { - if (e.getAction() == MotionEvent.ACTION_UP) { - // on click - touchResponder.onActionUp(this.stopID, this.name); - } - return true; - }); - - - } - - public interface TouchResponder{ - /** - * React to a click on the stop View - * @param stopID the stop id - * @param stopName the stop name - */ - void onActionUp(@NonNull String stopID, @Nullable String stopName); - } -} diff --git a/app/src/main/java/it/reyboz/bustorino/map/GeoPointInterpolator.java b/app/src/main/java/it/reyboz/bustorino/map/LatLngInterpolator.java similarity index 79% rename from app/src/main/java/it/reyboz/bustorino/map/GeoPointInterpolator.java rename to app/src/main/java/it/reyboz/bustorino/map/LatLngInterpolator.java index 94a8323..e62d32d 100644 --- a/app/src/main/java/it/reyboz/bustorino/map/GeoPointInterpolator.java +++ b/app/src/main/java/it/reyboz/bustorino/map/LatLngInterpolator.java @@ -1,85 +1,86 @@ package it.reyboz.bustorino.map; /* Copyright 2013 Google Inc. Licensed under Apache 2.0: http://www.apache.org/licenses/LICENSE-2.0.html */ -import org.osmdroid.util.GeoPoint; + +import org.maplibre.android.geometry.LatLng; import static java.lang.Math.asin; import static java.lang.Math.atan2; import static java.lang.Math.cos; import static java.lang.Math.pow; import static java.lang.Math.sin; import static java.lang.Math.sqrt; import static java.lang.Math.toDegrees; import static java.lang.Math.toRadians; -public interface GeoPointInterpolator { - public GeoPoint interpolate(float fraction, GeoPoint a, GeoPoint b); +public interface LatLngInterpolator { + public LatLng interpolate(float fraction, LatLng a, LatLng b); - public class Linear implements GeoPointInterpolator { + public class Linear implements LatLngInterpolator { @Override - public GeoPoint interpolate(float fraction, GeoPoint a, GeoPoint b) { + public LatLng interpolate(float fraction, LatLng a, LatLng b) { double lat = (b.getLatitude() - a.getLatitude()) * fraction + a.getLatitude(); double lng = (b.getLongitude() - a.getLongitude()) * fraction + a.getLongitude(); - return new GeoPoint(lat, lng); + return new LatLng(lat, lng); } } - public class LinearFixed implements GeoPointInterpolator { + public class LinearFixed implements LatLngInterpolator { @Override - public GeoPoint interpolate(float fraction, GeoPoint a, GeoPoint b) { + public LatLng interpolate(float fraction, LatLng a, LatLng b) { double lat = (b.getLatitude() - a.getLatitude()) * fraction + a.getLatitude(); double lngDelta = b.getLongitude() - a.getLongitude(); // Take the shortest path across the 180th meridian. if (Math.abs(lngDelta) > 180) { lngDelta -= Math.signum(lngDelta) * 360; } double lng = lngDelta * fraction + a.getLongitude(); - return new GeoPoint(lat, lng); + return new LatLng(lat, lng); } } - public class Spherical implements GeoPointInterpolator { + public class Spherical implements LatLngInterpolator { /* From github.com/googlemaps/android-maps-utils */ @Override - public GeoPoint interpolate(float fraction, GeoPoint from, GeoPoint to) { + public LatLng interpolate(float fraction, LatLng from, LatLng to) { // http://en.wikipedia.org/wiki/Slerp double fromLat = toRadians(from.getLatitude()); double fromLng = toRadians(from.getLongitude()); double toLat = toRadians(to.getLatitude()); double toLng = toRadians(to.getLongitude()); double cosFromLat = cos(fromLat); double cosToLat = cos(toLat); // Computes Spherical interpolation coefficients. double angle = computeAngleBetween(fromLat, fromLng, toLat, toLng); double sinAngle = sin(angle); if (sinAngle < 1E-6) { return from; } double a = sin((1 - fraction) * angle) / sinAngle; double b = sin(fraction * angle) / sinAngle; // Converts from polar to vector and interpolate. double x = a * cosFromLat * cos(fromLng) + b * cosToLat * cos(toLng); double y = a * cosFromLat * sin(fromLng) + b * cosToLat * sin(toLng); double z = a * sin(fromLat) + b * sin(toLat); // Converts interpolated vector back to polar. double lat = atan2(z, sqrt(x * x + y * y)); double lng = atan2(y, x); - return new GeoPoint(toDegrees(lat), toDegrees(lng)); + return new LatLng(toDegrees(lat), toDegrees(lng)); } private double computeAngleBetween(double fromLat, double fromLng, double toLat, double toLng) { // Haversine's formula double dLat = fromLat - toLat; double dLng = fromLng - toLng; return 2 * asin(sqrt(pow(sin(dLat / 2), 2) + cos(fromLat) * cos(toLat) * pow(sin(dLng / 2), 2))); } } } diff --git a/app/src/main/java/it/reyboz/bustorino/map/LocationOverlay.java b/app/src/main/java/it/reyboz/bustorino/map/LocationOverlay.java deleted file mode 100644 index cd0bd59..0000000 --- a/app/src/main/java/it/reyboz/bustorino/map/LocationOverlay.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - BusTO - Map components - Copyright (C) 2021 Fabio Mazza - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program. If not, see . - */ -package it.reyboz.bustorino.map; - - -import android.content.Context; -import android.util.Log; -import org.osmdroid.views.MapView; -import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider; -import org.osmdroid.views.overlay.mylocation.IMyLocationProvider; -import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay; - -public class LocationOverlay extends MyLocationNewOverlay { - - private final static String DEBUG_TAG = "BusTOLocationOverlay"; - final OverlayCallbacks callbacks; - - public LocationOverlay(MapView mapView, OverlayCallbacks callbacks) { - super(mapView); - this.callbacks = callbacks; - } - - public LocationOverlay(IMyLocationProvider myLocationProvider, MapView mapView, OverlayCallbacks callbacks) { - super(myLocationProvider, mapView); - this.callbacks = callbacks; - } - - @Override - public void enableFollowLocation() { - super.enableFollowLocation(); - callbacks.onEnableFollowMyLocation(); - } - - @Override - public void disableFollowLocation() { - - super.disableFollowLocation(); - callbacks.onDisableFollowMyLocation(); - } - - public static LocationOverlay createLocationOverlay(boolean enableLocation, MapView map, Context context, OverlayCallbacks locationCallbacks){ - if(context== null) { - Log.d(DEBUG_TAG, "Cannot start location overlay, context is null"); - return null; - } - // Location Overlay - // from OpenBikeSharing (THANK GOD) - Log.d(DEBUG_TAG, "Starting position overlay"); - GpsMyLocationProvider imlp = new GpsMyLocationProvider(context.getApplicationContext()); - imlp.setLocationUpdateMinDistance(5); - imlp.setLocationUpdateMinTime(2000); - - final LocationOverlay overlay = new LocationOverlay(imlp,map, locationCallbacks); - if (enableLocation) overlay.enableMyLocation(); - //overlay.setOptionsMenuEnabled(true); - - return overlay; - } - - public interface OverlayCallbacks{ - /** - * Called right after disableFollowMyLocation - */ - void onDisableFollowMyLocation(); - - /** - * Called right after enableFollowMyLocation - */ - void onEnableFollowMyLocation(); - } -} diff --git a/app/src/main/java/it/reyboz/bustorino/map/Styles.kt b/app/src/main/java/it/reyboz/bustorino/map/MapLibreStyles.kt similarity index 98% rename from app/src/main/java/it/reyboz/bustorino/map/Styles.kt rename to app/src/main/java/it/reyboz/bustorino/map/MapLibreStyles.kt index 8c76ada..39eda0e 100644 --- a/app/src/main/java/it/reyboz/bustorino/map/Styles.kt +++ b/app/src/main/java/it/reyboz/bustorino/map/MapLibreStyles.kt @@ -1,56 +1,56 @@ package it.reyboz.bustorino.map import android.content.Context import it.reyboz.bustorino.util.ViewUtils import org.maplibre.android.maps.Style -object Styles { +object MapLibreStyles { const val DEMOTILES = "https://demotiles.maplibre.org/style.json" const val VERSATILES = "https://tiles.versatiles.org/assets/styles/colorful.json" const val AMERICANA = "https://americanamap.org/style.json" const val OPENFREEMAP_LIBERTY = "https://tiles.openfreemap.org/styles/liberty" const val OPENFREEMAP_BRIGHT = "https://tiles.openfreemap.org/styles/bright" const val BASIC_V8 = "mapbox://styles/mapbox/streets-v8" const val AWS_OPEN_DATA_STANDARD_LIGHT = "https://maps.geo.us-east-2.amazonaws.com/maps/v0/maps/OpenDataStyle/style-descriptor?key=v1.public.eyJqdGkiOiI1NjY5ZTU4My0yNWQwLTQ5MjctODhkMS03OGUxOTY4Y2RhMzgifR_7GLT66TNRXhZJ4KyJ-GK1TPYD9DaWuc5o6YyVmlikVwMaLvEs_iqkCIydspe_vjmgUVsIQstkGoInXV_nd5CcmqRMMa-_wb66SxDdbeRDvmmkpy2Ow_LX9GJDgL2bbiCws0wupJPFDwWCWFLwpK9ICmzGvNcrPbX5uczOQL0N8V9iUvziA52a1WWkZucIf6MUViFRf3XoFkyAT15Ll0NDypAzY63Bnj8_zS8bOaCvJaQqcXM9lrbTusy8Ftq8cEbbK5aMFapXRjug7qcrzUiQ5sr0g23qdMvnKJQFfo7JuQn8vwAksxrQm6A0ByceEXSfyaBoVpFcTzEclxUomhY.NjAyMWJkZWUtMGMyOS00NmRkLThjZTMtODEyOTkzZTUyMTBi" private fun protomaps(style: String): String { return "https://api.protomaps.com/styles/v2/${style}.json?key=e761cc7daedf832a" } private fun makeStyleMapBoxUrl(dark: Boolean) = if (dark) "https://basemaps.cartocdn.com/gl/dark-matter-gl-style/style.json" else //"https://basemaps.cartocdn.com/gl/positron-gl-style/style.json" "https://basemaps.cartocdn.com/gl/voyager-gl-style/style.json" val PROTOMAPS_LIGHT = protomaps("light") val PROTOMAPS_DARK = protomaps("dark") val PROTOMAPS_GRAYSCALE = protomaps("grayscale") val PROTOMAPS_WHITE = protomaps("white") val PROTOMAPS_BLACK = protomaps("black") val CARTO_DARK = makeStyleMapBoxUrl(true) val CARTO_VOYAGER = makeStyleMapBoxUrl(false) fun getPredefinedStyleWithFallback(name: String): String { try { val style = Style.getPredefinedStyle(name) return style } catch (e: Exception) { return OPENFREEMAP_LIBERTY } } fun getJsonStyleFromAsset(context: Context, filename: String) = ViewUtils.loadJsonFromAsset(context,filename) } \ No newline at end of file diff --git a/app/src/main/java/it/reyboz/bustorino/map/MarkerUtils.java b/app/src/main/java/it/reyboz/bustorino/map/MarkerUtils.java deleted file mode 100644 index 962898f..0000000 --- a/app/src/main/java/it/reyboz/bustorino/map/MarkerUtils.java +++ /dev/null @@ -1,102 +0,0 @@ -package it.reyboz.bustorino.map; - -import android.animation.ObjectAnimator; -import android.animation.TypeEvaluator; -import android.graphics.drawable.Drawable; -import android.util.Log; -import android.util.Property; - - -import android.view.animation.LinearInterpolator; -import it.reyboz.bustorino.R; -import org.osmdroid.util.GeoPoint; -import org.osmdroid.views.MapView; -import org.osmdroid.views.overlay.Marker; -import org.osmdroid.views.overlay.infowindow.InfoWindow; - -public class MarkerUtils { - - public static final int LINEAR_ANIMATION = 1; - - /* Copyright 2013 Google Inc. - Licensed under Apache 2.0: http://www.apache.org/licenses/LICENSE-2.0.html */ - public static ObjectAnimator makeMarkerAnimator(final MapView map, Marker marker, GeoPoint finalPosition, int animationType, int durationMs) { - - GeoPointInterpolator interpolator; - switch (animationType){ - case LINEAR_ANIMATION: - interpolator = new GeoPointInterpolator.Linear(); - break; - default: - throw new IllegalArgumentException("Value "+animationType+ " for animationType is invalid"); - } - TypeEvaluator typeEvaluator = (fraction, startValue, endValue) -> - interpolator.interpolate(fraction, startValue, endValue); - Property property = Property.of(Marker.class, GeoPoint.class, "position"); - ObjectAnimator animator = ObjectAnimator.ofObject(marker, property, typeEvaluator, finalPosition); - switch (animationType){ - case LINEAR_ANIMATION: - - animator.setInterpolator(new LinearInterpolator()); - default: - } - animator.setDuration(durationMs); - //animator.start(); - return animator; - } - - public static Marker makeMarker(GeoPoint geoPoint, String stopID, String stopName, - String routesStopping, - MapView map, - CustomInfoWindow.TouchResponder responder, - Drawable icon, - int infoWindowLayout, - int titleColorId) { - - // add a marker - final Marker marker = new Marker(map); - - // set custom info window as info window - CustomInfoWindow popup = new CustomInfoWindow(map, stopID, stopName, routesStopping, responder, infoWindowLayout, titleColorId); - marker.setInfoWindow(popup); - - // make the marker clickable - marker.setOnMarkerClickListener((thisMarker, mapView) -> { - if (thisMarker.isInfoWindowOpen()) { - // on second click - Log.w("BusTO-OsmMap", "Pressed on the click marker"); - } else { - // on first click - - // hide all opened info window - InfoWindow.closeAllInfoWindowsOn(map); - // show this particular info window - thisMarker.showInfoWindow(); - // move the map to its position - map.getController().animateTo(thisMarker.getPosition()); - } - - return true; - }); - - // set its position - marker.setPosition(geoPoint); - marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM); - // add to it an icon - //marker.setIcon(getResources().getDrawable(R.drawable.bus_marker)); - - marker.setIcon(icon); - // add to it a title - marker.setTitle(stopName); - // set the description as the ID - marker.setSnippet(stopID); - - // show popup info window of the searched marker - /*if (isStartMarker) { - marker.showInfoWindow(); - //map.getController().animateTo(marker.getPosition()); - }*/ - - return marker; - } -} diff --git a/app/src/main/java/it/reyboz/bustorino/util/RoutePositionSorter.java b/app/src/main/java/it/reyboz/bustorino/util/RoutePositionSorter.java index abb9b0f..2eb0f23 100644 --- a/app/src/main/java/it/reyboz/bustorino/util/RoutePositionSorter.java +++ b/app/src/main/java/it/reyboz/bustorino/util/RoutePositionSorter.java @@ -1,76 +1,72 @@ /* BusTO (util) Copyright (C) 2019 Fabio Mazza This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ package it.reyboz.bustorino.util; import android.location.Location; import androidx.core.util.Pair; import android.util.Log; -import it.reyboz.bustorino.backend.Passaggio; -import it.reyboz.bustorino.backend.Route; -import it.reyboz.bustorino.backend.Stop; -import it.reyboz.bustorino.backend.utils; -import org.osmdroid.api.IGeoPoint; +import it.reyboz.bustorino.backend.*; import java.util.Collections; import java.util.Comparator; import java.util.List; public class RoutePositionSorter implements Comparator> { private final double latPos, longPos; private final double minutialmetro = 6.0/100; //v = 5km/h private final double distancemultiplier = 2./3; public RoutePositionSorter(double latitude, double longitude){ latPos = latitude; longPos = longitude; } - public RoutePositionSorter(IGeoPoint position){ + public RoutePositionSorter(GPSPoint position){ this(position.getLatitude(), position.getLongitude()); } @Override public int compare(Pair pair1, Pair pair2) throws NullPointerException{ int delta = 0; final Stop stop1 = pair1.first, stop2 = pair2.first; double dist1 = utils.measuredistanceBetween(latPos,longPos, stop1.getLatitude(),stop1.getLongitude()); double dist2 = utils.measuredistanceBetween(latPos,longPos, stop2.getLatitude(),stop2.getLongitude()); final List passaggi1 = pair1.second.passaggi, passaggi2 = pair2.second.passaggi; if(passaggi1.size()<=0 || passaggi2.size()<=0){ Log.e("ArrivalsStopAdapter","Cannot compare: No arrivals in one of the stops"); } else { Collections.sort(passaggi1); Collections.sort(passaggi2); int deltaOre = passaggi1.get(0).hh-passaggi2.get(0).hh; if(deltaOre>12) deltaOre -= 24; else if (deltaOre<-12) deltaOre += 24; delta+=deltaOre*60 + passaggi1.get(0).mm-passaggi2.get(0).mm; } delta += (int)((dist1 -dist2)*minutialmetro*distancemultiplier); return delta; } @Override public boolean equals(Object obj) { return obj instanceof RoutePositionSorter; } } diff --git a/app/src/main/java/it/reyboz/bustorino/viewmodels/StopsMapViewModel.kt b/app/src/main/java/it/reyboz/bustorino/viewmodels/StopsMapViewModel.kt index 1c75b83..cc8270b 100644 --- a/app/src/main/java/it/reyboz/bustorino/viewmodels/StopsMapViewModel.kt +++ b/app/src/main/java/it/reyboz/bustorino/viewmodels/StopsMapViewModel.kt @@ -1,88 +1,89 @@ package it.reyboz.bustorino.viewmodels import android.app.Application import android.os.Bundle import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import it.reyboz.bustorino.backend.Stop import it.reyboz.bustorino.data.NextGenDB import it.reyboz.bustorino.data.OldDataRepository import org.maplibre.android.geometry.LatLngBounds -import org.osmdroid.util.BoundingBox import java.util.concurrent.Executors import kotlin.collections.ArrayList class StopsMapViewModel(application: Application): AndroidViewModel(application) { private val executor = Executors.newFixedThreadPool(2) private val oldRepo = OldDataRepository(executor, NextGenDB.getInstance(application)) val stopsToShow = MutableLiveData(ArrayList()) private var stopsShownIDs = HashSet() private var allStopsLoaded = HashMap() val stopsInBoundingBox = MutableLiveData>() private val callback = OldDataRepository.Callback> { res -> if(res.isSuccess){ stopsInBoundingBox.postValue(res.result) Log.d(DEBUG_TAG, "Setting value of stops in bounding box") } } private val addStopsCallback = OldDataRepository.Callback> { res -> if(res.isSuccess) res.result?.let{ newStops -> val stopsAdd = stopsToShow.value ?: ArrayList() for (s in newStops){ if (s.ID !in stopsShownIDs){ stopsShownIDs.add(s.ID) stopsAdd.add(s) allStopsLoaded[s.ID] = s } } stopsToShow.postValue(stopsAdd) //Log.d(DEBUG_TAG, "Loaded ${stopsAdd.size} stops in total") } } fun getStopByID(id: String): Stop? { if (id in allStopsLoaded) return allStopsLoaded[id] else return null } fun getAllStopsLoaded(): ArrayList{ return ArrayList(allStopsLoaded.values) } - fun requestStopsInBoundingBox(bb: BoundingBox) { + /*fun requestStopsInBoundingBox(bb: BoundingBox) { bb.let { Log.d(DEBUG_TAG, "Launching stop request") oldRepo.requestStopsInArea(it.latSouth, it.latNorth, it.lonWest, it.lonEast, callback) } } + + */ fun requestStopsInLatLng(bb: LatLngBounds) { bb.let { Log.d(DEBUG_TAG, "Launching stop request") oldRepo.requestStopsInArea(it.latitudeSouth, it.latitudeNorth, it.longitudeWest, it.longitudeEast, callback) } } fun loadStopsInLatLngBounds(bb: LatLngBounds?){ bb?.let { Log.d(DEBUG_TAG, "Launching stop request") oldRepo.requestStopsInArea(it.latitudeSouth, it.latitudeNorth, it.longitudeWest, it.longitudeEast, addStopsCallback) } } var savedState: Bundle? = null companion object{ private const val DEBUG_TAG = "BusTOStopMapViewModel" } } \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index eccee43..629be30 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1,362 +1,361 @@ BusTO Libre BusTO BusTO dev BusTO git You\'re using the latest in technology when it comes to respecting your privacy. Search Scan QR Code Yes No Next Previous Install Barcode Scanner? This application requires an app to scan the QR codes. Would you like to install Barcode Scanner now? Bus stop number Bus stop name Insert bus stop number Insert bus stop name %1$s towards %2$s %s (unknown destination) Verify your Internet connection! Seems that no bus stop have this name No arrivals found for this stop Error parsing the 5T/GTT website (damn site!) Name too short, type more characters and retry Arrivals at: %1$s Choose the bus stop… Line Lines Urban lines Extra urban lines Tourist lines No lines found in this category No lines match the searched name Destination: Lines: %1$s Line: %1$s No timetable found No QR code found, try using another app to scan Unexpected internal error, cannot extract data from GTT/5T website Help About the app More about Contribute https://gitpull.it/w/librebusto/en/ Source code Licence11 Meet the author Bus stop is now in your favorites Bus stop removed from your favorites Added line to favorites Remove line from favorites Favorites Favorites Favorites Map No favorites? Arghh! Press on a bus stop star to populate this list! Delete Rename Rename the bus stop Reset About the app Tap the star to add the bus stop to the favourites\n\nHow to read timelines:\n   12:56* Real-time arrivals\n   12:56   Scheduled arrivals\n\nPull down to refresh the timetable \n Long press on Arrivals source to change the source of the arrival times GOT IT! Arrival times No arrivals found for lines: Welcome!

Thanks for using BusTO, an open source and independent app useful to move around Torino using a Free/Libre software.


Why use this app?

- You\'ll never be tracked
- You\'ll never see boring ads
- We\'ll always respect your privacy
- Moreover, it\'s lightweight!


Introductory tutorial

If you want to see the introduction again, use the button below:

]]>
News and Updates

On the Telegram channel, you can find information about the latest app updates

]]>
How does it work?

This app is able to do all the amazing things it does by pulling data from www.gtt.to.it, www.5t.torino.it or muoversiatorino.it "for personal use", along with open data from the AperTO (aperto.comune.torino.it) website.


The work of several people is behind this app, in particular:
- Fabio Mazza, current senior rockstar developer.
- Andrea Ugo, current junior rockstar developer.
- Silviu Chiriac, designer of the 2021 logo.
- Marco M, rockstar tester and bug hunter.
- Ludovico Pavesi, previous senior rockstar developer (asd).
- Valerio Bozzolan, maintainer and infrastructure (sponsor).
- Marco Gagino, contributor and first icon creator.
- JSoup web scraper library.
- makovkastar floating buttons.
- Google for icons and support and design libraries.
- Other icons from Bootstrap, Feather, and Hero Icons.
- All the contributors, and the beta testers, too!


If you want more technical information or to contribute to development, use the buttons below! ]]>
Licenses

The app and the related source code are released by Valerio Bozzolan and the other authors under the terms of the GNU General Public License v3+). So everyone is allowed to use, to study, to improve and to share this app by any kind of means and for any purpose: under the conditions of maintaining this rights and of attributing the original work to Valerio Bozzolan.


Notes

This app has been developed with the hope to be useful to everyone, but comes without ANY warranty of any kind.

The data used by the app comes directly from GTT and other public agencies: if you find any errors, please take it up to them, not to us.

This translation is kindly provided by Riccardo Caniato, Marco Gagino and Fabio Mazza.

Now you can hack public transport, too! :)

]]>
Cannot add to favorites (storage full or corrupted database?)! View on a map Cannot find any application to show it in Cannot find the position of the stop ListFragment - BusTO it.reyboz.bustorino.preferences db_is_updating Nearby stops Nearby connections App version The number of stops to show in the recent stops is invalid Invalid value, put a valid number Finding location No stops nearby Minimum number of stops Preferences Settings Settings General Experimental features Maximum distance (meters) Recent stops General settings Database management Launch manual database update Allow access to location to show it on the map Allow access to location to show stops nearby Please enable location on the device Database update in progress… Updating the database Force database update Touch to update the app database now is arriving at at the stop %1$s - %2$s Show arrivals Show stops Join Telegram channel Show introduction Center on my location Follow me Enable or disable location Location enabled Location disabled Location is disabled on device Arrivals source: %1$s GTT App GTT Website 5T Torino website Muoversi a Torino app Undetermined Changing arrival times source… Long press to change the source of arrivals @string/source_mato @string/fivetapifetcher @string/gttjsonfetcher @string/fivetscraper Sources of arrival times Select which sources of arrival times to use Default Default channel for notifications Database operations Updates of the app database BusTO - live position service Live positions Showing activity related to the live positions service MaTO live bus positions service is running Downloading trips from MaTO server Asked for %1$s permission too many times Cannot use the map with the storage permission! storage The application has crashed because you encountered a bug. \nIf you want, you can help the developers by sending the crash report via email. \nNote that no sensitive data is contained in the report, just small bits of info on your phone and app configuration/state. The application crashed and the crash report is in the attachments. Please describe what you were doing before the crash: \n Arrivals Map Favorites Open navigation drawer Close navigation drawer Experiments Buy us a coffee Map Search by stop Filter by name Launching database update Downloading data from MaTO server Capitalize directions @string/directions_capitalize_no_change @string/directions_capitalize_everything @string/directions_capitalize_first_letter Do not change arrivals directions Capitalize everything Capitalize only first letter KEEP CAPITALIZE_ALL CAPITALIZE_FIRST Section to show on startup Touch to change it Show arrivals touching on stop Enable experiments Long press the stop for options @string/nav_arrivals_text @string/nav_favorites_text @string/nav_map_text @string/lines Source of real time positions for buses and trams - + MaTO (updated more frequently, might be offline) + GTFS RT (more stable, less frequently updated) @string/positions_source_mato_descr @string/positions_source_gtfsrt_descr - MaTO (updated more frequently, might be offline) - GTFS RT (more stable, less frequently updated) + Style of the map Versatiles (vector) OSM legacy (raster, lighter) @string/map_style_versatiles @string/map_style_legacy_raster - MaTO (updated more frequently, might be offline) - GTFS RT (more stable, less frequently updated) Remove trips data (free up space) All GTFS trips have been removed from the database Show tutorial open source app for Turin public transport. This is an independent app, with no ads and no tracking whatsoever.]]> favorites by touching the star next to its name]]> blue)]]> Settings to customize the app behaviour, and in the About the app section if you want to know more about the app and the developers.]]> Notifications permission to show the information about background processing. Press the button below to grant it]]> Grant location permission Location permission granted Location permission has not been granted OK, close the tutorial Close the tutorial Enable notifications Notifications enabled Backup and restore Import/export preferences Data saved Backup to file Import data from backup Backup has been imported Check at least one item to import! Import favorites from backup Import preferences from backup Hello blank fragment No map app present to show the stop! Direction is already shown Loading destination… Destination unknown +