Page MenuHomeGitPull.it

No OneTemporary

Authored By
Unknown
Size
276 KB
Referenced Files
None
Subscribers
None
This file is larger than 256 KB, so syntax highlighting was skipped.
diff --git a/.gitignore b/.gitignore
index eac6c11..0a78043 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,64 +1,66 @@
# Created by .ignore support plugin (hsz.mobi)
### Android template
# Built application files
*.apk
*.ap_
+*.dm
+*.aab
# Files for the ART/Dalvik VM
*.dex
# Java class files
*.class
# Generated files
bin/
gen/
out/
# Gradle files
.gradle/
build/
# Local configuration file (sdk path, etc)
local.properties
# Proguard folder generated by Eclipse
proguard/
# Log Files
*.log
# Android Studio Navigation editor temp files
.navigation/
# Android Studio captures folder
captures/
# IntelliJ
*.iml
.idea
# Keystore files
# Uncomment the following line if you do not want to check your keystore files in.
#*.jks
# External native build folder generated in Android Studio 2.2 and later
.externalNativeBuild
# Google Services (e.g. APIs or Firebase)
google-services.json
# Freeline
freeline.py
freeline/
freeline_project_description.json
# fastlane
fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots
fastlane/test_output
fastlane/readme.md
# script stuff
/cli/config.php
diff --git a/app/src/main/java/it/reyboz/bustorino/fragments/ArrivalsFragment.kt b/app/src/main/java/it/reyboz/bustorino/fragments/ArrivalsFragment.kt
index 32737b9..4139886 100644
--- a/app/src/main/java/it/reyboz/bustorino/fragments/ArrivalsFragment.kt
+++ b/app/src/main/java/it/reyboz/bustorino/fragments/ArrivalsFragment.kt
@@ -1,885 +1,885 @@
/*
BusTO - Fragments components
Copyright (C) 2018-2026 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 <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.fragments
import android.content.Context
import android.database.Cursor
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.cardview.widget.CardView
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.loader.app.LoaderManager
import androidx.loader.content.CursorLoader
import androidx.loader.content.Loader
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import it.reyboz.bustorino.R
import it.reyboz.bustorino.adapters.PalinaAdapter
import it.reyboz.bustorino.adapters.PalinaAdapter.PalinaClickListener
import it.reyboz.bustorino.adapters.RouteAdapter
import it.reyboz.bustorino.adapters.RouteOnlyLineAdapter
import it.reyboz.bustorino.backend.*
import it.reyboz.bustorino.backend.DBStatusManager.OnDBUpdateStatusChangeListener
import it.reyboz.bustorino.backend.Passaggio.Source
import it.reyboz.bustorino.data.AppDataProvider
import it.reyboz.bustorino.data.NextGenDB
import it.reyboz.bustorino.data.UserDB
import it.reyboz.bustorino.middleware.CoroutineFavoriteAction
import it.reyboz.bustorino.util.LinesNameSorter
import it.reyboz.bustorino.viewmodels.ArrivalsViewModel
import it.reyboz.bustorino.viewmodels.ServiceAlertsViewModel
import java.util.*
class ArrivalsFragment : ResultBaseFragment(), LoaderManager.LoaderCallbacks<Cursor> {
private var DEBUG_TAG = DEBUG_TAG_ALL
private lateinit var stopID: String
//private set
private var stopName: String? = null
private var prefs: DBStatusManager? = null
private var listener: OnDBUpdateStatusChangeListener? = null
private var justCreated = false
private var lastUpdatedPalina: Palina? = null
private var needUpdateOnAttach = false
private var fetchersChangeRequestPending = false
//Views
protected lateinit var addToFavorites: ImageButton
protected lateinit var openInMapButton: ImageButton
protected lateinit var arrivalsSourceTextView: TextView
private lateinit var messageTextView: TextView
private lateinit var preMessageTextView: TextView // this hold the "Arrivals at: " text
protected lateinit var arrivalsRecyclerView: RecyclerView
private var mListAdapter: PalinaAdapter? = null
private lateinit var resultsLayout : LinearLayout
private lateinit var loadingMessageTextView: TextView
private lateinit var progressBar: ProgressBar
private lateinit var howDoesItWorkTextView: TextView
private lateinit var hideHintButton: Button
private lateinit var alertsCardView : CardView
//private NestedScrollView theScrollView;
protected lateinit var noArrivalsRecyclerView: RecyclerView
private var noArrivalsAdapter: RouteOnlyLineAdapter? = null
private var noArrivalsTitleView: TextView? = null
private var layoutManager: GridLayoutManager? = null
//private View canaryEndView;
private var fetchers: List<ArrivalsFetcher?> = ArrayList()
private val arrivalsViewModel : ArrivalsViewModel by viewModels()
private val alertsViewModel: ServiceAlertsViewModel by activityViewModels()
private var reloadOnResume = true
private var routesNoPassages = listOf<Route>()
fun getStopID() = stopID
private val palinaClickListener: PalinaClickListener = object : PalinaClickListener {
override fun showRouteFullDirection(route: Route) {
var routeName = route.routeLongDisplayName
Log.d(DEBUG_TAG, "Make toast for line " + route.name)
if (context == null) Log.e(DEBUG_TAG, "Touched on a route but Context is null")
else if (route.destinazione == null || route.destinazione.length == 0) {
Toast.makeText(
context,
getString(R.string.route_towards_unknown, routeName), Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(
context,
getString(R.string.route_towards_destination, routeName, route.destinazione), Toast.LENGTH_SHORT
).show()
}
}
override fun requestShowingRoute(route: Route) {
showRoutesInLinesFragment(route)
}
}
private fun showRoutesInLinesFragment(route: Route) {
Log.d(
DEBUG_TAG, """Need to show line for route: gtfsID ${route.gtfsId} name ${route.name}"""
)
if (route.gtfsId != null) {
mListener.openLineFromStop(route.gtfsId, stopID)
} else {
val gtfsID = FiveTNormalizer.getGtfsRouteID(route)
Log.d(DEBUG_TAG, "GtfsID for route is: $gtfsID")
mListener.openLineFromStop(gtfsID, stopID)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
stopID = requireArguments().getString(KEY_STOP_ID) ?: ""
DEBUG_TAG = DEBUG_TAG_ALL + " " + stopID
arrivalsViewModel.setStopId(stopID)
//this might really be null
stopName = requireArguments().getString(KEY_STOP_NAME)
val arrivalsFragment = this
listener = object : OnDBUpdateStatusChangeListener {
override fun onDBStatusChanged(updating: Boolean) {
if (!updating) {
loaderManager.restartLoader(
loaderFavId,
arguments, arrivalsFragment
)
} else {
val lm = loaderManager
lm.destroyLoader(loaderFavId)
lm.destroyLoader(loaderStopId)
}
}
override fun defaultStatusValue(): Boolean {
return true
}
}
prefs = DBStatusManager(requireContext().applicationContext, listener)
justCreated = true
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_arrivals, container, false)
messageTextView = root.findViewById(R.id.messageTextView)
preMessageTextView = root.findViewById(R.id.arrivalsTextView)
addToFavorites = root.findViewById(R.id.addToFavorites)
openInMapButton = root.findViewById(R.id.openInMapButton)
// "How does it work part"
howDoesItWorkTextView = root.findViewById(R.id.howDoesItWorkTextView)
hideHintButton = root.findViewById(R.id.hideHintButton)
//TODO: Hide this layout at the beginning, show it later
resultsLayout = root.findViewById(R.id.resultsLayout)
loadingMessageTextView = root.findViewById(R.id.loadingMessageTextView)
progressBar = root.findViewById(R.id.circularProgressBar)
alertsCardView = root.findViewById(R.id.alertsCardView)
hideHintButton.setOnClickListener { v: View? -> this.onHideHint(v) }
//theScrollView = root.findViewById(R.id.arrivalsScrollView);
// recyclerview holding the arrival times
arrivalsRecyclerView = root.findViewById(R.id.arrivalsRecyclerView)
val manager = LinearLayoutManager(context)
arrivalsRecyclerView.setLayoutManager(manager)
val mDividerItemDecoration = DividerItemDecoration(
arrivalsRecyclerView.context,
manager.orientation
)
arrivalsRecyclerView.addItemDecoration(mDividerItemDecoration)
arrivalsSourceTextView = root.findViewById(R.id.timesSourceTextView)
arrivalsSourceTextView.setOnLongClickListener { view: View? ->
if (!fetchersChangeRequestPending) {
rotateFetchers()
//Show we are changing provider
arrivalsSourceTextView.setText(R.string.arrival_source_changing)
requestArrivalsForTheFragment()
fetchersChangeRequestPending = true
return@setOnLongClickListener true
}
false
}
arrivalsSourceTextView.setOnClickListener(View.OnClickListener { view: View? ->
Toast.makeText(
context, R.string.change_arrivals_source_message, Toast.LENGTH_SHORT
)
.show()
})
//Button
addToFavorites.setClickable(true)
addToFavorites.setOnClickListener(View.OnClickListener { v: View? ->
// add/remove the stop in the favorites
toggleStopFavorites()
})
val displayName = requireArguments().getString(STOP_TITLE)
if (displayName != null) setTextViewMessage(
String.format(
getString(R.string.passages_fill), displayName
)
)
val probablemessage = requireArguments().getString(MESSAGE_TEXT_VIEW)
if (probablemessage != null) {
//Log.d("BusTO fragment " + this.getTag(), "We have a possible message here in the savedInstaceState: " + probablemessage);
messageTextView.setText(probablemessage)
messageTextView.setVisibility(View.VISIBLE)
}
//no arrivals stuff
noArrivalsRecyclerView = root.findViewById(R.id.noArrivalsRecyclerView)
/*layoutManager = GridLayoutManager(context, 60)
layoutManager!!.spanSizeLookup = object : SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
return 12
}
}
*/
noArrivalsRecyclerView.setLayoutManager(getFlexLayoutManager(requireContext()))
noArrivalsTitleView = root.findViewById(R.id.noArrivalsMessageTextView)
//canaryEndView = root.findViewById(R.id.canaryEndView);
/*String sourcesTextViewData = getArguments().getString(SOURCES_TEXT);
if (sourcesTextViewData!=null){
timesSourceTextView.setText(sourcesTextViewData);
}*/
//need to do this when we recreate the fragment but we haven't updated the arrival times
val tentPalina = arrivalsViewModel.palinaToShow.value
if(lastUpdatedPalina == null && tentPalina != null) {
//this updates lastUpdatedPalina and also shows the arrival source
updateFragmentData(tentPalina)
}
//lastUpdatedPalina?.let { showArrivalsSources(it) }
return root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arrivalsViewModel.arrivalsRequestRunningLiveData.observe(viewLifecycleOwner, { running ->
//UI CHANGES TO APPLY WHEN THE REQUEST IS RUNNING
mListener.toggleSpinner(running)
if(running){
//different way of setting this flag
if(lastUpdatedPalina == null || lastUpdatedPalina?.totalNumberOfPassages==0) {
showLoadingMessageForFirstTime()
}
} else{
//stopped running, we can show the palina
//val uname = lastUpdatedPalina?.stopDisplayName
if (lastUpdatedPalina == null || lastUpdatedPalina?.numRoutesWithArrivals == 0) {
//no passages and result is not valid
setUIForNoStopFound()
}
}
})
arrivalsViewModel.palinaToShow.observe(viewLifecycleOwner){
Log.d(DEBUG_TAG, "New result palina observed, has coords: ${it.hasCoords()}, title ${it?.stopDisplayName}, number of passages: ${it.totalNumberOfPassages}")
val palinaIsValid = it!=null && (it.totalNumberOfPassages>0 || it.stopDisplayName!=null)
if (palinaIsValid){
updateFragmentData(it)
}
if(arrivalsViewModel.arrivalsRequestRunningLiveData.value ==false) {
//finished loading
if (palinaIsValid) {
//the result is true
hideLoadingMessageAndShowResults()
} else {
setUIForNoStopFound()
}
}
}
// this is only for the progress
arrivalsViewModel.sourcesLiveData.observe(viewLifecycleOwner){
Log.d(DEBUG_TAG, "Using arrivals source: $it")
val srcString = getDisplayArrivalsSource(it,requireContext())
loadingMessageTextView.text = getString(R.string.searching_arrivals_fmt, srcString)
}
arrivalsViewModel.resultLiveData.observe(viewLifecycleOwner){res ->
val src = arrivalsViewModel.sourcesLiveData.value
when (res) {
Fetcher.Result.OK -> {}
Fetcher.Result.CLIENT_OFFLINE -> showFetcherMessage(R.string.network_error, src)
Fetcher.Result.SERVER_ERROR -> {
if (utils.isConnected(context)) {
showFetcherMessage(R.string.parsing_error, src)
} else {
showFetcherMessage(R.string.network_error, src)
}
showFetcherMessage(R.string.internal_error,src)
}
Fetcher.Result.PARSER_ERROR -> showFetcherMessage(R.string.internal_error, src)
Fetcher.Result.QUERY_TOO_SHORT -> showFetcherMessage(R.string.query_too_short, src)
Fetcher.Result.EMPTY_RESULT_SET -> showFetcherMessage(R.string.no_arrivals_stop, src)
Fetcher.Result.NOT_FOUND -> showFetcherMessage(R.string.no_bus_stop_have_this_name, src)
else -> showFetcherMessage(R.string.internal_error, src)
}
}
arrivalsViewModel.stopInFavorites.observe(viewLifecycleOwner, { isFavorite ->
updateStarIcon(isFavorite)
})
alertsViewModel.alertsByStopLiveData.observe(viewLifecycleOwner) { alerts ->
if(alerts!=null && alerts.isNotEmpty()){
alertsCardView.visibility = View.VISIBLE
alertsCardView.setOnClickListener {
AlertsDialogFragment.newInstanceForStop(stopID).show(parentFragmentManager, "AlertsDialogStop$stopID")
}
} else{
alertsCardView.visibility = View.GONE
}
}
}
private fun showShortToast(id: Int) = showToastMessage(id,true)
private fun showFetcherMessage(id: Int, source: Source?){
val srcString = source?.let{ getDisplayArrivalsSource(it,requireContext())}
if (srcString!=null){
Toast.makeText(requireContext(), id, Toast.LENGTH_SHORT).show()
} else{
val message = getString(id)
Toast.makeText(requireContext(), "$srcString : $message", Toast.LENGTH_SHORT).show()
}
}
/*private fun changeUIFirstSearchActive(yes: Boolean){
if(yes){
resultsLayout.visibility = View.GONE
progressBar.visibility = View.VISIBLE
loadingMessageTextView.visibility = View.VISIBLE
} else{
resultsLayout.visibility = View.VISIBLE
progressBar.visibility = View.GONE
loadingMessageTextView.visibility = View.GONE
}
}
*/
private fun showLoadingMessageForFirstTime(){
resultsLayout.visibility = View.GONE
progressBar.visibility = View.VISIBLE
loadingMessageTextView.visibility = View.VISIBLE
}
private fun hideLoadingMessageAndShowResults(){
resultsLayout.visibility = View.VISIBLE
progressBar.visibility = View.GONE
loadingMessageTextView.visibility = View.GONE
}
private fun setUIForNoStopFound(){
progressBar.visibility=View.INVISIBLE
// Avoid showing this ugly message if we have found the stop, clearly it exists but GTT doesn't provide arrival times
if (stopName==null)
loadingMessageTextView.text = getString(R.string.no_bus_stop_have_this_name)
else
loadingMessageTextView.text = getString(R.string.no_arrivals_stop)
}
override fun onResume() {
super.onResume()
val loaderManager = loaderManager
Log.d(DEBUG_TAG, "OnResume, justCreated $justCreated, lastUpdatedPalina is: $lastUpdatedPalina")
mListener.readyGUIfor(FragmentKind.ARRIVALS)
//fix bug when the list adapter is null
mListAdapter?.let { resetListAdapter(it) }
if (noArrivalsAdapter != null) {
noArrivalsRecyclerView.adapter = noArrivalsAdapter
}
if (stopID.isNotEmpty()) {
if (!justCreated) {
fetchers = utils.getDefaultArrivalsFetchers(context)
adjustFetchersToSource()
if (reloadOnResume) requestArrivalsForTheFragment() //mListener.requestArrivalsForStopID(stopID)
} else {
//start first search
requestArrivalsForTheFragment()
showLoadingMessageForFirstTime()
justCreated = false
}
//start the loader
if (prefs!!.isDBUpdating(true)) {
prefs!!.registerListener()
} else {
Log.d(DEBUG_TAG, "Restarting loader for stop")
loaderManager.restartLoader(
loaderFavId,
arguments, this
)
}
updateMessage()
}
if (ScreenBaseFragment.getOption(requireContext(), OPTION_SHOW_LEGEND, true)) {
showHints()
}
}
override fun onStart() {
super.onStart()
if (needUpdateOnAttach) {
updateFragmentData(null)
needUpdateOnAttach = false
} else{
updateFragmentData(lastUpdatedPalina ?: Palina(stopID))
}
}
override fun onPause() {
if (listener != null) prefs!!.unregisterListener()
super.onPause()
val loaderManager = loaderManager
Log.d(DEBUG_TAG, "onPause, have running loaders: " + loaderManager.hasRunningLoaders())
loaderManager.destroyLoader(loaderFavId)
}
override fun onAttach(context: Context) {
super.onAttach(context)
//get fetchers
fetchers = utils.getDefaultArrivalsFetchers(context)
}
fun reloadsOnResume(): Boolean {
return reloadOnResume
}
fun setReloadOnResume(reloadOnResume: Boolean) {
this.reloadOnResume = reloadOnResume
}
// HINT "HOW TO USE"
private fun showHints() {
howDoesItWorkTextView.visibility = View.VISIBLE
hideHintButton.visibility = View.VISIBLE
//actionHelpMenuItem.setVisible(false);
}
private fun hideHints() {
howDoesItWorkTextView.visibility = View.GONE
hideHintButton.visibility = View.GONE
//actionHelpMenuItem.setVisible(true);
}
fun onHideHint(v: View?) {
hideHints()
setOption(requireContext(), OPTION_SHOW_LEGEND, false)
}
fun getCurrentFetchersAsArray(): Array<out ArrivalsFetcher?> {
val r= fetchers.toTypedArray()
//?: emptyArray<ArrivalsFetcher>()
return r
}
private fun rotateFetchers() {
Log.d(DEBUG_TAG, "Rotating fetchers, before: $fetchers")
fetchers?.let { Collections.rotate(it, -1) }
Log.d(DEBUG_TAG, "Rotating fetchers, afterwards: $fetchers")
}
/**
* Update the UI with the new data
* @param p the full Palina
*/
fun updateFragmentData(p: Palina?) {
if (p != null) {
lastUpdatedPalina = p
//set the gtfsID for the alerts
if(isAdded){
//alertsViewModel.setStopFilter(p)
} else{
Log.w(DEBUG_TAG, "Cannot filter alerts for palina $p, the fragment is not added")
}
}
if (!isAdded) {
//defer update at next show
if (p == null) Log.w(DEBUG_TAG, "Asked to update the data, but we're not attached and the data is null")
else needUpdateOnAttach = true
} else {
//set title
if(stopName==null && p?.stopDisplayName != null){
stopName = p.stopDisplayName
updateMessage()
}
val adapter = PalinaAdapter(context, lastUpdatedPalina, palinaClickListener, true)
p?.let {
//only update the sources if we have actual passaggi
if (arrivalsViewModel.arrivalsRequestRunningLiveData.value == false)
showArrivalsSources(lastUpdatedPalina!!)
}
resetListAdapter(adapter)
lastUpdatedPalina?.let{ pal ->
openInMapButton.setOnClickListener {
if (pal.hasCoords())
mListener.showMapCenteredOnStop(pal)
}
}
val routesWithNoPassages = lastUpdatedPalina!!.routesWithNoPassages
if (routesWithNoPassages.isEmpty()) {
//hide the views if there are no empty routes
noArrivalsRecyclerView.visibility = View.GONE
noArrivalsTitleView!!.visibility = View.GONE
} else {
val sorter = LinesNameSorter()
this.routesNoPassages = routesWithNoPassages.sortedWith{ r1, r2 -> sorter.compare(r1.displayCode, r2.displayCode) }
noArrivalsAdapter = RouteOnlyLineAdapter(routesNoPassages.map{r->r.displayCode}, ){ idx,_ ->
val route = routesNoPassages[idx]
showRoutesInLinesFragment(route)
}
noArrivalsRecyclerView.adapter = noArrivalsAdapter
noArrivalsRecyclerView.visibility = View.VISIBLE
noArrivalsTitleView!!.visibility = View.VISIBLE
}
//canaryEndView.setVisibility(View.VISIBLE);
//check if canaryEndView is visible
//boolean isCanaryVisibile = ViewUtils.Companion.isViewPartiallyVisibleInScroll(canaryEndView, theScrollView);
//Log.d(DEBUG_TAG, "Canary view fully visibile: "+isCanaryVisibile);
}
}
/**
* Set the message of the arrival times source
* @param p Palina with the arrival times
*/
protected fun showArrivalsSources(p: Palina) {
val source = p.passaggiSourceIfAny
val source_txt = getDisplayArrivalsSource(source, requireContext())
//
val updatedFetchers = adjustFetchersToSource(source)
if (!updatedFetchers) Log.w(DEBUG_TAG, "Tried to update the source fetcher but it didn't work")
val base_message = getString(R.string.times_source_fmt, source_txt)
arrivalsSourceTextView.text = base_message
arrivalsSourceTextView.visibility = View.VISIBLE
if (p.totalNumberOfPassages > 0) {
arrivalsSourceTextView.visibility = View.VISIBLE
} else {
arrivalsSourceTextView.visibility = View.INVISIBLE
}
fetchersChangeRequestPending = false
}
protected fun adjustFetchersToSource(source: Source?): Boolean {
if (source == null) return false
var count = 0
if (source != Source.UNDETERMINED) while (source != fetchers[0]!!.sourceForFetcher && count < 200) {
//we need to update the fetcher that is requested
rotateFetchers()
count++
}
return count < 200
}
protected fun adjustFetchersToSource(): Boolean {
if (lastUpdatedPalina == null) return false
val source = lastUpdatedPalina!!.passaggiSourceIfAny
return adjustFetchersToSource(source)
}
/**
* Update the stop title in the fragment
*/
private fun updateMessage() {
var message = ""
if (stopName != null && !stopName!!.isEmpty()) {
message = ("$stopID - $stopName")
} else if (stopID != null) {
message = stopID
} else {
Log.e("ArrivalsFragm$tag", "NO ID FOR THIS FRAGMENT - something went horribly wrong")
}
if (message.isNotEmpty()) {
//setTextViewMessage(getString(R.string.passages_fill, message))
setTextViewMessage(message)
}
}
/**
* Set the message textView
* @param message the whole message to write in the textView
*/
fun setTextViewMessage(message: String?) {
messageTextView.text = message
messageTextView.visibility = View.VISIBLE
}
-
+ //TODO: Remove all this loader stuff
override fun onCreateLoader(id: Int, p1: Bundle?): Loader<Cursor> {
val args = arguments
//if (args?.getString(KEY_STOP_ID) == null) throw
val stopID = args?.getString(KEY_STOP_ID) ?: ""
val builder = AppDataProvider.getUriBuilderToComplete()
val cl: CursorLoader
when (id) {
loaderFavId -> {
builder.appendPath("favorites").appendPath(stopID)
cl = CursorLoader(requireContext(), builder.build(), UserDB.FAVORITES_COLUMNS_ARRAY, null, null, null)
}
loaderStopId -> {
builder.appendPath("stop").appendPath(stopID)
cl = CursorLoader(
requireContext(), builder.build(), arrayOf(NextGenDB.Contract.StopsTable.COL_NAME),
null, null, null
)
}
else -> {
cl = CursorLoader(requireContext(), builder.build(), null, null,null,null)
Log.d(DEBUG_TAG, "This is probably going to crash")
}
}
cl.setUpdateThrottle(500)
return cl
}
override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor) {
/*
when (loader.id) {
loaderFavId -> {
val colUserName = data.getColumnIndex(UserDB.FAVORITES_COLUMNS_ARRAY[1])
if (data.count > 0) {
// IT'S IN FAVORITES
data.moveToFirst()
val probableName = data.getString(colUserName)
stopIsInFavorites = true
if (probableName != null && !probableName.isEmpty()) stopName = probableName //set the stop
//update the message in the textview
updateMessage()
} else {
stopIsInFavorites = false
}
updateStarIcon()
if (stopName == null) {
//stop is not inside the favorites and wasn't provided
Log.d("ArrivalsFragment$tag", "Stop wasn't in the favorites and has no name, looking in the DB")
loaderManager.restartLoader(
loaderStopId,
arguments, this
)
}
}
loaderStopId -> if (data.count > 0) {
data.moveToFirst()
val index = data.getColumnIndex(
NextGenDB.Contract.StopsTable.COL_NAME
)
if (index == -1) {
Log.e(DEBUG_TAG, "Index is -1, column not present. App may explode now...")
}
stopName = data.getString(index)
updateMessage()
} else {
Log.w("ArrivalsFragment$tag", "Stop is not inside the database... CLOISTER BELL")
}
}
*/
}
override fun onLoaderReset(loader: Loader<Cursor>) {
//NOTHING TO DO
}
protected fun resetListAdapter(adapter: PalinaAdapter) {
mListAdapter = adapter
arrivalsRecyclerView.adapter = adapter
arrivalsRecyclerView.visibility = View.VISIBLE
}
fun toggleStopFavorites() {
val stop: Stop? = lastUpdatedPalina
if (stop != null) {
// toggle the status in background
CoroutineFavoriteAction(requireContext().applicationContext, CoroutineFavoriteAction.Action.TOGGLE){
}.execute(stop)
} else {
// this case have no sense, but just immediately update the favorite icon
//updateStarIconFromLastBusStop(true)
Log.d(DEBUG_TAG, "Stop is null!")
}
}
/*
/**
* Update the star "Add to favorite" icon
*/
fun updateStarIconFromLastBusStop(toggleDone: Boolean) {
stopIsInFavorites = if (stopIsInFavorites) !toggleDone
else toggleDone
updateStarIcon()
}
*/
/**
* Update the star icon according to `stopIsInFavorites`
*/
fun updateStarIcon(stopIsInFavorites: Boolean) {
// no favorites no party!
// check if there is a last Stop
if (stopID.isEmpty()) {
addToFavorites.visibility = View.INVISIBLE
} else {
// filled or outline?
if (stopIsInFavorites) {
addToFavorites.setImageResource(R.drawable.ic_star_filled)
} else {
addToFavorites.setImageResource(R.drawable.ic_star_outline)
}
addToFavorites.visibility = View.VISIBLE
}
}
override fun onDestroyView() {
//arrivalsRecyclerView = null
if (arguments != null) {
requireArguments().putString(SOURCES_TEXT, arrivalsSourceTextView.text.toString())
requireArguments().putString(MESSAGE_TEXT_VIEW, messageTextView.text.toString())
}
super.onDestroyView()
}
override fun getBaseViewForSnackBar(): View? {
return null
}
fun isFragmentForTheSameStop(stopID: String) : Boolean{
return if (tag != null) tag == getFragmentTag(stopID)
else false
}
fun isFragmentForTheSameStop(p: Palina): Boolean {
return isFragmentForTheSameStop(p.ID)
}
/**
* Request arrivals in the fragment
*/
fun requestArrivalsForTheFragment(){
// Run with previous fetchers
context?.let {
mListener.toggleSpinner(true)
val fetcherSources = fetchers.map { f-> f?.sourceForFetcher?.name ?: "" }
//val workRequest = ArrivalsWorker.buildWorkRequest(stopID, fetcherSources.toTypedArray())
//val workManager = WorkManager.getInstance(it)
//workManager.enqueueUniqueWork(getArrivalsWorkID(stopID), ExistingWorkPolicy.REPLACE, workRequest)
arrivalsViewModel.requestArrivalsForStop(stopID,fetcherSources.toTypedArray())
//prepareGUIForArrivals();
//new AsyncArrivalsSearcher(fragmentHelper,fetchers, getContext()).execute(ID);
Log.d(DEBUG_TAG, "Started search for arrivals of stop $stopID")
}
}
companion object {
private const val OPTION_SHOW_LEGEND = "show_legend"
private const val KEY_STOP_ID = "stopid"
private const val KEY_STOP_NAME = "stopname"
private const val DEBUG_TAG_ALL = "BUSTOArrivalsFragment"
private const val loaderFavId = 2
private const val loaderStopId = 1
const val STOP_TITLE: String = "messageExtra"
private const val SOURCES_TEXT = "sources_textview_message"
@JvmStatic
@JvmOverloads
fun newInstance(stopID: String, stopName: String? = null): ArrivalsFragment {
val fragment = ArrivalsFragment()
val args = Bundle()
args.putString(KEY_STOP_ID, stopID)
//parameter for ResultListFragmentrequestArrivalsForStopID
//args.putSerializable(LIST_TYPE,FragmentKind.ARRIVALS);
if (stopName != null) {
args.putString(KEY_STOP_NAME, stopName)
}
fragment.arguments = args
return fragment
}
//return "palina_" + p.ID
@JvmStatic
fun getFragmentTag(stopID: String) = "palina_$stopID"
@JvmStatic
fun getFragmentTag(p: Palina) = getFragmentTag(p.ID)
@JvmStatic
fun getArrivalsWorkID(stopID: String) = "arrivals_search_$stopID"
@JvmStatic
fun getDisplayArrivalsSource(source: Source, context: Context): String{
return when (source) {
Source.GTTJSON -> context.getString(R.string.gttjsonfetcher)
Source.FiveTAPI -> context.getString(R.string.fivetapifetcher)
Source.FiveTScraper -> context.getString(R.string.fivetscraper)
Source.MatoAPI -> context.getString(R.string.source_mato)
Source.UNDETERMINED -> //Don't show the view
context.getString(R.string.undetermined_source)
}
}
}
}
diff --git a/app/src/main/java/it/reyboz/bustorino/fragments/GeneralMapLibreFragment.kt b/app/src/main/java/it/reyboz/bustorino/fragments/GeneralMapLibreFragment.kt
index 11e178b..6870aeb 100644
--- a/app/src/main/java/it/reyboz/bustorino/fragments/GeneralMapLibreFragment.kt
+++ b/app/src/main/java/it/reyboz/bustorino/fragments/GeneralMapLibreFragment.kt
@@ -1,1311 +1,1353 @@
/*
BusTO - Fragments components
Copyright (C) 2025 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 <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.fragments
import android.Manifest
import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.content.Context.LOCATION_SERVICE
import android.content.SharedPreferences
import android.content.res.ColorStateList
import android.graphics.Color
import android.location.Location
import android.location.LocationManager
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import android.widget.ImageButton
import android.widget.ImageView
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.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import androidx.core.view.ViewCompat
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.gson.JsonObject
import it.reyboz.bustorino.BuildConfig
import it.reyboz.bustorino.R
import it.reyboz.bustorino.backend.FiveTNormalizer
import it.reyboz.bustorino.backend.LivePositionTripPattern
import it.reyboz.bustorino.backend.LivePositionsServiceStatus
import it.reyboz.bustorino.backend.Stop
import it.reyboz.bustorino.backend.VehicleClassInfo
import it.reyboz.bustorino.backend.VehicleUtils
import it.reyboz.bustorino.backend.gtfs.GtfsUtils
import it.reyboz.bustorino.backend.gtfs.LivePositionUpdate
import it.reyboz.bustorino.backend.utils
import it.reyboz.bustorino.data.PreferencesHolder
import it.reyboz.bustorino.data.gtfs.TripAndPatternWithStops
import it.reyboz.bustorino.map.MapLibreLocationEngine
+import it.reyboz.bustorino.map.MapLibreStyles
import it.reyboz.bustorino.map.MapLibreUtils
import it.reyboz.bustorino.middleware.FusedNativeLocationProvider
-import it.reyboz.bustorino.util.Permissions
+import it.reyboz.bustorino.util.PermissionsHelper
import it.reyboz.bustorino.util.ViewUtils
import it.reyboz.bustorino.viewmodels.LivePositionsViewModel
import it.reyboz.bustorino.viewmodels.MapStateViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
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.location.LocationComponent
import org.maplibre.android.location.LocationComponentActivationOptions
import org.maplibre.android.location.engine.LocationEngineCallback
import org.maplibre.android.location.engine.LocationEngineRequest
import org.maplibre.android.location.engine.LocationEngineResult
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.ICON_ANCHOR_CENTER
import org.maplibre.android.style.layers.Property.ICON_ROTATION_ALIGNMENT_MAP
import org.maplibre.android.style.layers.Property.TEXT_ANCHOR_CENTER
import org.maplibre.android.style.layers.Property.TEXT_ROTATION_ALIGNMENT_VIEWPORT
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
import kotlin.math.absoluteValue
import kotlin.time.Duration.Companion.milliseconds
abstract class GeneralMapLibreFragment: ScreenBaseFragment(), OnMapReadyCallback {
protected var map: MapLibreMap? = null
/**
* Stop to show in Bottom Sheet, if it is null, no stop is shown
*/
protected var shownStopInBottomSheet : Stop? = null
protected var fragmentListener: CommonFragmentListener? = null
// Declare a variable for MapView
protected var mapView: MapView? = null
protected lateinit var mapStyle: Style
protected lateinit var stopsSource: GeoJsonSource
protected lateinit var busesSource: GeoJsonSource
protected lateinit var selectedStopSource: GeoJsonSource
protected lateinit var selectedBusSource: GeoJsonSource //= GeoJsonSource(SEL_BUS_SOURCE)
protected lateinit var sharedPreferences: SharedPreferences
protected lateinit var bottomSheetBehavior: BottomSheetBehavior<ConstraintLayout>
protected var locationEngine: MapLibreLocationEngine? = null
protected var locationProvider: FusedNativeLocationProvider? = null
protected var shownToastNoPosition = false
protected var locationEnabledOnDevice = true
protected var busLayerStarted = false
//TODO ACTIVATE THIS
private val preferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener(){ pref, key ->
/*when(key){
SettingsFragment.LIBREMAP_STYLE_PREF_KEY -> reloadMap()
}
*/
if(key == SettingsFragment.LIBREMAP_STYLE_PREF_KEY){
Log.d(DEBUG_TAG,"ASKING RELOAD OF MAP")
//reloadMap()
}
}
/**
* What to do when requesting the permission, when it's ok, initialize the map location component
*/
protected val positionRequestResponder = registerForActivityResult(
ActivityResultContracts.RequestMultiplePermissions(), ActivityResultCallback{ res ->
if(!(res.containsKey(PERM_LOC_COARSE)&&res.containsKey(PERM_LOC_FINE))){
Log.e(DEBUG_TAG, "Location request does not have the correct keys")
} else if(res[PERM_LOC_COARSE]!! && res[PERM_LOC_FINE]!!){
//permission OK, init map location
val mMap = map
if(mMap == null){
Log.w(DEBUG_TAG, "Location request completed, but map is null!")
}else{
- initializeMapLocationComponent(mMap,requireContext(), null)
+ initializeMapLocationComponent(mMap,requireContext(), mMap.style!!)
}
} else{
// PERMISSION DENIED
// TODO find better way to show the necessity of the permission
if(shouldShowRequestPermissionRationale(PERM_LOC_FINE))
Toast.makeText(requireContext(),
R.string.enable_position_message_map, Toast.LENGTH_SHORT).show()
}
}
)
//Bottom sheet behavior in GeneralMapLibreFragment
protected var bottomLayout: ConstraintLayout? = null
protected lateinit var stopTitleTextView: TextView
protected lateinit var stopNumberTextView: TextView
protected lateinit var linesPassingTextView: TextView
protected lateinit var extraBottomTextView: TextView
protected lateinit var linesBottomTextView: TextView
protected lateinit var arrivalsCard: CardView
protected lateinit var directionsCard: CardView
protected lateinit var bottomrightImage: ImageView
- protected lateinit var locationComponent: LocationComponent
+ protected var locationComponent: LocationComponent? = null
protected lateinit var busPositionsIconButton: ImageButton
protected lateinit var vehicleIcon: ImageView
protected lateinit var warningTripIcon: ImageView
private lateinit var loadingTripIcon: ImageView
protected lateinit var centerBottomImage: ImageView
protected var lastLocation : Location? = null
private var lastMapStyle =""
//BUS POSITIONS
protected val updatesByVehDict = HashMap<String, LivePositionTripPattern>(5)
protected val animatorsByVeh = HashMap<String, ValueAnimator>()
/**
* Label of the vehicle to show in Bottom Sheet, if it is null, no vehicle is shown
*/
protected var vehShowing: String? = null
protected var lastUpdateTime:Long = -2
protected var jobUpdate: Job? = null
//private val lifecycleOwnerLiveData = viewLifecycleOwnerLiveData
//extra items to use the LibreMap
protected var symbolManager : SymbolManager? = null
protected var stopActiveSymbol: Symbol? = null
protected var stopsLayerStarted = false
protected val livePositionsViewModel : LivePositionsViewModel by activityViewModels()
//private lateinit var symbolManager: SymbolManager
protected val mapStateViewModel: MapStateViewModel by viewModels()
protected var locationInitialized = false
protected var mapInitialized = false
protected var receivedFirstLocation = false
//location callback to decide if to zoom to the user position
@SuppressLint("MissingPermission")
protected val mapLibreLocationCallback = object : LocationEngineCallback<LocationEngineResult> {
override fun onSuccess(result: LocationEngineResult) {
val location: Location? = result.lastLocation
Log.d(DEBUG_TAG, "Received location $location")
location?.let {
//check timing of the location
val currentTime = System.currentTimeMillis()
val discard = (currentTime - it.time) > 90 * 1000.0 // discard if it is Older than 60 seconds
if(!discard) {
if (!receivedFirstLocation) {
onFirstReceivedLocation(it)
}
receivedFirstLocation = true
}
}
if(receivedFirstLocation){
//remove this listener once we have received the location
locationEngine?.removeLocationUpdates(this)
}
}
override fun onFailure(exception: Exception) {
Log.e(DEBUG_TAG, "Error in getting position: ${exception.message}")
}
}
protected val deviceLocationStatusListener = FusedNativeLocationProvider.LocationStatusListener { isEnabled ->
mapStateViewModel.locationDeviceEnabled.value = isEnabled
if(locationEnabledOnDevice && !isEnabled && locationInitialized) {
warnLocationNotEnabledOnDevice()
//setMapLocationEnabled(false)
}
locationEnabledOnDevice = isEnabled
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//sharedPreferences = PreferenceManager.getDefaultSharedPreferences(requireContext())
lastMapStyle = PreferencesHolder.getMapLibreStyleFile(requireContext())
//init map
MapLibre.getInstance(requireContext())
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
//TODO: Re-create map when this preference changes
lastMapStyle = PreferencesHolder.getMapLibreStyleFile(requireContext())
Log.d(DEBUG_TAG, "onCreateView lastMapStyle: $lastMapStyle")
return super.onCreateView(inflater, container, savedInstanceState)
}
protected fun initBottomSheet(view: View){
val bottomSheet = view.findViewById<ConstraintLayout>(R.id.bottom_sheet)
bottomLayout = bottomSheet
stopTitleTextView = view.findViewById(R.id.stopTitleTextView)
stopNumberTextView = view.findViewById(R.id.stopNumberTextView)
linesPassingTextView = view.findViewById(R.id.descriptionTextView)
arrivalsCard = view.findViewById(R.id.arrivalsCardButton)
directionsCard = view.findViewById(R.id.directionsCardButton)
vehicleIcon = view.findViewById(R.id.vehicleIcon)
loadingTripIcon = view.findViewById(R.id.downloadingIcon)
warningTripIcon = view.findViewById(R.id.warningIconTrip)
linesBottomTextView = view.findViewById(R.id.linesBottomTextView)
linesBottomTextView.text = getString(R.string.lines_fill, "")
bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet)
bottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN
centerBottomImage = view.findViewById(R.id.centerBottomLayoutImage)
centerBottomImage.setOnClickListener(){ centerOnOpenItemInBottomSheet() }
//set onclick listener for warning trip icon
warningTripIcon.setOnClickListener {
showToastMessage(R.string.no_trip_info_warning, true)
}
loadingTripIcon.setOnClickListener { showToastMessage(R.string.downloading_trip_info, true) }
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//init bottom sheet
initBottomSheet(view)
bottomrightImage = view.findViewById(R.id.rightmostImageView)
extraBottomTextView = view.findViewById(R.id.extraBottomTextView)
}
override fun onResume() {
super.onResume()
mapView?.onResume()
val newMapStyle = PreferencesHolder.getMapLibreStyleFile(requireContext())
Log.d(DEBUG_TAG, "onResume newMapStyle: $newMapStyle, lastMapStyle: $lastMapStyle")
// TODO: reload style if user changed preferences
//if(newMapStyle!=lastMapStyle){
// reloadMap()
//}
if(busLayerStarted)
updatePositionsIcons(false)
}
override fun onLowMemory() {
mapView?.onLowMemory()
super.onLowMemory()
}
override fun onStart() {
super.onStart()
mapView?.onStart()
}
override fun onDestroy() {
mapView?.onDestroy()
Log.d(DEBUG_TAG, "Destroyed mapView Fragment!!")
busLayerStarted = false
super.onDestroy()
}
override fun onStop() {
locationProvider?.removeListener(deviceLocationStatusListener)
mapView?.onStop()
super.onStop()
}
override fun onPause() {
jobUpdate?.cancel()
mapView?.onPause()
super.onPause()
}
override fun onDestroyView() {
bottomLayout = null
mapInitialized = false
locationInitialized = false
super.onDestroyView()
}
protected fun warnLocationNotEnabledOnDevice(){
context?.let{
Toast.makeText(it,R.string.enable_location_message,Toast.LENGTH_SHORT).show()
}
}
- protected fun reloadMap(){
- /*map?.let {
- Log.d("GeneralMapFragment", "RELOADING MAP")
- //save map state
- savedMapStateOnPause = saveMapStateInBundle()
-
- onMapDestroy()
- //Destroy and recreate MAP
- mapView.onDestroy()
- mapView.onCreate(null)
- mapView.getMapAsync(this)
+ override fun onMapReady(mapReady: MapLibreMap) {
+ this.map = mapReady
+ val context = requireContext()
+
+ // 1. Caricamento Stile (Comune)
+ val mjson = MapLibreStyles.getJsonStyleFromAsset(context, PreferencesHolder.getMapLibreStyleFile(context))
+ val builder = Style.Builder().fromJson(mjson!!)
+
+ mapReady.setStyle(builder) { style ->
+ mapStyle = style
+ addImagesStyle(style)
+
+ // Gancio per layer e configurazioni specifiche dello stile
+ onStyleLoaded(mapReady, style)
+
+ checkInitMapLocation(mapReady, style, context)
}
- */
+ // 2. Setup Listeners (Comune + Specifici)
+ setupMapListenersOnInit(mapReady)
+
+ // 4. Ripristino Camera / observe Buses
+
+ mapInitialized = true
+ mapStateViewModel.mapInitOnce.set(true)
+
+ onMapLibreInitialized(mapReady)
+
}
+ // --- Methods to implement in subclasses ---
+ /**
+ * Called when the map is loaded and the style is ready
+ */
+ abstract fun onStyleLoaded(mapReady: MapLibreMap,style: Style)
+
+ /**
+ * Called during the init setup of the map, separate method to add listeners to the map
+ */
+ abstract fun setupMapListenersOnInit(mapReady: MapLibreMap)
+
+ /**
+ * All things to do on the map different from listeners: listen to bus stops, bus positions updates...
+ */
+ abstract fun onMapLibreInitialized(mapReady: MapLibreMap)
+
//For extra stuff to do when the map is destroyed
abstract fun onMapDestroy()
override fun onAttach(context: Context) {
super.onAttach(context)
if(context is CommonFragmentListener){
fragmentListener = context
} else throw RuntimeException("$context must implement CommonFragmentListener")
}
protected fun stopToGeoJsonFeature(s: Stop): Feature{
return Feature.fromGeometry(
Point.fromLngLat(s.longitude!!, s.latitude!!),
JsonObject().apply {
addProperty("id", s.ID)
addProperty("name", s.stopDefaultName)
//addProperty("routes", s.routesThatStopHereToString()) // Add routes array to JSON object
}
)
}
protected fun isPointInsideVisibleRegion(p: LatLng, other: Boolean): Boolean{
val bounds = map?.projection?.visibleRegion?.latLngBounds
var inside = other
bounds?.let { inside = it.contains(p) }
return inside
}
protected fun isPointInsideVisibleRegion(lat: Double, lon: Double, other: Boolean): Boolean{
val p = LatLng(lat, lon)
return isPointInsideVisibleRegion(p, other)
}
protected fun removeVehiclesData(vehs: List<String>){
for(v in vehs){
if (updatesByVehDict.contains(v)) {
updatesByVehDict.remove(v)
if (animatorsByVeh.contains(v)){
animatorsByVeh[v]?.cancel()
animatorsByVeh.remove(v)
}
}
if (vehShowing==v){
hideStopOrBusBottomSheet()
}
}
}
// Hide the bottom sheet and remove extra symbol
protected open fun hideStopOrBusBottomSheet(){
if (stopActiveSymbol!=null){
symbolManager?.delete(stopActiveSymbol)
stopActiveSymbol = null
}
if(!showOpenStopWithSymbolLayer()){
selectedStopSource.setGeoJson(FeatureCollection.fromFeatures(ArrayList<Feature>()))
}
bottomSheetBehavior.state = BottomSheetBehavior.STATE_HIDDEN
//isBottomSheetShowing = false
//reset states
shownStopInBottomSheet = null
if (vehShowing!=null){
//we are hiding a vehicle
vehShowing = null
updatePositionsIcons(true)
}
extraBottomTextView.visibility = View.GONE
}
protected fun initSymbolManager(mapReady: MapLibreMap , style: Style){
val sm = SymbolManager(mapView!!, mapReady, style)
sm.iconAllowOverlap = true
sm.textAllowOverlap = false
sm.addClickListener { _ ->
if (stopActiveSymbol != null) {
hideStopOrBusBottomSheet()
return@addClickListener true
} else
return@addClickListener false
}
symbolManager = sm
}
/**
* Change the icon indicating the status of the live Positions
*/
protected fun setBusPositionsIcon(enabled: Boolean, error: Boolean){
val ctx = requireContext()
if(!enabled)
busPositionsIconButton.setImageDrawable(ContextCompat.getDrawable(ctx, R.drawable.bus_pos_circle_inactive))
else if(error)
busPositionsIconButton.setImageDrawable(ContextCompat.getDrawable(ctx, R.drawable.bus_pos_circle_notworking))
else
busPositionsIconButton.setImageDrawable(ContextCompat.getDrawable(ctx, R.drawable.bus_pos_circle_active))
}
abstract fun onMapLocationComponentInitialized()
@SuppressLint("MissingPermission")
protected fun setLocationComponentEnabled(enabled: Boolean): Boolean{
var changed = false
map?.apply {
if(locationComponent.isLocationComponentEnabled !=enabled)
locationComponent.isLocationComponentEnabled= enabled
changed = true}
Log.d(DEBUG_TAG, "Asked to set location component enabled: $enabled, changed: $changed")
mapStateViewModel.locationUserActive.value = enabled
return changed
}
+ /**
+ * Method to be called to start all the location stuff related to the map
+ * ONLY WHEN YOU HAVE THE LOCATION PERMISSION
+ */
@SuppressLint("MissingPermission")
- protected fun initializeMapLocationComponent(map: MapLibreMap, context: Context, style: Style?){
- val mStyle = style ?: map.style
+ protected fun initializeMapLocationComponent(map: MapLibreMap, context: Context, style: Style){
if(locationInitialized){
Log.w(DEBUG_TAG, "trying to initialize Location Component, but it is already done")
return
}
- mStyle?.let{ style ->
- locationComponent = map.locationComponent
-
- val locProvider = FusedNativeLocationProvider(context)
- locProvider.addListener(deviceLocationStatusListener)
- locationEngine = MapLibreLocationEngine(locProvider)
- locationProvider = locProvider
- val options = LocationComponentActivationOptions.builder(context, style)
- .useDefaultLocationEngine(false)
- .locationEngine(locationEngine)
- .build()
- locationComponent.activateLocationComponent(options)
-
- if(BuildConfig.DEBUG) Log.d(DEBUG_TAG, "Initializing location, request initial position")
- startInitialPositionRequest()
-
- if(!locationEnabledOnDevice){
- warnLocationNotEnabledOnDevice()
- }else {
- setLocationComponentEnabled(true)
- }
- locationInitialized = true
- onMapLocationComponentInitialized()
+ locationComponent = map.locationComponent
+
+ val locProvider = FusedNativeLocationProvider(context)
+ locProvider.addListener(deviceLocationStatusListener)
+ locationEngine = MapLibreLocationEngine(locProvider)
+ locationProvider = locProvider
+ val options = LocationComponentActivationOptions.builder(context, style)
+ .useDefaultLocationEngine(false)
+ .locationEngine(locationEngine)
+ .build()
+ locationComponent!!.activateLocationComponent(options)
+
+ if(BuildConfig.DEBUG) Log.d(DEBUG_TAG, "Initializing location, request initial position")
+ startInitialPositionRequest()
+
+ if(!locationEnabledOnDevice){
+ warnLocationNotEnabledOnDevice()
+ }else {
+ setLocationComponentEnabled(true)
}
+ locationInitialized = true
+ onMapLocationComponentInitialized()
+
}
@SuppressLint("MissingPermission")
protected fun startInitialPositionRequest(){
locationEngine?.requestLocationUpdates(LocationEngineRequest.Builder(500).setDisplacement(20.0f).build(),
mapLibreLocationCallback, null)
}
protected fun stopInitialPositionRequest(){
locationEngine?.removeLocationUpdates(mapLibreLocationCallback)
}
protected fun showVehClassInfo(vehInfo: VehicleClassInfo){
val print = "${vehInfo.type.getName()}: ${vehInfo.name}"
makeToast(print)
}
/**
* Update function for the bus positions
* Takes the processed updates and saves them accordingly
* Unified version that works with both fragments
*
* @param incomingData Map of updates with optional trip and pattern information
* @param hasVehicleTracking If true, checks if vehShowing is updated and calls callback (default: true)
* @param trackVehicleCallback Optional callback to show vehicle details when vehShowing is updated
*/
protected fun updateBusPositionsInMap(
incomingData: HashMap<String, Pair<LivePositionUpdate,TripAndPatternWithStops?>>,
hasVehicleTracking: Boolean = true,
trackVehicleCallback: ((String) -> Unit)? = null
) {
//TODO: Eventually change this (incomingData should be keyed by vehicle)
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
var createdVehs = 0
for (upsWithTrp in incomingData.values) {
val newPos = upsWithTrp.first
val patternStops = upsWithTrp.second
val vehID = newPos.vehicle
// Validate coordinates
if (!vehsOld.contains(vehID)) {
if (newPos.latitude <= 0 || newPos.longitude <= 0) {
Log.w(DEBUG_TAG, "Update ignored for veh $vehID on line ${newPos.routeID}, lat: ${newPos.latitude}, lon ${newPos.longitude}")
continue
}
}
if (vehsOld.contains(vehID)) {
// Changing the location of an existing bus
val oldPosData = updatesByVehDict[vehID]!!
val oldPos = oldPosData.posUpdate
val oldPattern = oldPosData.pattern
var avoidShowingUpdateBecauseIsImpossible = false
// Check for impossible route changes
if (oldPos.routeID != newPos.routeID) {
val dist = LatLng(oldPos.latitude, oldPos.longitude).distanceTo(
LatLng(newPos.latitude, newPos.longitude)
)
val speed = dist * 3.6 / (newPos.timestamp - oldPos.timestamp) // km/h
Log.w(DEBUG_TAG, "Vehicle $vehID changed route from ${oldPos.routeID} to ${newPos.routeID}, distance: $dist, speed: $speed")
if (speed > 120 || speed < 0) {
avoidShowingUpdateBecauseIsImpossible = true
}
}
if (avoidShowingUpdateBecauseIsImpossible) {
Log.w(DEBUG_TAG, "Update for vehicle $vehID skipped")
continue
}
// Check if position actually changed
val samePosition = (oldPos.latitude == newPos.latitude) &&
(oldPos.longitude == newPos.longitude)
val setPattern = (oldPattern == null) && (patternStops != null)
// Copy old bearing if new one is missing
if (newPos.bearing == null && oldPos.bearing != null) {
newPos.bearing = oldPos.bearing
}
if (!samePosition || setPattern) {
val newOrOldPosInBounds = isPointInsideVisibleRegion(
newPos.latitude, newPos.longitude, true
) || isPointInsideVisibleRegion(oldPos.latitude, oldPos.longitude, true)
if (newOrOldPosInBounds) {
// Update pattern data if available
patternStops?.let {
updatesByVehDict[vehID]!!.pattern = it.pattern
}
// Animate the position change
animateNewPositionMove(newPos)
} else {
// Update position without animation
updatesByVehDict[vehID] = LivePositionTripPattern(
newPos,
patternStops?.pattern
)
}
}
countUpds++
} else {
// New vehicle - create entry
updatesByVehDict[vehID] = LivePositionTripPattern(
newPos,
patternStops?.pattern
)
createdVehs++
}
// Update vehicle details if this is the shown/tracked vehicle
if (hasVehicleTracking && vehShowing?.isNotEmpty() == true && vehID == vehShowing) {
trackVehicleCallback?.invoke(vehID)
}
}
// Remove old positions
Log.d(DEBUG_TAG, "Updated $countUpds vehicles, created $createdVehs vehicles")
vehsOld.removeAll(vehsNew)
// Clean up stale vehicles (not updated for 2 minutes)
val currentTimeStamp = System.currentTimeMillis() / 1000
for (vehID in vehsOld) {
val posData = updatesByVehDict[vehID]!!
if (currentTimeStamp - posData.posUpdate.timestamp > 2 * 60) {
// Remove the bus
updatesByVehDict.remove(vehID)
// Cancel and remove animator if exists
animatorsByVeh[vehID]?.cancel()
animatorsByVeh.remove(vehID)
}
}
// Update UI
updatePositionsIcons(false)
}
/**
* Shared bottom sheet setup. The [onDirectionsClick] lambda is called when
* directionsCard is tapped; it receives the pattern code (empty string when
* no pattern is available) so each subclass can navigate as it sees fit.
*/
protected fun showVehicleTripInBottomSheet(
veh: String,
onDirectionsClick: (patternCode: String, veh: String) -> Unit
) {
val data = updatesByVehDict[veh] ?: run {
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), false
)
val pat = data.pattern
val update = data.posUpdate
if (pat != null) {
stopTitleTextView.text = pat.headsign
stopTitleTextView.visibility = View.VISIBLE
stopNumberTextView.text = getString(R.string.line_fill_towards, lineName)
loadingTripIcon.visibility = View.GONE
} else {
stopTitleTextView.visibility = View.GONE
stopNumberTextView.text = getString(R.string.line_fill, lineName)
loadingTripIcon.visibility = if (update.hasTripId()) View.VISIBLE else View.GONE
}
directionsCard.setOnClickListener {
onDirectionsClick(pat?.code ?: "", veh)
}
directionsCard.visibility = View.VISIBLE
bottomrightImage.setImageDrawable(
ResourcesCompat.getDrawable(resources, R.drawable.ic_magnifying_glass, activity?.theme)
)
// if you change this, remember to change the color of the vehicleIcon
val colorBlue = ResourcesCompat.getColor(resources, R.color.bus_marker_color_selected, activity?.theme)
ViewCompat.setBackgroundTintList(directionsCard, ColorStateList.valueOf(colorBlue))
linesPassingTextView.text = getString(R.string.vehicle_fill, data.posUpdate.vehicle)
linesPassingTextView.gravity = Gravity.CENTER_VERTICAL
linesBottomTextView.visibility = View.GONE
arrivalsCard.visibility = View.GONE
extraBottomTextView.text = getString(R.string.updated_fill, utils.unixTimestampToLocalTime(data.posUpdate.timestamp))
extraBottomTextView.visibility = View.VISIBLE
val vehInfo = VehicleUtils.getTypeForLabel(update.vehicle)
if(vehInfo == null){
vehicleIcon.visibility = View.GONE
linesPassingTextView.setOnClickListener { } //empty click listener
} else{
val ico = when(vehInfo.type){
VehicleUtils.VehicleType.BUS -> R.drawable.ic_bus
VehicleUtils.VehicleType.ELECTRIC_BUS -> R.drawable.ic_bus_electric_filled
VehicleUtils.VehicleType.TRAM -> R.drawable.ic_tram_material
}
vehicleIcon.setImageDrawable(ResourcesCompat.getDrawable(resources, ico, activity?.theme))
vehicleIcon.visibility = View.VISIBLE
vehicleIcon.setOnClickListener {
showVehClassInfo(vehInfo)
}
linesPassingTextView.setOnClickListener { showVehClassInfo(vehInfo) }
}
if (!update.hasTripId()){
warningTripIcon.visibility = View.VISIBLE
} else{
warningTripIcon.visibility = View.GONE
}
}
vehShowing = veh
bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
updatePositionsIcons(true)
Log.d(DEBUG_TAG, "Shown vehicle $veh in bottom sheet")
}
/**
* Update the bus positions displayed on the map, from the existing data
*
* @param forced If true, forces immediate update ignoring the 100ms throttle
*/
protected fun updatePositionsIcons(forced: Boolean) {
// Avoid frequent updates - throttle to max once per 60ms
val currentTime = System.currentTimeMillis()
val isStarted = (lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED))
if(forced){
// if we're running a forced update, cancel the pending one
jobUpdate?.apply{
cancel()
//Log.d(DEBUG_TAG, "Cancelled update")
}
}
else if (currentTime - lastUpdateTime < 100) {
// Schedule delayed update
if(viewLifecycleOwnerLiveData.value != null) {
jobUpdate?.cancel()
jobUpdate = viewLifecycleOwner.lifecycleScope.launch {
delay(100.milliseconds)
//Log.d(DEBUG_TAG, "Running update from delayed")
updatePositionsIcons(false)
}
//Log.d(DEBUG_TAG, "Cancelled previous job, delaying update")
}
return
}
if(!isStarted){
Log.w(DEBUG_TAG, "fragment is not started, ")
}
val busFeatures = ArrayList<Feature>()
val selectedBusFeatures = ArrayList<Feature>()
for (dat in updatesByVehDict.values) {
val pos = dat.posUpdate
val point = Point.fromLngLat(pos.longitude, pos.latitude)
val newFeature = 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'))
}
)
// Separate selected vehicle from others
if (vehShowing?.isNotEmpty() == true && vehShowing == dat.posUpdate.vehicle) {
selectedBusFeatures.add(newFeature)
//Log.d(DEBUG_TAG, "Update position for bus $vehShowing")
//TODO: Recenter the map on the vehicle
} else {
busFeatures.add(newFeature)
}
}
busesSource.setGeoJson(FeatureCollection.fromFeatures(busFeatures))
selectedBusSource.setGeoJson(FeatureCollection.fromFeatures(selectedBusFeatures))
lastUpdateTime = System.currentTimeMillis()
}
/**
* Animates the transition of a vehicle from its current position to a new position
* This is the tricky part - we need to set the new positions with the data and redraw them all
*
* @param positionUpdate The new position update to animate to
*/
protected fun animateNewPositionMove(positionUpdate: LivePositionUpdate) {
val vehID = positionUpdate.vehicle
// Check if vehicle exists in our tracking dictionary
if (vehID !in updatesByVehDict.keys) {
return
}
val currentUpdate = updatesByVehDict[vehID] ?: run {
Log.e(DEBUG_TAG, "Have to run animation for veh $vehID but not in the dict")
return
}
// Cancel any current animation for this vehicle
animatorsByVeh[vehID]?.cancel()
val posUp = currentUpdate.posUpdate
val currentPos = LatLng(posUp.latitude, posUp.longitude)
val newPos = LatLng(positionUpdate.latitude, positionUpdate.longitude)
// Create animator for smooth transition
val valueAnimator = ValueAnimator.ofObject(
MapLibreUtils.LatLngEvaluator(),
currentPos,
newPos
)
valueAnimator.addUpdateListener { animation ->
val latLng = animation.animatedValue as LatLng
// Update position during animation
updatesByVehDict[vehID]?.let { update ->
update.posUpdate.latitude = latLng.latitude
update.posUpdate.longitude = latLng.longitude
updatePositionsIcons(false)
} ?: run {
Log.w(DEBUG_TAG, "The bus position to animate has been removed, but the animator is still running!")
}
}
// Set the new position as current but keep old coordinates for animation start
positionUpdate.latitude = posUp.latitude
positionUpdate.longitude = posUp.longitude
updatesByVehDict[vehID]!!.posUpdate = positionUpdate
// Configure and start animation
valueAnimator.duration = 300
valueAnimator.interpolator = LinearInterpolator()
valueAnimator.start()
// Store animator for potential cancellation
animatorsByVeh[vehID] = valueAnimator
}
/// STOP OPENING
abstract fun showOpenStopWithSymbolLayer(): Boolean
/**
* Update the bottom sheet with the stop information
*/
protected fun openStopInBottomSheet(stop: Stop){
bottomLayout?.let {
//lay.findViewById<TextView>(R.id.stopTitleTextView).text ="${stop.ID} - ${stop.stopDefaultName}"
val stopName = stop.stopUserName ?: stop.stopDefaultName
stopTitleTextView.text = stopName//stop.stopDefaultName
stopNumberTextView.text = getString(R.string.stop_fill,stop.ID)
stopTitleTextView.visibility = View.VISIBLE
val string_show = if (stop.numRoutesStopping==0) ""
else stop.routesThatStopHereToString() //requireContext().getString(R.string.lines_fill, stop.routesThatStopHereToString())
linesPassingTextView.text = string_show
linesPassingTextView.visibility = View.VISIBLE
linesPassingTextView.setOnClickListener { } //empty click listener (needed when switching from vehicle)
linesPassingTextView.gravity = Gravity.TOP
linesBottomTextView.visibility =View.VISIBLE
//SET ON CLICK LISTENER
arrivalsCard.setOnClickListener{
fragmentListener?.requestArrivalsForStopID(stop.ID)
}
arrivalsCard.visibility = View.VISIBLE
directionsCard.visibility = View.VISIBLE
directionsCard.setOnClickListener {
ViewUtils.openStopInOutsideApp(stop, context)
}
context?.let {
val colorIcon = ViewUtils.getColorFromTheme(it, 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))
// icons for the vehicles
vehicleIcon.visibility = View.GONE
warningTripIcon.visibility = View.GONE
loadingTripIcon.visibility = View.GONE
}
//add stop marker
if (stop.latitude!=null && stop.longitude!=null) {
Log.d(DEBUG_TAG, "Showing stop: ${stop.ID}")
if (showOpenStopWithSymbolLayer()) {
stopActiveSymbol = symbolManager?.create(
SymbolOptions()
.withLatLng(LatLng(stop.latitude!!, stop.longitude!!))
.withIconImage(STOP_ACTIVE_IMG)
.withIconAnchor(ICON_ANCHOR_CENTER)
)
} else {
val list = ArrayList<Feature>()
list.add(stopToGeoJsonFeature(stop))
selectedStopSource.setGeoJson(
FeatureCollection.fromFeatures(list)
)
}
}
Log.d(DEBUG_TAG, "Shown stop $stop in bottom sheet")
shownStopInBottomSheet = stop
bottomSheetBehavior.state = BottomSheetBehavior.STATE_EXPANDED
}
protected fun stopAnimations(){
for(anim in animatorsByVeh.values){
anim.cancel()
}
}
protected fun addImagesStyle(style: Style){
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)!!)
style.addImage(BUS_IMAGE_ID,ResourcesCompat.getDrawable(resources, R.drawable.map_bus_position_icon, activity?.theme)!!)
style.addImage(BUS_SEL_IMAGE_ID, ResourcesCompat.getDrawable(resources, R.drawable.map_bus_position_icon_sel, activity?.theme)!!)
val polyIconArrow = ResourcesCompat.getDrawable(resources, R.drawable.arrow_up_box_fill, activity?.theme)!!
style.addImage(POLY_ARROW, polyIconArrow)
}
protected fun initStopsLayer(style: Style, stopsFeatures: FeatureCollection?){
//determine default layer
val layerAbove = if (lastMapStyle == MapLibreUtils.STYLE_OSM_RASTER){
"osm-raster"
} else// if (lastMapStyle == MapLibreUtils.STYLE_VERSATILES_ECLIPSE_JSON){
"symbol-transit-airfield"
/*} else {
//
"poi_park"
}
*/
initStopsLayer(style, stopsFeatures, layerAbove)
}
protected fun initStopsLayer(style: Style, stopsFeatures: FeatureCollection?, stopsLayerAbove: String){
stopsSource = GeoJsonSource(STOPS_SOURCE_ID,stopsFeatures ?: FeatureCollection.fromFeatures(ArrayList<Feature>()))
style.addSource(stopsSource)
// 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.addLayerAbove(stopsLayer, stopsLayerAbove ) //"label_country_1") this with OSM Bright
selectedStopSource = GeoJsonSource(SEL_STOP_SOURCE, FeatureCollection.fromFeatures(ArrayList<Feature>()))
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
*/
protected fun setupBusLayer(style: Style, withLabels: Boolean =false, busIconsScale: Float = 1.0f) {
// 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)!!)
selectedBusSource = GeoJsonSource(SEL_BUS_SOURCE)
style.addSource(selectedBusSource)
// Buses layer
val busesLayer = SymbolLayer(BUSES_LAYER_ID, BUSES_SOURCE_ID).apply {
withProperties(
PropertyFactory.iconImage(BUS_IMAGE_ID),
PropertyFactory.iconSize(busIconsScale),
PropertyFactory.iconAllowOverlap(true),
PropertyFactory.iconIgnorePlacement(true),
PropertyFactory.iconRotate(Expression.get("bearing")),
PropertyFactory.iconRotationAlignment(ICON_ROTATION_ALIGNMENT_MAP)
)
if (withLabels){
withProperties(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)
val selectedBusLayer = SymbolLayer(SEL_BUS_LAYER, SEL_BUS_SOURCE).apply {
withProperties(
PropertyFactory.iconImage(BUS_SEL_IMAGE_ID),
PropertyFactory.iconSize(busIconsScale),
PropertyFactory.iconAllowOverlap(true),
PropertyFactory.iconIgnorePlacement(true),
PropertyFactory.iconRotate(Expression.get("bearing")),
PropertyFactory.iconRotationAlignment(ICON_ROTATION_ALIGNMENT_MAP)
)
if (withLabels){
withProperties(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(selectedBusLayer, BUSES_LAYER_ID)
busLayerStarted = true
}
/**
* Method used for enabling / disabling the location from the buttons
*/
- protected fun switchUserLocationStatus(view: View?){
- val enabled = if(locationInitialized) locationComponent.isLocationComponentEnabled else false
+ protected fun switchUserLocationStatus(view: View?) {
+
+ val enabled = locationInitialized && (locationComponent?.isLocationComponentEnabled == true)
val context = context ?: return
- if(enabled) {
- if(!receivedFirstLocation){
+ if (enabled) {
+ if (!receivedFirstLocation) {
//use case: the user has decided to disable the location before the first position arrived
stopInitialPositionRequest()
}
// we have to disable it
setMapLocationEnabled(false)
- }
- else if(deviceHasLocationProvider()) {
- if(Permissions.bothLocationPermissionsGranted(context)){
- if(!locationEnabledOnDevice){
+ } else if (deviceHasLocationProvider()) {
+ if (PermissionsHelper.bothLocationPermissionsGranted(context)) {
+ if (!locationEnabledOnDevice) {
warnLocationNotEnabledOnDevice()
- } else{
+ } else {
setMapLocationEnabled(true)
}
- } else{
+ } else {
Log.d(DEBUG_TAG, "Requesting permissions to show location")
- Permissions.getInstance(context).checkRequestLocationPermissions(requireActivity(), positionRequestResponder)
+ PermissionsHelper.getInstance(context)
+ .checkRequestLocationPermissions(requireActivity(), positionRequestResponder)
}
- } else{
+ } else {
context.let {
Toast.makeText(it, R.string.no_gps_on_device, Toast.LENGTH_SHORT).show()
}
- //adjust ui
- setLocationIconEnabled(false)
- }
+ mapStateViewModel.locationUserActive.value = false
+ //adjust ui - done in response to the above
+ //setLocationIconEnabled(false)
+
+ }
}
/**
* Set the map location component enabled
*/
@SuppressLint("MissingPermission")
protected fun setMapLocationEnabled(enabled: Boolean){
Log.d(DEBUG_TAG, "Setting map location enabled: $enabled")
- map?.locationComponent?.isLocationComponentEnabled = enabled
- //map?.cameraPosition =
+ val locCompo = map?.locationComponent
+ if (locCompo!=null)
+ locCompo.isLocationComponentEnabled = enabled
+ else Log.w(DEBUG_TAG, "Asked to set location to $enabled but locationComponent is null")
+
mapStateViewModel.locationUserActive.value = enabled
onMapLocationEnabled(enabled)
}
/**
- * Function to run at the first time the fragment is opened
+ * Function to run at the first time the map is ready
* Check if we have the permissions, and then initialize the map location component
* If we don't have it, request the permission
*/
protected fun checkInitMapLocation(mapReady: MapLibreMap,style: Style, context: Context) {
//enable location
val hasGps = deviceHasLocationProvider()
- val permissions = Permissions.getInstance(context)
+ val permissionsHelper = PermissionsHelper.getInstance(context)
if(hasGps) {
- if (Permissions.bothLocationPermissionsGranted(context)) {
+ if (PermissionsHelper.bothLocationPermissionsGranted(context)) {
Log.d(DEBUG_TAG, "Have got the location permission, init location component")
initializeMapLocationComponent(mapReady, context, style)
}else {
var req = false
activity?.let{
- req = permissions.checkRequestLocationPermissions(it, positionRequestResponder)
+ req = permissionsHelper.checkRequestLocationPermissions(it, positionRequestResponder)
}
if(!req) {
setMapLocationEnabled(false)
}
}
+ } else{
+ mapStateViewModel.setLocationNotAvailable()
}
+
}
/**
* Set the UI elements showing that the user location is disabled
*/
abstract fun onMapLocationEnabled(active: Boolean)
/**
* Helper function to actually set the icon
*/
abstract fun setLocationIconEnabled(enabled: Boolean)
/**
* Called when we receive the first fix on the user location
*/
abstract fun onFirstReceivedLocation(location: Location)
protected fun isBottomSheetShowing(): Boolean {
return bottomSheetBehavior.state == BottomSheetBehavior.STATE_EXPANDED
}
protected fun deviceHasLocationProvider(): Boolean{
val locManager = requireContext().getSystemService(LOCATION_SERVICE) as LocationManager
return locManager.allProviders.isNotEmpty()
}
/**
* Update automatically the icon when the live position service changes status
*/
protected fun observeStatusLivePositions(){
livePositionsViewModel.serviceStatus.observe(viewLifecycleOwner){ status ->
//if service is active, update the bus positions icon
when(status) {
LivePositionsServiceStatus.OK ->
setBusPositionsIcon(true, error = false)
LivePositionsServiceStatus.NO_POSITIONS -> setBusPositionsIcon(true, error = true)
else -> setBusPositionsIcon( true, error = true)
}
}
}
protected fun showingBusStopOrVehicle(): Boolean{
return !(shownStopInBottomSheet == null && vehShowing == null)
}
/**
* Clear all buses from the map
*/
protected fun clearAllBusPositionsInMap(){
for ((k, anim) in animatorsByVeh){
anim.cancel()
}
animatorsByVeh.clear()
updatesByVehDict.clear()
updatePositionsIcons(forced = false)
}
protected fun setCameraPosition(latitude: Double, longitude: Double, zoom: Double) {
map?.cameraPosition = CameraPosition.Builder()
.target(LatLng(latitude, longitude))
.zoom(zoom)
.build()
}
protected fun showToastLocation(enabled: Boolean){
val textid = if (enabled) R.string.location_enabled else R.string.location_disabled
context?.let{
Toast.makeText(it,textid,Toast.LENGTH_SHORT).show()
}
}
protected fun centerOnOpenItemInBottomSheet(){
var latlng: LatLng? = null
var found = 0
if(shownStopInBottomSheet!=null){
val stop = shownStopInBottomSheet!!
latlng = LatLng(stop.latitude!!, stop.longitude!!)
found = 1
}else if(vehShowing!=null){
val update = updatesByVehDict.getOrDefault(vehShowing!!, null)
update?.let{
latlng = LatLng(it.posUpdate.latitude, it.posUpdate.longitude)
found = 2
}
}
if (latlng!=null) {
map?.apply{
//complicated part: make toast if the position is the same
//val newBbox = projection.visibleRegion.latLngBounds
val ll = cameraPosition.target
if(ll!=null && (ll.latitude - latlng.latitude).absoluteValue < 1e-4 && (ll.longitude-latlng.longitude).absoluteValue < 1e-4){
Toast.makeText(requireContext(),
if(found==1) R.string.already_center_bottom_sheet_stop else R.string.already_center_bottom_sheet_vehicle,
Toast.LENGTH_SHORT
).show()
} else {
animateCamera(
CameraUpdateFactory.newLatLng(latlng),
700
)
}
}
}else {
Log.d(DEBUG_TAG, "Asked to center on open thing in bottom sheet but no position found")
}
}
companion object{
private const val DEBUG_TAG="GeneralMapLibreFragment"
const val BUSES_SOURCE_ID = "buses-source"
const val BUSES_LAYER_ID = "buses-layer"
const val SEL_STOP_SOURCE="selected-stop-source"
const val SEL_STOP_LAYER = "selected-stop-layer"
const val SEL_BUS_SOURCE = "sel_bus_source"
const val SEL_BUS_LAYER = "sel_bus_layer"
const val KEY_LOCATION_ENABLED="location_enabled"
protected const val STOPS_SOURCE_ID = "stops-source"
protected const val STOPS_LAYER_ID = "stops-layer"
protected const val STOP_IMAGE_ID = "stop-img"
protected const val STOP_ACTIVE_IMG = "stop_active_img"
protected const val BUS_IMAGE_ID = "bus_symbol"
protected const val BUS_SEL_IMAGE_ID = "sel_bus_symbol"
protected const val POLYLINE_LAYER = "polyline-layer"
protected const val POLYLINE_SOURCE = "polyline-source"
protected const val POLY_ARROWS_LAYER = "arrows-layer"
protected const val POLY_ARROWS_SOURCE = "arrows-source"
protected const val POLY_ARROW ="poly-arrow-img"
private const val PERM_LOC_COARSE = Manifest.permission.ACCESS_COARSE_LOCATION
private const val PERM_LOC_FINE = Manifest.permission.ACCESS_FINE_LOCATION
//TODO: this is hardcoded, make it modifiable by the user
protected const val MAX_DIST_KM = 90.0
}
}
\ No newline at end of file
diff --git a/app/src/main/java/it/reyboz/bustorino/fragments/IntroFragment.kt b/app/src/main/java/it/reyboz/bustorino/fragments/IntroFragment.kt
index f3f4d61..1e69bf2 100644
--- a/app/src/main/java/it/reyboz/bustorino/fragments/IntroFragment.kt
+++ b/app/src/main/java/it/reyboz/bustorino/fragments/IntroFragment.kt
@@ -1,242 +1,241 @@
/*
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 <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.fragments
import android.content.Context
import android.graphics.*
import android.graphics.text.LineBreaker
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.content.ContextCompat
-import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.Fragment
import it.reyboz.bustorino.R
import it.reyboz.bustorino.backend.utils
-import it.reyboz.bustorino.util.Permissions
+import it.reyboz.bustorino.util.PermissionsHelper
import it.reyboz.bustorino.util.ViewUtils
import java.lang.IllegalStateException
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val SCREEN_INDEX = "screenindex"
class IntroFragment : Fragment() {
private var screenIndex = 1
private lateinit var imageHolder: ImageView
private lateinit var textView: TextView
private lateinit var listener: IntroListener
private lateinit var interactButton: Button
private val locationRequestResLauncher = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()){ res ->
//onActivityResult(res: map<String,Boolean>)
- if(res[Permissions.LOCATION_PERMISSIONS[0]] ==true || res[Permissions.LOCATION_PERMISSIONS[1]] ==true)
+ if(res[PermissionsHelper.LOCATION_PERMISSIONS[0]] ==true || res[PermissionsHelper.LOCATION_PERMISSIONS[1]] ==true)
setInteractButtonState(ButtonState.LOCATION,false)
}
private val notificationsReqLauncher = registerForActivityResult(ActivityResultContracts.RequestPermission()) {
if (it) setInteractButtonState(ButtonState.NOTIFICATIONS, false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
screenIndex = it.getInt(SCREEN_INDEX)
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
if(context !is IntroListener){
throw IllegalStateException("Context must implement IntroListener")
}
listener = context
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val root= inflater.inflate(R.layout.fragment_intro, container, false)
imageHolder = root.findViewById(R.id.image_tutorial)
textView = root.findViewById(R.id.tutorialTextView)
interactButton = root.findViewById(R.id.permissionButton)
when(screenIndex){
0 -> {
setImageBitmap(imageHolder, R.drawable.tuto_busto, 300f)
textView.text = utils.convertHtml(getString(R.string.tutorial_first))
}
1->{
setImageBitmap(imageHolder, R.drawable.tuto_search)
setTextHtmlDescription(R.string.tutorial_search)
}
2 ->{
setImageBitmap(imageHolder, R.drawable.tuto_arrivals)
textView.text = utils.convertHtml(getString(R.string.tutorial_arrivals))
}
3 ->{
setImageBitmap(imageHolder, R.drawable.tuto_stops)
textView.text = utils.convertHtml(getString(R.string.tutorial_stops))
}
4 ->{
setImageBitmap(imageHolder, R.drawable.tuto_map, 300f)
textView.text = utils.convertHtml(getString(R.string.tutorial_map))
if (Build.VERSION.SDK_INT >= 23) {
//only show if running on Android M or above
- val permGranted = (Permissions.anyLocationPermissionsGranted(requireContext()))
+ val permGranted = (PermissionsHelper.anyLocationPermissionsGranted(requireContext()))
setInteractButtonState(ButtonState.LOCATION, !permGranted)
interactButton.setOnClickListener {
//ask location permission
- Permissions.getInstance(requireContext()).checkRequestLocationPermissions(requireActivity(), locationRequestResLauncher)
+ PermissionsHelper.getInstance(requireContext()).checkRequestLocationPermissions(requireActivity(), locationRequestResLauncher)
//locationRequestResLauncher.launch(Permissions.LOCATION_PERMISSIONS)
}
interactButton.visibility = View.VISIBLE
}
}
5 ->{
setImageBitmap(imageHolder, R.drawable.tuto_line_det, 300f)
textView.text = utils.convertHtml(getString(R.string.tutorial_line))
}
6-> {
setImageBitmap(imageHolder,R.drawable.tuto_menu)
setTextHtmlDescription(R.string.tutorial_menu)
//this is the cheapest trick ever lol
- if(!Permissions.isNotificationPermissionNeeded()){
+ if(!PermissionsHelper.isNotificationPermissionNeeded()){
//no other screen needed
val button = root.findViewById<Button>(R.id.closeAllButton)
button.visibility = View.VISIBLE
button.setOnClickListener {
listener.closeIntroduction()
}
}
}
/// IMPORTANT: THIS NEEDS TO BE LAST SCREEN, ALWAYS
7 ->{
imageHolder.setImageDrawable(ContextCompat.getDrawable(requireContext(),R.drawable.megaphone))
setTextHtmlDescription(R.string.tutorial_permissions)
- if(Permissions.isNotificationPermissionNeeded()) {
- val disabled = Permissions.isPermissionGranted(
+ if(PermissionsHelper.isNotificationPermissionNeeded()) {
+ val disabled = PermissionsHelper.isPermissionGranted(
requireContext(),
android.Manifest.permission.POST_NOTIFICATIONS
)
setInteractButtonState(ButtonState.NOTIFICATIONS, !disabled)
interactButton.setOnClickListener {
- if (Permissions.isNotificationPermissionNeeded()) {
+ if (PermissionsHelper.isNotificationPermissionNeeded()) {
notificationsReqLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS)
}
}
interactButton.visibility = View.VISIBLE
}
//show the other button
val button = root.findViewById<Button>(R.id.closeAllButton)
button.setText(R.string.close_tutorial_short)
button.visibility = View.VISIBLE
button.setOnClickListener {
listener.closeIntroduction()
}
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
textView.breakStrategy = LineBreaker.BREAK_STRATEGY_HIGH_QUALITY
}
return root
}
private fun setTextHtmlDescription(resId: Int){
textView.text = utils.convertHtml(getString(resId))
}
private fun setInteractButtonState(state: ButtonState, active: Boolean){
when(state){
ButtonState.LOCATION ->
if(active) interactButton.setText(R.string.grant_location_permission)
else interactButton.setText(R.string.location_permission_granted)
ButtonState.NOTIFICATIONS -> if(active)
interactButton.setText(R.string.grant_notification_permission)
else interactButton.setText(R.string.notification_permission_granted)
}
if(!active) {
val color = ViewUtils.getColorFromTheme(requireContext(), R.attr.colorAccent)//ContextCompat.getColor(requireContext(), R.style.AppTheme.)
if(Build.VERSION.SDK_INT >= 29)
interactButton.background.colorFilter = BlendModeColorFilter(color, BlendMode.MULTIPLY)
else
interactButton.background.setColorFilter(
color,PorterDuff.Mode.MULTIPLY)
interactButton.isClickable = false
}
}
private fun setImageBitmap(imageView: ImageView, resId: Int, maxDpToScale:Float = DP_LIM_IMAGE){
val bitmap = BitmapFactory.decodeResource(resources,resId)
val limPix = utils.convertDipToPixels(resources, maxDpToScale)
if (bitmap.width > limPix) {
val rescFac = limPix/bitmap.width
val rescaledBitmap = Bitmap.createScaledBitmap(bitmap,(limPix).toInt(), (bitmap.height*rescFac).toInt(),false)
imageView.setImageBitmap(rescaledBitmap)
}
else
imageView.setImageBitmap(bitmap)
}
companion object {
const val DP_LIM_IMAGE = 1000f
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param index the screen index
* @return A new instance of fragment IntroFragment.
*/
@JvmStatic
fun newInstance(index: Int) =
IntroFragment().apply {
arguments = Bundle().apply {
putInt(SCREEN_INDEX, index)
}
}
@JvmStatic
fun makeArguments(index: Int) = Bundle().apply {
putInt(SCREEN_INDEX, index) }
fun View.disable() {
background.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY)
isClickable = false
}
enum class ButtonState{
LOCATION, NOTIFICATIONS
}
}
interface IntroListener{
fun closeIntroduction()
}
}
\ No newline at end of file
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 ba55d31..6133419 100644
--- a/app/src/main/java/it/reyboz/bustorino/fragments/LinesDetailFragment.kt
+++ b/app/src/main/java/it/reyboz/bustorino/fragments/LinesDetailFragment.kt
@@ -1,1188 +1,1163 @@
/*
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 <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.fragments
-import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
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.widget.*
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
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.Stop
import it.reyboz.bustorino.backend.gtfs.GtfsUtils
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.map.*
-import it.reyboz.bustorino.util.Permissions
+import it.reyboz.bustorino.util.PermissionsHelper
import it.reyboz.bustorino.viewmodels.LinesViewModel
import it.reyboz.bustorino.viewmodels.MapStateViewModel
import it.reyboz.bustorino.viewmodels.ServiceAlertsViewModel
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.maps.MapLibreMap
import org.maplibre.android.maps.Style
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_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
class LinesDetailFragment() : GeneralMapLibreFragment() {
private var lineID = "" // the GTFS line ID (e.g. "gtt:10U")
private lateinit var patternsSpinner: Spinner
private var patternsAdapter: ArrayAdapter<String>? = null
- //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<MatoPatternWithStops>
//private lateinit var map: MapView
private var patternShown: MatoPatternWithStops? = null
private val viewModel: LinesViewModel by viewModels()
private val alertsViewModel: ServiceAlertsViewModel by activityViewModels()
//private var firstInit = true
private var pausedFragment = false
private lateinit var switchButton: ImageButton
private lateinit var lineInfoButton: 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 = ""
private var patternIdToShow = ""
//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 polylineSource: GeoJsonSource
private lateinit var polyArrowSource: GeoJsonSource
-
- private var savedCameraPosition: CameraPosition? = null
-
private var lastStopsSizeShown = 0
-
//BUS POSITIONS
-
- private var enablingPositionFromClick = false
-
private var polyline: LineString? = null
//private var stopPosList = ArrayList<GeoPoint>()
//fragment actions
private var showOnTopOfLine = false
- private var recyclerInitDone = false
private var usingMQTTPositions = true
private var restoredCameraInMap = false
- //position of live markers
-
- private val tripMarkersAnimators = HashMap<String, ObjectAnimator>()
//extra items to use the LibreMap
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val args = requireArguments()
lineID = args.getString(LINEID_KEY,"")
stopIDFromToShow = args.getString(STOPID_FROM_KEY, "") //can be null
patternIdToShow = args.getString(PATTERN_SHOW_KEY, "")
}
@SuppressLint("SetTextI18n")
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
//reset statuses
//isBottomSheetShowing = false
//stopsLayerStarted = false
lastStopsSizeShown = 0
mapInitialized = false
val rootView = inflater.inflate(R.layout.fragment_lines_detail, container, false)
//lineID = requireArguments().getString(LINEID_KEY, "")
arguments?.let {
lineID = it.getString(LINEID_KEY, "")
stopIDFromToShow = it.getString(STOPID_FROM_KEY, "") //can be null
patternIdToShow = it.getString(PATTERN_SHOW_KEY, "")
Log.d(DEBUG_TAG, "LineID selected: $lineID, stopIDFromToShow: $stopIDFromToShow, patternIdToShow: $patternIdToShow")
}
switchButton = rootView.findViewById(R.id.switchImageButton)
locationIcon = rootView.findViewById(R.id.locationEnableIcon)
busPositionsIconButton = rootView.findViewById(R.id.busPositionsImageButton)
lineInfoButton = rootView.findViewById(R.id.lineInfoWarningButton)
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)
//TODO: Unify in GeneralMapLibreFragment
// Setup close button
rootView.findViewById<View>(R.id.btnClose).setOnClickListener {
hideStopOrBusBottomSheet()
}
val titleTextView = rootView.findViewById<TextView>(R.id.titleTextView)
titleTextView.text = getString(R.string.line)+" "+ GtfsUtils.lineNameDisplayFromGtfsID(lineID)
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<String>())
patternsSpinner.adapter = patternsAdapter
initializeRecyclerView()
switchButton.setOnClickListener{
if(mapView?.visibility == View.VISIBLE){
hideMapAndShowStopList()
} else{
hideStopListAndShowMap()
}
}
locationIcon?.let {view ->
//set click Listener
view.setOnClickListener(this::switchUserLocationStatus)
}
busPositionsIconButton.setOnClickListener {
LivePositionsDialogFragment().show(parentFragmentManager, "LivePositionsDialog")
}
//set
lineInfoButton.setOnClickListener {
AlertsDialogFragment.newInstanceForLine(lineID).show(parentFragmentManager, "Alerts-Line$lineID")
}
/*
*/
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)
livePositionsViewModel.retriggerPositionUpdate()
}
if (shownStopInBottomSheet!=null){
//check if the stop is inside the new pattern
/*val s = shownStopInBottomSheet!!
val newPatternStops = patternWithStops.stopsIndices
val filterPStops = newPatternStops.filter { ps -> ps.stopGtfsId == "gtt:${s.ID}" }
if (filterPStops.isEmpty()){
hideStopOrBusBottomSheet()
}
*/
// do another thing, just close the stop when the pattern is changed
if (patt.code != patternWithStops.pattern.code){
hideStopOrBusBottomSheet()
}
}
}
}
livePositionsViewModel.setGtfsLineToFilterPos(lineID, patternWithStops.pattern)
}
override fun onNothingSelected(p0: AdapterView<*>?) {
}
}
Log.d(DEBUG_TAG, "Views created!")
observeStatusLivePositions()
return rootView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//reflect UI
//INITIALIZE VIEW MODELS
viewModel.setRouteIDQuery(lineID)
livePositionsViewModel.setGtfsLineToFilterPos(lineID, null)
//observe the change, clear buses when switching position
livePositionsViewModel.useMQTTPositionsLiveData.observe(viewLifecycleOwner){ useMQTT->
//Log.d(DEBUG_TAG, "Changed MQTT positions, now have to use MQTT: $useMQTT")
if (isResumed) {
//Log.d(DEBUG_TAG, "Deciding to switch, the current source is using MQTT: $usingMQTTPositions")
if(useMQTT!=usingMQTTPositions){
// we have to switch
val clearPos = PreferenceManager.getDefaultSharedPreferences(requireContext()).getBoolean("positions_clear_on_switch_pref", true)
livePositionsViewModel.clearOldPositionsUpdates()
if(useMQTT){
//switching to MQTT, the GTFS positions are disabled automatically
livePositionsViewModel.requestMatoPosUpdates(GtfsUtils.getLineNameFromGtfsID(lineID))
} else{
//switching to GTFS RT: stop Mato, launch first request
livePositionsViewModel.stopMatoUpdates()
livePositionsViewModel.requestGTFSUpdates()
}
Log.d(DEBUG_TAG, "Should clear positions: $clearPos")
if (clearPos) {
livePositionsViewModel.clearAllPositions()
//force clear of the viewed data
if(!vehShowing.isNullOrEmpty()) hideStopOrBusBottomSheet()
clearAllBusPositionsInMap()
}
}
}
usingMQTTPositions = useMQTT
}
val keySourcePositions = getString(R.string.pref_positions_source)
usingMQTTPositions = PreferenceManager.getDefaultSharedPreferences(requireContext())
.getString(keySourcePositions, "mqtt").contentEquals("mqtt")
viewModel.patternsWithStopsByRouteLiveData.observe(viewLifecycleOwner, this::savePatternsToShow)
/*
*/
viewModel.stopsForPatternLiveData.observe(viewLifecycleOwner) { stops ->
val pattern = viewModel.selectedPatternLiveData.value
if (pattern == null) {
Log.w(DEBUG_TAG, "The selectedPattern is null!")
return@observe
}
if(mapView?.visibility ==View.VISIBLE) {
// We have the pattern and the stops here, time to display them
//TODO: Decide if we should follow the camera view given by the previous screen (probably the map fragment)
// use !restoredCameraInMap to do so
// val shouldZoom = (shownStopInBottomSheet == null) //use this if we want to avoid zoom when we're keeping the stop open
displayPatternWithStopsOnMap(pattern, stops, true)
} else {
if(stopsRecyclerView.visibility==View.VISIBLE) {
patternShown = pattern
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
}
mapStateViewModel.locationUserActive.observe(viewLifecycleOwner) {
+ Log.d(DEBUG_TAG, "User location is enabled: $it")
setLocationIconEnabled(it)
}
// enable info button if there are alerts on the line
alertsViewModel.setGtfsLineFilter(lineID)
alertsViewModel.alertsByRouteLiveData.observe(viewLifecycleOwner){ list ->
Log.d(DEBUG_TAG, "alerts for line $lineID: ${list.size}")
if(list.isNotEmpty()){
lineInfoButton.visibility = View.VISIBLE
//Log.d(DEBUG_TAG, "First alert is:\n ${list[0].longPrint()}")
} else
lineInfoButton.visibility = View.GONE
}
lineInfoButton.setOnClickListener {
AlertsDialogFragment.newInstanceForLine(lineID).show(parentFragmentManager, "Alerts-Line$lineID")
}
}
// ------------- UI switch stuff ---------
private fun hideMapAndShowStopList(){
mapView?.visibility = View.GONE
stopsRecyclerView.visibility = View.VISIBLE
locationIcon?.visibility = View.GONE
busPositionsIconButton?.visibility = View.GONE
viewModel.setMapShowing(false)
if(usingMQTTPositions) livePositionsViewModel.stopMatoUpdates()
//map.overlayManager.remove(busPositionsOverlay)
switchButton.setImageDrawable(AppCompatResources.getDrawable(requireContext(), R.drawable.ic_map_white_30))
hideStopOrBusBottomSheet()
- if(locationComponent.isLocationComponentEnabled){
+ if(locationComponent?.isLocationComponentEnabled == true){
+ //disable location
+ setLocationComponentEnabled(false)
+ //shouldMapLocationBeReactivated = true
+ } //else
+ //shouldMapLocationBeReactivated = false
+
+ /*if(mapStateViewModel.locationUserActive.value == true) {
setLocationComponentEnabled(false)
shouldMapLocationBeReactivated = true
- } else
- shouldMapLocationBeReactivated = false
+ } else shouldMapLocationBeReactivated = false
+
+ */
}
private fun hideStopListAndShowMap(){
stopsRecyclerView.visibility = View.GONE
mapView?.visibility = View.VISIBLE
locationIcon?.visibility = View.VISIBLE
busPositionsIconButton.visibility = View.VISIBLE
viewModel.setMapShowing(true)
//map.overlayManager.add(busPositionsOverlay)
//map.
if(usingMQTTPositions)
livePositionsViewModel.requestMatoPosUpdates(GtfsUtils.getLineNameFromGtfsID(lineID))
else
livePositionsViewModel.requestGTFSUpdates()
switchButton.setImageDrawable(AppCompatResources.getDrawable(requireContext(), R.drawable.ic_list_30))
- if(shouldMapLocationBeReactivated){
- setLocationComponentEnabled(Permissions.bothLocationPermissionsGranted(requireContext()))
+ if(mapStateViewModel.locationUserActive.value == true){
+ val actual = (PermissionsHelper.bothLocationPermissionsGranted(requireContext()))
+ setLocationComponentEnabled(actual)
+ if (!actual) context?.let{ Toast.makeText(it, R.string.location_permission_not_granted, Toast.LENGTH_LONG).show() }
}
}
override fun setLocationIconEnabled(enabled: Boolean){
if(enabled) {
locationIcon?.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.location_circlew_red))
}
else {
locationIcon?.setImageDrawable(ContextCompat.getDrawable(
requireContext(),
R.drawable.location_circlew_grey
)
)
}
}
override fun onMapLocationEnabled(active: Boolean) {
//extra thing: show the toast
showToastLocation(active)
}
override fun onMapLocationComponentInitialized() {
//enable the position after the first fix
//onMapLocationEnabled(true)
}
@SuppressLint("MissingPermission")
override fun onFirstReceivedLocation(location: Location) {
if(mapInitialized){
val center = map!!.cameraPosition.target
val newPos = LatLng(location.latitude, location.longitude)
Log.d(DEBUG_TAG, "Center of the map : $center")
val newStatus = if(center==null || newPos.distanceTo(center) > 20*1000){
Log.d(DEBUG_TAG, "Distance from center of map to location: "+center?.distanceTo(newPos))
if(!shownToastNoPosition) context?.let{ c->
Toast.makeText(c, R.string.too_far_not_showing_location, Toast.LENGTH_LONG).show()
shownToastNoPosition = true
}
false
} else{
true
}
if(!newStatus) setLocationComponentEnabled(newStatus)
mapStateViewModel.locationUserActive.value = newStatus
}
}
// ------------- Map Code -------------------------
- /**
- * This method sets up the map and the layers
- */
- override fun onMapReady(mapReady: MapLibreMap) {
- this.map = mapReady
- var setViewAlready = false
-
- val context = requireContext()
- 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 ->
- addImagesStyle(style)
-
- mapStyle = style
- //setupLayers(style)
-
- //checkInitMapLocation(mapReady, style,requireContext())
- //if(!stopsLayerStarted)
- initPolylineStopsLayers(style, null)
+ override fun onStyleLoaded(mapReady: MapLibreMap, style: Style) {
- setupBusLayer(style)
+ initPolylineStopsLayers(style, null)
- initSymbolManager(mapReady, style)
- toRunWhenMapReady?.run()
- toRunWhenMapReady = null
- mapInitialized = true
+ setupBusLayer(style)
- if(patternShown!=null){
- viewModel.stopsForPatternLiveData.value?.let {
- Log.d(DEBUG_TAG, "Show stops from the cache")
- displayPatternWithStopsOnMap(patternShown!!, it, true)
- //Show stop from cache
- mapStateViewModel.lastOpenStopID.value?.let{ sID->
- val s= it.filter { stop -> stop.ID==sID }
- if (s.isEmpty()) {
- if(sID.isNotEmpty())
- Log.w(DEBUG_TAG,"Wanted to open stop $sID in map but it was not loaded!")
- }
- else openStopInBottomSheet(s[0])
+ initSymbolManager(mapReady, style)
+ if(!mapStateViewModel.mapInitOnce.get() || mapStateViewModel.locationUserActive.value == true)
+ checkInitMapLocation(mapReady, style, requireContext())
+ }
- }
+ override fun setupMapListenersOnInit(mapReady: MapLibreMap) {
+ mapReady.addOnMapClickListener { point ->
+ val screenPoint = mapReady.projection.toScreenLocation(point)
+ val stopsNearby = mapReady.queryRenderedFeatures(screenPoint, STOPS_LAYER_ID)
+ val busNearby = mapReady.queryRenderedFeatures(screenPoint, BUSES_LAYER_ID)
+ //Log.d(DEBUG_TAG, "onMapClick, stopsNearby: $stopsNearby \nstopShown: $shownStopInBottomSheet \nbusNearby: $busNearby,")
+
+ if (stopsNearby.isNotEmpty()) {
+ val feature = stopsNearby[0]
+ val id = feature.getStringProperty("id")
+ val stop = viewModel.getStopByID(id)
+ stop?.let {
+ if (isBottomSheetShowing()) {
+ hideStopOrBusBottomSheet()
}
+ openStopInBottomSheet(it)
-
+ //move camera
+ if(it.latitude!=null && it.longitude!=null)
+ mapReady.animateCamera(CameraUpdateFactory.newLatLng(LatLng(it.latitude!!,it.longitude!!)),750)
}
- var restoredMapState = mapStateViewModel.restoreMapState(mapReady)
- arguments?.let { args ->
- // if there is a Camera State in the arguments, set it for the new camera (doesn't work yet!)
- if (!restoredMapState && MapCameraState.checkInBundle(args)) {
- val initCamState = MapCameraState.fromBundle(args)
- //map?.let{
- MapStateViewModel.restoreMapState(mapReady, initCamState)
- setViewAlready = true
- restoredMapState = true
+ return@addOnMapClickListener true
+ } else if (busNearby.isNotEmpty()){
+ val feature = busNearby[0]
+ openBusFromMapClick(feature)
- }
- }
- restoredCameraInMap = restoredMapState
+ return@addOnMapClickListener true
}
+ false
+ }
+ }
- mapReady.addOnMapClickListener { point ->
- val screenPoint = mapReady.projection.toScreenLocation(point)
- val stopsNearby = mapReady.queryRenderedFeatures(screenPoint, STOPS_LAYER_ID)
- val busNearby = mapReady.queryRenderedFeatures(screenPoint, BUSES_LAYER_ID)
- //Log.d(DEBUG_TAG, "onMapClick, stopsNearby: $stopsNearby \nstopShown: $shownStopInBottomSheet \nbusNearby: $busNearby,")
-
- if (stopsNearby.isNotEmpty()) {
- val feature = stopsNearby[0]
- val id = feature.getStringProperty("id")
- val stop = viewModel.getStopByID(id)
- stop?.let {
- if (isBottomSheetShowing()) {
- hideStopOrBusBottomSheet()
- }
- openStopInBottomSheet(it)
+ override fun onMapLibreInitialized(mapReady: MapLibreMap) {
+ toRunWhenMapReady?.run()
+ toRunWhenMapReady = null
- //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]
- openBusFromMapClick(feature)
+ observeBusPositionUpdates()
+
+ if(patternShown!=null){
+ viewModel.stopsForPatternLiveData.value?.let {
+ Log.d(DEBUG_TAG, "Show stops from the cache")
+ displayPatternWithStopsOnMap(patternShown!!, it, true)
+ //Show stop from cache
+ mapStateViewModel.lastOpenStopID.value?.let { sID ->
+ val s = it.filter { stop -> stop.ID == sID }
+ if (s.isEmpty()) {
+ if (sID.isNotEmpty())
+ Log.w(DEBUG_TAG, "Wanted to open stop $sID in map but it was not loaded!")
+ } else openStopInBottomSheet(s[0])
- return@addOnMapClickListener true
}
- false
}
-
- // we start requesting the bus positions now
- observeBusPositionUpdates()
-
}
- val zoom = 12.0
- val latlngTarget = LatLng(MapLibreFragment.DEFAULT_CENTER_LAT, MapLibreFragment.DEFAULT_CENTER_LON)
- if(!setViewAlready)
- mapReady.cameraPosition = savedCameraPosition ?:CameraPosition.Builder().target(latlngTarget).zoom(zoom).build()
+ var restoredMapState = false
- savedCameraPosition = null
+ restoredMapState = mapStateViewModel.restoreMapState(mapReady)
+ arguments?.let { args ->
+ // if there is a Camera State in the arguments, set it for the new camera (doesn't work yet!)
+ if (!restoredMapState && MapCameraState.checkInBundle(args)) {
+ val initCamState = MapCameraState.fromBundle(args)
+ //map?.let{
+ MapStateViewModel.restoreMapState(mapReady, initCamState)
+ restoredMapState = true
+
+ }
+ }
+ restoredCameraInMap = restoredMapState
+ Log.d(DEBUG_TAG, "Restored map state: $restoredMapState")
- if(shouldMapLocationBeReactivated)
- mapReady.style?.let{ checkInitMapLocation(mapReady,it, context)}
+ if(!restoredMapState) {
+ val zoom = 12.0
+ val latlngTarget = LatLng(MapLibreFragment.DEFAULT_CENTER_LAT, MapLibreFragment.DEFAULT_CENTER_LON)
+ mapReady.cameraPosition = CameraPosition.Builder().target(latlngTarget).zoom(zoom).build()
+ }
}
override fun showOpenStopWithSymbolLayer(): Boolean {
return true
}
/**
* Separate function to find the vehicle associated with a feature and display it
*/
private fun openBusFromMapClick(feature: Feature){
val vehid = feature.getStringProperty("veh")
if(isBottomSheetShowing())
hideStopOrBusBottomSheet()
showVehicleTripInBottomSheet(vehid)
updatesByVehDict[vehid]?.let {
map?.animateCamera(
CameraUpdateFactory.newLatLng(LatLng(it.posUpdate.latitude, it.posUpdate.longitude)),
750
)
}
}
private fun observeBusPositionUpdates(){
//live bus positions
livePositionsViewModel.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, hasVehicleTracking = true) { veh->
showVehicleTripInBottomSheet(veh)
}
//if not using MQTT positions
if(!usingMQTTPositions){
livePositionsViewModel.requestDelayedGTFSUpdates(2000)
}
}
//download missing tripIDs
livePositionsViewModel.tripsGtfsIDsToQuery.observe(viewLifecycleOwner){
//gtfsPosViewModel.downloadTripsFromMato(dat);
MatoTripsDownloadWorker.requestMatoTripsDownload(
it, requireContext().applicationContext,
"BusTO-MatoTripDownload"
)
}
}
private fun showVehicleTripInBottomSheet(veh: String) {
super.showVehicleTripInBottomSheet(veh) { patternCode, veh ->
//this is checked in @GeneralMapLibreFragment
//val data = updatesByVehDict[veh] ?: return@showVehicleTripInBottomSheet
if (patternCode.isEmpty()) return@showVehicleTripInBottomSheet
if (patternShown?.pattern?.code == patternCode) {
//center view on vehicle
updatesByVehDict[veh]?.let { up->
map?.let{
/*
val c = it.cameraPosition
it.moveCamera(CameraUpdateFactory.CameraPositionUpdate(c.bearing,
LatLng(up.posUpdate.latitude, up.posUpdate.longitude),
c.tilt,c.zoom, c.padding)
)
*/
it.animateCamera(CameraUpdateFactory.newLatLng(LatLng(up.posUpdate.latitude, up.posUpdate.longitude)))
}
} ?: {
Toast.makeText(context, R.string.showing_same_direction, Toast.LENGTH_SHORT).show()
}
} else {
showPatternWithCode(patternCode)
}
}
}
// ------- MAP LAYERS INITIALIZE ----
/**
* Initialize the map layers for the stops
*/
private fun initPolylineStopsLayers(style: Style, arrowFeatures: FeatureCollection?){
Log.d(DEBUG_TAG, "INIT STOPS CALLED")
stopsSource = GeoJsonSource(STOPS_SOURCE_ID)
//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 icons
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)!!)
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
initStopsLayer(style, null, POLY_ARROWS_LAYER)
}
private fun filterPatternFromArgs(patterns: List<MatoPatternWithStops>): MatoPatternWithStops?{
var p: MatoPatternWithStops? = null
if (patternIdToShow.isNotEmpty()){
for (patt in patterns) {
if (patt.pattern.code == patternIdToShow){
p = patt
}
}
if(p==null)
Log.w(DEBUG_TAG, "We had to show the pattern with code $patternIdToShow, but we didn't find it")
else
Log.d(DEBUG_TAG, "Requesting to show pattern with code $patternIdToShow, found pattern ${p.pattern.code}")
}
// if we are loading from a stop, find it
else if(stopIDFromToShow.isNotEmpty()) {
val stopGtfsID = "gtt:$stopIDFromToShow"
var pLength = 0
for (patt in patterns) {
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
}
}
}
if(p==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 ${p.pattern.code}")
}
// the flag of showing pattern is not necessary anymore, we have set the pattern
patternIdToShow = ""
// the flag of selecting from stop needs to be used again when displaying the pattern
return p
}
/**
* Save the loaded pattern data, without the stops!
*/
private fun savePatternsToShow(patterns: List<MatoPatternWithStops>){
currentPatterns = patterns.sortedWith(patternsSorter)
patternsAdapter?.let {
it.clear()
it.addAll(currentPatterns.map { p->"${p.pattern.directionId} - ${p.pattern.headsign}" })
it.notifyDataSetChanged()
}
val patternToShow = filterPatternFromArgs(currentPatterns)
if(patternToShow!=null) {
//showPattern(patternToShow)
patternShown = patternToShow
}
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 }
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")
// this triggers the showing on the map / recyclerview
if (pos !=-2)
patternsSpinner.setSelection(pos)
else
Log.e(DEBUG_TAG, "Pattern with code $code not found!!")
}
/**
* Zoom on the map to get the pattern
*/
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<Stop>, zoomToPattern: Boolean){
if(!mapInitialized){
//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<Feature>()
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<Feature>()
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")
initPolylineStopsLayers(mapStyle, 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!!")
}
var reallyZoomToPattern = zoomToPattern
if(stopIDFromToShow.isNotEmpty()){
//open the stop
val stopfilt = stopsSorted.filter { s -> s.ID == stopIDFromToShow }
if (stopfilt.isEmpty()){
Log.e(DEBUG_TAG, "Tried to show stop but it's not in the selected pattern")
} else{
val stop = stopfilt[0]
openStopInBottomSheet(stop)
if(stop.hasCoords()) {
reallyZoomToPattern = false
setCameraPosition(stop.latitude!!, stop.longitude!!, 13.5)
}
}
// Reset this to avoid checking again when showing
stopIDFromToShow = ""
//camera set
}
if(reallyZoomToPattern) zoomToCurrentPattern()
}
private fun initializeRecyclerView(){
val llManager = LinearLayoutManager(context)
llManager.orientation = LinearLayoutManager.VERTICAL
stopsRecyclerView.layoutManager = llManager
}
private fun showStopsInRecyclerView(stops: List<Stop>){
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
}
}
}
override fun onResume() {
super.onResume()
Log.d(DEBUG_TAG, "Resetting paused from onResume")
pausedFragment = false
val keySourcePositions = getString(R.string.pref_positions_source)
usingMQTTPositions = PreferenceManager.getDefaultSharedPreferences(requireContext())
.getString(keySourcePositions, "mqtt").contentEquals("mqtt")
//separate paths
if(usingMQTTPositions)
livePositionsViewModel.requestMatoPosUpdates(GtfsUtils.getLineNameFromGtfsID(lineID))
else
livePositionsViewModel.requestGTFSUpdates()
//initialize GUI here
fragmentListener?.readyGUIfor(FragmentKind.LINES)
}
override fun onPause() {
super.onPause()
if(usingMQTTPositions) livePositionsViewModel.stopMatoUpdates()
pausedFragment = true
//save map
map?.let{
//if map is initialized
mapStateViewModel.saveMapState(it)
}
mapStateViewModel.lastOpenStopID.postValue(shownStopInBottomSheet?.ID)
}
- override fun onStop() {
+ /*override fun onStop() {
super.onStop()
if(locationInitialized)
shouldMapLocationBeReactivated = locationComponent.isLocationComponentEnabled
else
shouldMapLocationBeReactivated = false
}
+ */
+
override fun onDestroyView() {
- map?.run {
+ map?.let {
Log.d(DEBUG_TAG, "Saving camera position")
- savedCameraPosition = cameraPosition
+ //savedCameraPosition = cameraPosition
+ mapStateViewModel.saveMapState(it)
}
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
setLocationComponentEnabled(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 PATTERN_SHOW_KEY ="patternIDShow"
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 makeArgsPattern(lineID: String, patternShow: String?, extraArgs: Bundle?): Bundle {
val b= extraArgs ?: Bundle()
b.putString(LINEID_KEY, lineID)
b.putString(PATTERN_SHOW_KEY, patternShow)
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>): 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
}
}
\ No newline at end of file
diff --git a/app/src/main/java/it/reyboz/bustorino/fragments/MainScreenFragment.java b/app/src/main/java/it/reyboz/bustorino/fragments/MainScreenFragment.java
index 00af54b..45c6a9a 100644
--- a/app/src/main/java/it/reyboz/bustorino/fragments/MainScreenFragment.java
+++ b/app/src/main/java/it/reyboz/bustorino/fragments/MainScreenFragment.java
@@ -1,1098 +1,1097 @@
/*
BusTO - Fragments 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 <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.fragments;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.InputType;
import android.widget.TextView;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatImageButton;
import androidx.appcompat.widget.SearchView;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
-import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import it.reyboz.bustorino.BuildConfig;
import it.reyboz.bustorino.R;
import it.reyboz.bustorino.adapters.StopNearbyAdapter;
import it.reyboz.bustorino.backend.*;
-import it.reyboz.bustorino.util.Permissions;
+import it.reyboz.bustorino.util.PermissionsHelper;
import it.reyboz.bustorino.viewmodels.IntroViewModel;
import it.reyboz.bustorino.viewmodels.SearchStopsDBViewModel;
import org.jetbrains.annotations.NotNull;
-import static it.reyboz.bustorino.util.Permissions.LOCATION_PERMISSIONS;
+import static it.reyboz.bustorino.util.PermissionsHelper.LOCATION_PERMISSIONS;
/**
* A simple {@link Fragment} subclass.
* Use the {@link MainScreenFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class MainScreenFragment extends BarcodeFragment implements FragmentListenerMain, ParentFragmentManagerFromChild{
private static final String SAVED_FRAGMENT="saved_fragment";
private static final String DEBUG_TAG = "BusTO - MainFragment";
public static final String ARG_INITIAL_CONTENT = "initial_content";
public static final String ARG_STOP_ID = "pending_stop_id";
public static final String ARG_SEARCH_QUERY = "pending_search_query";
public final static String FRAGMENT_TAG = "MainScreenFragment";
private enum SearchMode {SEARCH_ID,SEARCH_NAME,INITIAL}
public enum InitialScreen {
HOME_BUTTONS(0),
NEARBY_STOPS(1),
ARRIVALS(2),
STOP_SEARCH(3),
NEARBY_ARRIVALS(4);
public final int code;
InitialScreen(int code) { this.code = code; }
@Nullable
public static InitialScreen fromCode(int code) {
for (InitialScreen c : values()) if (c.code == code) return c;
return null;
}
@NonNull
public static InitialScreen fromFragmentKind(@NonNull FragmentKind kind){
switch (kind){
case HOME_BUTTONS -> { return InitialScreen.HOME_BUTTONS; }
case NEARBY_STOPS -> { return InitialScreen.NEARBY_STOPS; }
case FragmentKind.ARRIVALS -> { return InitialScreen.ARRIVALS; }
case FragmentKind.STOPS -> { return InitialScreen.STOP_SEARCH; }
case FragmentKind.NEARBY_ARRIVALS -> { return InitialScreen.NEARBY_ARRIVALS; }
default -> {
throw new IllegalArgumentException("Unknown fragment kind");
}
}
}
}
private FragmentHelper fragmentHelper;
private SwipeRefreshLayout swipeRefreshLayout;
//private EditText busStopSearchByIDEditText;
//private EditText busStopSearchByNameEditText;
private SearchView busStopSearchView;
private ProgressBar progressBar;
private FloatingActionButton floatingActionButton;
private SearchStopsDBViewModel searchStopsViewModel;
private boolean setupOnStart = true;
private boolean suppressArrivalsReload = false;
private boolean initialScreenShown = false;
private SearchMode searchMode = SearchMode.INITIAL;
private FragmentManager childFragMan;
/// LOCATION STUFF ///
boolean pendingIntroRun = false;
boolean pendingNearbyStopsFragmentRequest = false;
boolean pendingNearbyAddToBackStack = false;
boolean locationPermissionGranted, locationPermissionAsked = false;
//// ACTIVITY ATTACHED (LISTENER ///
private CommonFragmentListener mListener;
private String pendingStopID = null;
private String pendingSearchQuery = null;
private InitialScreen initialScreen = InitialScreen.HOME_BUTTONS;
private CoordinatorLayout coordLayout;
private RecyclerView suggestionsRecyclerView;
private StopNearbyAdapter suggestionsAdapter = null;
private TextView stopSearchMessageTextView;
//this is really a hackish thing, but it works
private final LinkedBlockingQueue<Runnable> thingsToDoOnStart = new LinkedBlockingQueue<>();
private boolean isSearchModeById(){
return searchMode != SearchMode.SEARCH_NAME;
}
private void emptySearchQueryViewModel(){
searchStopsViewModel.searchStops("",isSearchModeById());
}
private void refreshStop() {
if(getContext() == null){
Log.w(DEBUG_TAG,"Asked to refresh stop but context is null");
return;
}
if (childFragMan.findFragmentById(R.id.resultFrame) instanceof ArrivalsFragment) {
ArrivalsFragment fragment = (ArrivalsFragment) childFragMan.findFragmentById(R.id.resultFrame);
if (fragment == null){
//we create a new fragment, which is WRONG
Log.e("BusTO-RefreshStop", "Asking for refresh when there is no fragment");
} else{
//String stopName = fragment.getStopID();
fragment.requestArrivalsForTheFragment();
}
} else { //we create a new fragment, which is WRONG
Log.w(DEBUG_TAG, "Asked to refresh stop when there is no fragment");
}
}
private final ActivityResultLauncher<String[]> requestPermissionLauncher =
registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), new ActivityResultCallback<>() {
@Override
public void onActivityResult(Map<String, Boolean> result) {
if (result == null) return;
if (result.get(Manifest.permission.ACCESS_COARSE_LOCATION) == null ||
result.get(Manifest.permission.ACCESS_FINE_LOCATION) == null)
return;
Log.d(DEBUG_TAG, "Permissions for location are: " + result);
if (Boolean.TRUE.equals(result.get(Manifest.permission.ACCESS_COARSE_LOCATION))
|| Boolean.TRUE.equals(result.get(Manifest.permission.ACCESS_FINE_LOCATION))) {
locationPermissionGranted = true;
Log.w(DEBUG_TAG, "Starting position");
/*if (mListener != null && getContext() != null) {
if (locationManager == null)
locationManager = AppLocationManager.getInstance(getContext());
locationManager.addLocationRequestFor(requester);
}
*/
// show nearby fragment
//showNearbyStopsFragment();
Log.d(DEBUG_TAG, "We have location permission");
if (pendingNearbyStopsFragmentRequest) {
showNearbyFragmentIfPossible(pendingNearbyAddToBackStack);
pendingNearbyStopsFragmentRequest = false;
}
}
if (pendingNearbyStopsFragmentRequest) pendingNearbyStopsFragmentRequest = false;
}
});
public MainScreenFragment() {
// Required empty public constructor
}
public static MainScreenFragment newInstance(@NonNull InitialScreen kind,
@Nullable String stopId,
@Nullable String query) {
MainScreenFragment f = new MainScreenFragment();
f.setArguments(makeArgs(kind, stopId, query));
return f;
}
public static MainScreenFragment newInstance(@NonNull InitialScreen kind, @Nullable Bundle args){
MainScreenFragment f = new MainScreenFragment();
if (args != null) {
f.setArguments(args);
}
return f;
}
/**
* Create the bundle for the arguments of the fragment
* @param kind the kind of initial screen
* @param stopId
* @param query
* @return
*/
public static Bundle makeArgs(@NonNull InitialScreen kind, @Nullable String stopId, @Nullable String query) {
Bundle b = new Bundle();
b.putInt(ARG_INITIAL_CONTENT, kind.code);
if (stopId != null) b.putString(ARG_STOP_ID, stopId);
if (query != null) b.putString(ARG_SEARCH_QUERY, query);
return b;
}
public static Bundle makeArgsArrivals(@NonNull String stopID){
return makeArgs(InitialScreen.ARRIVALS, stopID, null);
}
public static Bundle makeArgsStops(@NonNull String query){
return makeArgs(InitialScreen.STOP_SEARCH, query, null);
}
public static Bundle makeArgsNearby(){
return makeArgs(InitialScreen.NEARBY_STOPS, null, null);
}
public static Bundle makeArgsButtonsScreen(){
return makeArgs(InitialScreen.HOME_BUTTONS, null, null);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle args = getArguments();
if (args != null) {
Log.d(DEBUG_TAG, "ARGS ARE NOT NULL: "+ args);
if (args.containsKey(ARG_INITIAL_CONTENT)) {
int code = args.getInt(ARG_INITIAL_CONTENT, InitialScreen.HOME_BUTTONS.code);
InitialScreen parsed = InitialScreen.fromCode(code);
initialScreen = (parsed != null) ? parsed : InitialScreen.HOME_BUTTONS;
}
String stopId = args.getString(ARG_STOP_ID);
if (stopId != null)
pendingSearchQuery = stopId;
else
pendingSearchQuery = args.getString(ARG_SEARCH_QUERY);
}
fragmentHelper = new FragmentHelper(this, getChildFragmentManager(), getContext(), R.id.resultFrame);
}
@Override
public boolean needToPopMainStackOnBack() {
return fragmentHelper.needToPopMainStackOnBack();
}
@Override
public void setMainFragmentManagerTransition(boolean yes) {
fragmentHelper.setMainFragmentManagerTransition(yes);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View root = inflater.inflate(R.layout.fragment_main_screen, container, false);
/// UI ELEMENTS //
//busStopSearchByIDEditText = root.findViewById(R.id.busStopSearchByIDEditText);
//busStopSearchByNameEditText = root.findViewById(R.id.busStopSearchByNameEditText);
busStopSearchView = root.findViewById(R.id.busStopSearchView);
progressBar = root.findViewById(R.id.progressBar);
swipeRefreshLayout = root.findViewById(R.id.listRefreshLayout);
floatingActionButton = root.findViewById(R.id.floatingActionButton);
stopSearchMessageTextView = root.findViewById(R.id.stopSearchMessageTextView);
suggestionsRecyclerView = root.findViewById(R.id.suggestionsRecyclerView);
suggestionsRecyclerView.setLayoutManager(new LinearLayoutManager(requireContext(),LinearLayoutManager.VERTICAL, false));
EditText searchEditText = busStopSearchView.findViewById(androidx.appcompat.R.id.search_src_text);
searchEditText.setSelectAllOnFocus(true);
searchEditText.setOnFocusChangeListener( (view,hasFocus) ->{
if(hasFocus){
showFloatingActionButton(true);
}
});
busStopSearchView.setOnFocusChangeListener( (view, hasFocus) ->{
if(hasFocus){
showFloatingActionButton(true);
}
});
//busStopSearchView.setSelectAllOnFocus(true);
/*busStopSearchByIDEditText
.setOnEditorActionListener((v, actionId, event) -> {
// IME_ACTION_SEARCH alphabetical option
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
onSearchClick(v);
return true;
}
return false;
});
*/
/*searchEditText
.setOnEditorActionListener((v, actionId, event) -> {
// IME_ACTION_SEARCH alphabetical option
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
onSearchClick(v);
return true;
}
return false;
});
*/
busStopSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String q) {
onSearchClick(null);
emptySearchQueryViewModel();
return true;
}
@Override
public boolean onQueryTextChange(String q) {
//Log.d(DEBUG_TAG, "Changed query text");
searchStopsViewModel.searchStops(q, isSearchModeById());
return true;
}
});
swipeRefreshLayout
.setOnRefreshListener(this::refreshStop);
swipeRefreshLayout.setColorSchemeResources(R.color.blue_500, R.color.orange_500);
coordLayout = root.findViewById(R.id.coord_layout);
floatingActionButton.setImageResource(R.drawable.magnifying_glass_larger);
floatingActionButton.setOnClickListener((this::onToggleKeyboardLayout));
/*busStopSearchByIDEditText.setOnFocusChangeListener((v, hasFocus) -> {
//Log.d(DEBUG_TAG, "stop search by ID has focus: " + hasFocus);
if(hasFocus)
setSearchModeBusStopID();
});
busStopSearchByNameEditText.setOnFocusChangeListener((v, hasFocus) -> {
//Log.d(DEBUG_TAG, "stop search by Name has focus: " + hasFocus);
if(hasFocus)
setSearchModeBusStopName();
});
*/
AppCompatImageButton qrButton = root.findViewById(R.id.QRButton);
qrButton.setOnClickListener(this::onQRButtonClick);
AppCompatImageButton searchButton = root.findViewById(R.id.searchButton);
searchButton.setOnClickListener(this::onSearchClick);
// Fragment stuff
childFragMan = getChildFragmentManager();
childFragMan.addOnBackStackChangedListener(() -> Log.d("BusTO Main Fragment", "BACK STACK CHANGED"));
/*
cr.setAccuracy(Criteria.ACCURACY_FINE);
cr.setAltitudeRequired(false);
cr.setBearingRequired(false);
cr.setCostAllowed(true);
cr.setPowerRequirement(Criteria.NO_REQUIREMENT);
*/
//locationManager = AppLocationManager.getInstance(requireContext());
IntroViewModel introViewModel = new ViewModelProvider(requireActivity()).get(IntroViewModel.class);
introViewModel.getIntroIsRunning().observe(getViewLifecycleOwner(), isRunning -> {
pendingIntroRun = isRunning;
});
// TODO: Figure out how to go back to home when pressing home in the nav side bar
/*fragShowingViewModel.getKindShowingFragment().observe(getViewLifecycleOwner(), kind -> {
Log.w(DEBUG_TAG, "showing fragment kind: " + kind);
try {
var screenType = InternalScreen.fromFragmentKind(kind);
if(screenType != internalScreen) {
showDifferentSubFragments(screenType);
internalScreen = screenType;
}
} catch (IllegalArgumentException e) {
//ignored
Log.d(DEBUG_TAG, "no update from fragment kind");
}
});
*/
Log.d(DEBUG_TAG, "OnCreateView, savedInstanceState null: "+(savedInstanceState==null));
return root;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d(DEBUG_TAG, "onViewCreated, have savedInstanceState: "+ (savedInstanceState!=null) +
"; SwipeRefreshLayout visible: "+(swipeRefreshLayout.getVisibility()==View.VISIBLE));
//Log.d(DEBUG_TAG, "Saved instance state is: "+savedInstanceState);
searchStopsViewModel = new ViewModelProvider(requireActivity()).get(SearchStopsDBViewModel.class);
searchStopsViewModel.getFilteredStopsSearch().observe(getViewLifecycleOwner(),
stops -> setSuggestionsStopRecyclerView(stops, true));
if (getChildFragmentManager().findFragmentById(R.id.resultFrame)!= null){
swipeRefreshLayout.setVisibility(View.VISIBLE);
// The child FragmentManager has restored its content — don't dispatch again
return;
}
if (savedInstanceState != null) return;
showDifferentSubFragments(initialScreen);
}
/**
* Installs the initial child fragment based on the arguments supplied as arguments
*/
private void showDifferentSubFragments(@NonNull InitialScreen screen) {
boolean firstTime = !initialScreenShown;
switch (screen) {
case NEARBY_STOPS:
case NEARBY_ARRIVALS: // TODO differentiate later
//add to back stack if it is not just created
showNearbyStopsFragmentChecking(!firstTime);
break;
case ARRIVALS:
// pendingStopID is consumed in onResume → requestArrivalsForStopID
if(pendingSearchQuery != null && isResumed()) {
swipeRefreshLayout.setVisibility(View.VISIBLE);
Log.d(DEBUG_TAG, "Searching arrivals for initial stop: "+pendingSearchQuery);
requestsArrivalsInternal(pendingSearchQuery, false);
pendingSearchQuery = null;
}
break;
case STOP_SEARCH:
if (pendingSearchQuery != null && pendingSearchQuery.length() >= 2) {
fragmentHelper.requestStopSearch(pendingSearchQuery);
} else {
showButtonsFragment(firstTime);
}
pendingSearchQuery = null;
break;
case HOME_BUTTONS:
default:
showButtonsFragment(firstTime);
}
if(!initialScreenShown){
initialScreenShown = true;
}
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
super.onSaveInstanceState(outState);
Log.d(DEBUG_TAG, "Saving instance state");
Fragment fragment = getChildFragmentManager().findFragmentById(R.id.resultFrame);
if (fragment!=null)
getChildFragmentManager().putFragment(outState, SAVED_FRAGMENT, fragment);
//if (fragmentHelper!=null) fragmentHelper.setBlockAllActivities(true);
}
public void setSuggestionsStopRecyclerView(List<Stop> stops, boolean showMessage){
var res = !stops.isEmpty();
var query = searchStopsViewModel.getQueryStops();
//Log.d(DEBUG_TAG, "received stops suggestions, are "+stops.size());
if(res){
if(suggestionsAdapter!=null){
suggestionsAdapter.setStops(stops);
} else{
suggestionsAdapter = new StopNearbyAdapter(new ArrayList<>(stops), null, true, (stop)->{
requestArrivalsForStopID(stop.ID);
//clear query
emptySearchQueryViewModel();
//setSuggestionsStopRecyclerView(List.of(), false);
});
suggestionsRecyclerView.setAdapter(suggestionsAdapter);
}
suggestionsRecyclerView.setVisibility(View.VISIBLE);
} else{
if(suggestionsAdapter !=null) suggestionsAdapter = null;
suggestionsRecyclerView.setVisibility(View.GONE);
if(showMessage && query!=null && !query.trim().isEmpty()){
stopSearchMessageTextView.setText( searchMode == SearchMode.SEARCH_NAME ?
R.string.no_stop_found_search_name : R.string.no_stop_found_search_number);
stopSearchMessageTextView.setVisibility(View.VISIBLE);
} else{
stopSearchMessageTextView.setVisibility(View.GONE);
}
}
}
public void setSuppressArrivalsReload(boolean value){
suppressArrivalsReload = value;
// we have to suppress the reloading of the (possible) ArrivalsFragment
/*if(value) {
Fragment fragment = getChildFragmentManager().findFragmentById(R.id.resultFrame);
if (fragment instanceof ArrivalsFragment) {
ArrivalsFragment frag = (ArrivalsFragment) fragment;
frag.setReloadOnResume(false);
}
}
*/
}
/**
* Cancel the reload of the arrival times
* because we are going to pop the fragment
*/
public void cancelReloadArrivalsIfNeeded(){
if(getContext()==null) return; //we are not attached
//Fragment fr = getChildFragmentManager().findFragmentById(R.id.resultFrame);
fragmentHelper.stopLastRequestIfNeeded();
toggleSpinner(false);
}
@Override
public void onAttach(@NonNull Context context) {
super.onAttach(context);
Log.d(DEBUG_TAG, "OnAttach called, setupOnAttach: "+ setupOnStart);
if (context instanceof CommonFragmentListener) {
mListener = (CommonFragmentListener) context;
} else {
throw new RuntimeException(context
+ " must implement CommonFragmentListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
// setupOnAttached = true;
}
@Override
public void onStart() {
super.onStart();
Log.d(DEBUG_TAG, "onStart called, setupOnStart: "+setupOnStart);
try {
while (!thingsToDoOnStart.isEmpty()) {
var task = thingsToDoOnStart.take();
task.run();
}
} catch (InterruptedException e) {
Log.w(DEBUG_TAG, "Interrupted while doing task for start");
thingsToDoOnStart.clear();
}
if (setupOnStart) {
if (pendingStopID==null){
if(!pendingIntroRun){
//show the fragment
//showButtonsFragment();
}
}
else{
///TODO: if there is a stop displayed, we need to hold the update
}
setupOnStart = false;
}
// this happens when the fragment is recreated and the query is set on the searchView
if(!searchStopsViewModel.getShowingSearchSuggestions()){
emptySearchQueryViewModel();
}
}
private void showButtonsFragment(boolean addInsteadOfReplace){
swipeRefreshLayout.setVisibility(View.VISIBLE);
var ft = childFragMan.beginTransaction();
var frag = ButtonsFragment.newInstance();
if(addInsteadOfReplace)
ft.add(R.id.resultFrame,frag, ButtonsFragment.FRAGMENT_TAG);
else{
ft.replace(R.id.resultFrame, frag, ButtonsFragment.FRAGMENT_TAG);
ft.addToBackStack(null);
}
ft.commit();
}
public void showButtonsFragmentIfNotNearby(boolean addToBackStack){
if(isAdded()) {
var framan = getChildFragmentManager();
var showingFrag = framan.findFragmentById(R.id.resultFrame);
if (showingFrag == null || showingFrag instanceof NearbyStopsFragment) {
var fragHome = ButtonsFragment.newInstance();
var ft = framan.beginTransaction();
if (showingFrag == null) {
ft.add(R.id.resultFrame, fragHome, ButtonsFragment.FRAGMENT_TAG);
} else {
ft.replace(R.id.resultFrame, fragHome, ButtonsFragment.FRAGMENT_TAG);
}
if (addToBackStack) ft.addToBackStack(null);
ft.commit();
} else {
Log.d(DEBUG_TAG, "attempting to show buttons home fragment but have other types (different than nearby)");
}
} else{
Log.d(DEBUG_TAG, "Fragment is not added, putting in queue of things to do");
try {
thingsToDoOnStart.put(() -> {
showButtonsFragmentIfNotNearby(addToBackStack);
});
} catch (InterruptedException e) {
Log.e(DEBUG_TAG,"Cannot add task");
}
}
}
private void showNearbyStopsFragmentChecking(boolean addToBackStack){
if(!checkLocationPermission()){
requestLocationPermission();
pendingNearbyStopsFragmentRequest = true;
pendingNearbyAddToBackStack = addToBackStack;
Log.d(DEBUG_TAG, "requesting location permission for nearby fragment");
}
else {
Log.d(DEBUG_TAG, "Showing nearby stops fragment");
showNearbyFragmentIfPossible(addToBackStack);
}
}
@Override
public void onResume() {
super.onResume();
final Context con = requireContext();
Log.w(DEBUG_TAG, "OnResume called, setupOnStart: "+ setupOnStart);
//recheck the introduction activity has been run
- if(Permissions.bothLocationPermissionsGranted(con)){
+ if(PermissionsHelper.bothLocationPermissionsGranted(con)){
Log.d(DEBUG_TAG, "Location permission OK");
} //don't request permission
// if we have a pending stopID request, do it
Log.d(DEBUG_TAG, "Pending stop ID for arrivals: "+pendingStopID);
//this is the second time we are attaching this fragment ->
Log.d(DEBUG_TAG, "Waiting for new stop request: "+ suppressArrivalsReload);
if (suppressArrivalsReload){
// we have to suppress the reloading of the (possible) ArrivalsFragment
Fragment fragment = getChildFragmentManager().findFragmentById(R.id.resultFrame);
if (fragment instanceof ArrivalsFragment){
ArrivalsFragment frag = (ArrivalsFragment) fragment;
frag.setReloadOnResume(false);
}
//deactivate
suppressArrivalsReload = false;
}
// check if the fragment start query is null
if(pendingSearchQuery!=null) {
requestsArrivalsInternal(pendingSearchQuery, false);
pendingSearchQuery = null;
}
else if(pendingStopID!=null){
Log.d(DEBUG_TAG, "Pending request for arrivals at stop ID: "+pendingStopID);
requestArrivalsForStopID(pendingStopID);
pendingStopID = null;
}
//mListener.readyGUIfor(FragmentKind.MAIN_SCREEN_FRAGMENT);
//fragmentHelper.setBlockAllActivities(false);
}
@Override
public void onPause() {
//mainHandler = null;
//locationManager.removeLocationRequestFor(requester);
//fragmentHelper.setBlockAllActivities(true);
fragmentHelper.stopLastRequestIfNeeded();
searchStopsViewModel.saveOpenSearchSuggestions();
super.onPause();
}
/*
GUI METHODS
*/
@Override
public void onQrScanSuccess(@NotNull String busIDToSearch) {
EditText searchEditText = busStopSearchView.findViewById(androidx.appcompat.R.id.search_src_text);
searchEditText.setText(busIDToSearch);
requestArrivalsForStopID(busIDToSearch);
}
/**
* QR scan button clicked
*
* @param v View QRButton clicked
*/
public void onQRButtonClick(View v) {
launchBarcodeScan();
}
/**
* OK this is pure shit
*
* @param v View clicked
*/
public void onSearchClick(View v) {
//final StopsFinderByName[] stopsFinderByNames = new StopsFinderByName[]{new GTTStopsFetcher(), new FiveTStopsFetcher()};
if (searchMode == SearchMode.SEARCH_ID || searchMode == SearchMode.INITIAL) {
String busStopID = busStopSearchView.getQuery().toString();
fragmentHelper.stopLastRequestIfNeeded();
requestArrivalsForStopID(busStopID);
} else if (searchMode == SearchMode.SEARCH_NAME) {
// searchMode == SEARCH_BY_NAME
String query = busStopSearchView.getQuery().toString();
query = query.trim();
if(getContext()!=null) {
if (query.length() < 1) {
Toast.makeText(getContext(), R.string.insert_bus_stop_name_error, Toast.LENGTH_SHORT).show();
} else if(query.length()< 2){
Toast.makeText(getContext(), R.string.query_too_short, Toast.LENGTH_SHORT).show();
}
else {
fragmentHelper.requestStopSearch(query);
}
}
}
}
public void onToggleKeyboardLayout(View v) {
switch (searchMode){
case SEARCH_ID:
setSearchMode(SearchMode.SEARCH_NAME);
if (busStopSearchView.requestFocus())
showKeyboard();
//}
break;
case SEARCH_NAME:
case INITIAL:
setSearchMode(SearchMode.SEARCH_ID);
if (busStopSearchView.requestFocus())
showKeyboard();
//}
}
}
@Override
public void enableRefreshLayout(boolean yes) {
Log.d(DEBUG_TAG, "Enabling refresh layout: " + yes);
swipeRefreshLayout.setEnabled(yes);
}
////////////////////////////////////// GUI HELPERS /////////////////////////////////////////////
private EditText getSearchEditText() {
return busStopSearchView.findViewById(androidx.appcompat.R.id.search_src_text);
}
public void showKeyboard() {
if(getActivity() == null) return;
final EditText et = getSearchEditText();
et.requestFocus();
et.post(() -> {
InputMethodManager imm = (InputMethodManager)
requireActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm == null) return;
imm.restartInput(et); // applica il nuovo inputType
imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
});
}
protected boolean isNearbyFragmentShown(){
Fragment fragment = getChildFragmentManager().findFragmentByTag(NearbyStopsFragment.FRAGMENT_TAG);
return (fragment!= null && fragment.isResumed());
}
private void setSearchMode(SearchMode mode) {
searchMode = mode;
busStopSearchView.setQuery("", false);
boolean byId = mode != SearchMode.SEARCH_NAME;
busStopSearchView.setInputType(byId ? InputType.TYPE_CLASS_NUMBER : InputType.TYPE_CLASS_TEXT);
floatingActionButton.setImageResource(byId ? R.drawable.numeric : R.drawable.alphabetical);
busStopSearchView.setQueryHint(getString(byId ? R.string.insert_bus_stop_number : R.string.insert_bus_stop_name));
}
/*
* Having that cursor at the left of the edit text makes me cancer.
*
* @param busStopID bus stop ID
*/
//
/*
private void setBusStopSearchByIDEditText(String busStopID) {
busStopSearchByIDEditText.setText(busStopID);
busStopSearchByIDEditText.setSelection(busStopID.length());
}
*/
@Nullable
@Override
public View getBaseViewForSnackBar() {
return coordLayout;
}
@Override
public void toggleSpinner(boolean enable) {
if (enable) {
//already set by the RefreshListener when needed
//swipeRefreshLayout.setRefreshing(true);
progressBar.setVisibility(View.VISIBLE);
} else {
swipeRefreshLayout.setRefreshing(false);
progressBar.setVisibility(View.GONE);
}
}
private void prepareGUIForArrivals() {
swipeRefreshLayout.setEnabled(true);
swipeRefreshLayout.setVisibility(View.VISIBLE);
//this is to hide the eventual search results from the text
//setSuggestionsStopRecyclerView(List.of(), false);
//actionHelpMenuItem.setVisible(true);
}
private void prepareGUIForBusStops() {
swipeRefreshLayout.setEnabled(false);
swipeRefreshLayout.setVisibility(View.VISIBLE);
//setSuggestionsStopRecyclerView(List.of(), false);
//actionHelpMenuItem.setVisible(false);
}
@Override
public void showFloatingActionButton(boolean yes) {
//mListener.showFloatingActionButton(yes);
if(yes)
floatingActionButton.setVisibility(View.VISIBLE);
else
floatingActionButton.setVisibility(View.GONE);
}
/**
* This provides a temporary fix to make the transition
* to a single asynctask go smoother
*
* @param fragmentType the type of fragment created
*/
@Override
public void readyGUIfor(FragmentKind fragmentType) {
if(BuildConfig.DEBUG) Log.d(DEBUG_TAG, "Readying main fragment for type "+fragmentType);
//if we are getting results, already, stop waiting for nearbyStops
if (fragmentType == FragmentKind.ARRIVALS || fragmentType == FragmentKind.STOPS) {
hideKeyboard();
if (pendingNearbyStopsFragmentRequest) {
//locationManager.removeLocationRequestFor(requester);
pendingNearbyStopsFragmentRequest = false;
}
}
if (fragmentType == null) Log.e("ActivityMain", "Problem with fragmentType");
else
switch (fragmentType) {
case ARRIVALS:
prepareGUIForArrivals();
break;
case STOPS:
prepareGUIForBusStops();
break;
default:
//Log.d(DEBUG_TAG, "Fragment type is unknown");
return;
}
// Shows hints
}
/*
// KEEPING THIS METHODS AS EXAMPLES FOR SHOW
boolean searchStopsResultsFragmentShown(){
Fragment frag = childFragMan.findFragmentById(R.id.resultFrame);
return frag instanceof StopSearchResultFragment;
}
void showSearchStopsResultsFragment(){
final String TAG = "stopSearchResult";
Fragment frag = childFragMan.findFragmentById(R.id.resultFrame);
if (frag instanceof StopSearchResultFragment){
return; //nothing to do
}
boolean exists = frag != null;
var trans = childFragMan.beginTransaction();
frag = childFragMan.findFragmentByTag(TAG);
if (!(frag instanceof StopSearchResultFragment)) {
frag = StopSearchResultFragment.newInstance();
}
if(exists){
//show the fragment
trans.replace(R.id.resultFrame,frag, TAG);
} else{
//create new fragment
trans.add(R.id.resultFrame,frag, TAG);
}
trans.addToBackStack(null);
trans.commit();
}
*/
@Override
public void openLineFromStop(String routeGtfsId, @Nullable String stopIDFrom) {
//pass to activity
if(mListener!=null) mListener.openLineFromStop(routeGtfsId, stopIDFrom);
}
@Override
public void openLineFromVehicle(String routeGtfsId, @Nullable String optionalPatternId, @Nullable Bundle args) {
if(mListener!=null) mListener.openLineFromVehicle(routeGtfsId, optionalPatternId, args);
}
@Override
public void openNearbyStopsFragment() {
if(isAdded())
showNearbyStopsFragmentChecking(true);
else
try{
thingsToDoOnStart.put(() -> showNearbyStopsFragmentChecking(true));
} catch (InterruptedException e) {
Log.e(DEBUG_TAG, "trying to put open nearby in task but was interrupted");
}
}
@Override
public void openLinesFragment() {
if(mListener!=null) mListener.openLinesFragment();
}
@Override
public void openFavoritesFragment() {
if(mListener!=null) mListener.openFavoritesFragment();
}
@Override
public void showMapCenteredOnStop(Stop stop) {
if(mListener!=null) mListener.showMapCenteredOnStop(stop);
}
private void requestsArrivalsInternal(String stopID, boolean addToBackStack) {
if (!isResumed()){
//defer request to onResume - it will be added to the backstack
pendingStopID = stopID;
Log.d(DEBUG_TAG, "Deferring update for stop "+stopID+ " saved: "+pendingStopID);
return;
}
final boolean delayedRequest = !(pendingStopID==null);
final FragmentManager framan = getChildFragmentManager();
if (getContext()==null){
Log.e(DEBUG_TAG, "Asked for arrivals with null context");
return;
}
if (stopID == null || stopID.isEmpty()) {
// we're still in UI thread, no need to mess with Progress
showToastMessage(R.string.insert_bus_stop_number_error, true);
toggleSpinner(false);
} else{
// ensure that the new sub-fragment is gonna be visible
swipeRefreshLayout.setVisibility(View.VISIBLE);
var palinaTrial = new Palina(stopID);
if (framan.findFragmentById(R.id.resultFrame) instanceof ArrivalsFragment fragment) {
if (fragment.isFragmentForTheSameStop(palinaTrial)){
// Run with previous fetchers
//fragment.getCurrentFetchers().toArray()
fragment.requestArrivalsForTheFragment();
} else{
// The rest of the case is handled by the fragment Helper
fragmentHelper.showArrivalsFragmentForStop(palinaTrial, addToBackStack);
}
}
else {
// this is not needed any more
//prepareGUIForArrivals();
fragmentHelper.showArrivalsFragmentForStop(palinaTrial, addToBackStack);
}
}
}
/**
* Main method for stops requests
* @param ID the Stop ID
*/
@Override
public void requestArrivalsForStopID(String ID) {
requestsArrivalsInternal(ID, true);
}
private boolean checkLocationPermission(){
final Context context = getContext();
if(context==null) return false;
final boolean noPermission = ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED;
return !noPermission;
}
private void requestLocationPermission(){
if(shouldShowRequestPermissionRationale(Manifest.permission.ACCESS_FINE_LOCATION)){
makeToast(R.string.enable_position_message_nearby);
}
requestPermissionLauncher.launch(LOCATION_PERMISSIONS);
}
private void showNearbyFragmentIfPossible(boolean addToBackStack) {
if (isNearbyFragmentShown()) {
//nothing to do
Log.d(DEBUG_TAG, "Asked to show nearby fragment but we already are showing it");
return;
}
if (getContext() == null) {
Log.e(DEBUG_TAG, "Wanting to show nearby fragment but context is null");
return;
}
if (!childFragMan.isDestroyed()) {
//Go ahead with the request
swipeRefreshLayout.setVisibility(View.VISIBLE);
final Fragment existingFrag = childFragMan.findFragmentById(R.id.resultFrame);
// fragment;
if (!(existingFrag instanceof NearbyStopsFragment)){
Log.d(DEBUG_TAG, "actually showing Nearby Stops Fragment");
//there is no fragment showing
var nearbyFrag = (NearbyStopsFragment) childFragMan.findFragmentByTag(NearbyStopsFragment.FRAGMENT_TAG);
if(nearbyFrag==null){
nearbyFrag = NearbyStopsFragment.newInstance(NearbyStopsFragment.FragType.STOPS);
}
FragmentTransaction ft = childFragMan.beginTransaction();
ft.replace(R.id.resultFrame, nearbyFrag, NearbyStopsFragment.FRAGMENT_TAG);
if(addToBackStack) ft.addToBackStack(null);
if (getActivity()!=null && !getActivity().isFinishing())
ft.commit();
else Log.e(DEBUG_TAG, "Not showing nearby fragment because activity null or is finishing");
}
pendingNearbyStopsFragmentRequest = false;
}
}
}
\ No newline at end of file
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 367d933..74fee9d 100644
--- a/app/src/main/java/it/reyboz/bustorino/fragments/MapLibreFragment.kt
+++ b/app/src/main/java/it/reyboz/bustorino/fragments/MapLibreFragment.kt
@@ -1,749 +1,718 @@
/*
BusTO - Fragments components
Copyright (C) 2025 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 <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.fragments
import android.annotation.SuppressLint
import android.content.Context
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.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.preference.PreferenceManager
import androidx.room.concurrent.AtomicBoolean
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.map.MapLibreLocationEngine
-import it.reyboz.bustorino.map.MapLibreStyles
import it.reyboz.bustorino.viewmodels.StopsMapViewModel
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.engine.LocationEngineCallback
import org.maplibre.android.location.engine.LocationEngineResult
import org.maplibre.android.location.modes.CameraMode
import org.maplibre.android.location.modes.RenderMode
import org.maplibre.android.maps.MapLibreMap
import org.maplibre.android.maps.Style
import org.maplibre.android.plugins.annotation.Symbol
import org.maplibre.geojson.Feature
import org.maplibre.geojson.FeatureCollection
/**
* A simple [Fragment] subclass.
* Use the [MapLibreFragment.newInstance] factory method to
* create an instance of this fragment.
*/
class MapLibreFragment : GeneralMapLibreFragment() {
private val stopsViewModel: StopsMapViewModel by viewModels()
private var stopsShowing = ArrayList<Stop>(0)
// Sources for stops and buses are in GeneralMapLibreFragment
private var isUserMovingCamera = false
private var lastStopsSizeShown = 0
private var lastBBox = LatLngBounds.from(2.0, 2.0, 1.0,1.0)
private var stopsRedrawnTimes = 0
//bottom Sheet behavior in GeneralMapLibreFragment
//private var stopActiveSymbol: Symbol? = null
// Location stuff
private lateinit var locationManager: LocationManager
private lateinit var userLocationButton: ImageButton
private lateinit var centerUserButton: ImageButton
private lateinit var followUserButton: ImageButton
private var followingUserLocation = false
private var ignoreCameraMovementForFollowing = true
private var restoredMapCamera = AtomicBoolean()
//BUS POSITIONS
private var usingMQTTPositions = true // THIS IS INSIDE VIEW MODEL NOW
private val symbolsToUpdate = ArrayList<Symbol>()
private var initialStopToShow : Stop? = null
private var initialStopShown = false
private var waitingDelayedBusUpdate = 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)
if (initialStopToShow==null){
} else if(!initialStopToShow!!.hasCoords()){
//null the stop if it doesn't have coordinates, we cannot find it
initialStopToShow = null
}
}
}
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)
mapView!!.onCreate(savedInstanceState)
mapView!!.getMapAsync(this)
//init bottom sheet
initBottomSheet(rootView)
userLocationButton = rootView.findViewById(R.id.locationEnableIcon)
userLocationButton.setOnClickListener(this::switchUserLocationStatus)
followUserButton = rootView.findViewById(R.id.followUserImageButton)
centerUserButton = rootView.findViewById(R.id.centerMapImageButton)
busPositionsIconButton = rootView.findViewById(R.id.busPositionsImageButton)
busPositionsIconButton.setOnClickListener {
LivePositionsDialogFragment().show(parentFragmentManager, "LivePositionsDialog")
}
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)
+ locationComponent?.let { if (context != null && it.isLocationComponentEnabled) {
+ val location = it.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 && locationInitialized && locationComponent.isLocationComponentEnabled){
+ if(context!=null && locationInitialized && (locationComponent?.isLocationComponentEnabled ?: false)){
// CameraMode.TRACKING makes the camera move and jump to the location
setFollowUserLocation(!followingUserLocation)
}
}
- //locationManager = requireActivity().getSystemService(Context.LOCATION_SERVICE) as LocationManager
- /*
- if (Permissions.bothLocationPermissionsGranted(requireContext()) && deviceHasGpsProvider()) {
-
- 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()
- }
- // PERMISSIONS REQUESTED AFTER MAP SETUP
- }
-
- */
// Setup close button
rootView.findViewById<View>(R.id.btnClose).setOnClickListener {
hideStopOrBusBottomSheet()
}
Log.d(DEBUG_TAG, "Fragment View Created!")
//TODO: Reshow last open stop when switching back to the map fragment
return rootView
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//observe change in source of the live positions
livePositionsViewModel.useMQTTPositionsLiveData.observe(viewLifecycleOwner){ useMQTT->
//Log.d(DEBUG_TAG, "Changed MQTT positions, now have to use MQTT: $useMQTT")
if (showBusLayer && isResumed) {
//Log.d(DEBUG_TAG, "Deciding to switch, the current source is using MQTT: $usingMQTTPositions")
if(useMQTT!=usingMQTTPositions){
// we have to switch
val clearPos = PreferenceManager.getDefaultSharedPreferences(requireContext()).getBoolean("positions_clear_on_switch_pref", true)
livePositionsViewModel.clearOldPositionsUpdates()
if(useMQTT){
//switching to MQTT, the GTFS positions are disabled automatically
livePositionsViewModel.requestMatoPosUpdates(MQTTMatoClient.LINES_ALL)
} else{
//switching to GTFS RT: stop Mato, launch first request
livePositionsViewModel.stopMatoUpdates()
livePositionsViewModel.requestGTFSUpdates()
}
Log.d(DEBUG_TAG, "Should clear positions: $clearPos")
if (clearPos) {
livePositionsViewModel.clearAllPositions()
//force clear of the viewed data
if(!vehShowing.isNullOrEmpty()) hideStopOrBusBottomSheet()
clearAllBusPositionsInMap()
}
}
}
usingMQTTPositions = useMQTT
}
mapStateViewModel.locationUserActive.observe(viewLifecycleOwner){
setLocationIconEnabled(it)}
mapStateViewModel.followingUserPosition.observe(viewLifecycleOwner){ updateFollowingIcon(it)}
observeStatusLivePositions()
}
- /**
- * This method sets up the map and the layers
- */
- override fun onMapReady(mapReady: MapLibreMap) {
- this.map = mapReady
- val context = requireContext()
- val mjson = MapLibreStyles.getJsonStyleFromAsset(context, PreferencesHolder.getMapLibreStyleFile(context))
-
- val builder = Style.Builder().fromJson(mjson!!)
-
- mapReady.setStyle(builder) { style ->
- mapStyle = style
- //setupLayers(style)
- addImagesStyle(style)
-
- //init stop layer with this
- val stopsInCache = stopsViewModel.stopsToShow.value
- if(stopsInCache.isNullOrEmpty()) initStopsLayer(style, null)
- else displayStops(stopsInCache)
+ override fun onStyleLoaded(mapReady: MapLibreMap,style: Style) {
+ //init stop layer with this
+ val stopsInCache = stopsViewModel.stopsToShow.value
+ if(stopsInCache.isNullOrEmpty()) initStopsLayer(style, null)
+ else displayStops(stopsInCache)
- if(showBusLayer) setupBusLayer(style, withLabels = true, busIconsScale = 1.2f)
-
- // Start observing data now that everything is set up
- observeStops()
-
- checkInitMapLocation(mapReady,style, context)
- }
+ if(showBusLayer) setupBusLayer(style, withLabels = true, busIconsScale = 1.2f)
+ checkInitMapLocation(mapReady,style, requireContext())
+ }
+ override fun setupMapListenersOnInit(mapReady: MapLibreMap) {
mapReady.addOnCameraIdleListener {
map?.let {
val newBbox = it.projection.visibleRegion.latLngBounds
stopsViewModel.loadStopsInLatLngBounds(newBbox)
lastBBox = newBbox
}
}
mapReady.addOnCameraMoveStartedListener { v->
if(v== MapLibreMap.OnCameraMoveStartedListener.REASON_API_GESTURE){
//the user is moving the map
//isUserMovingCamera = true
updateFollowingIcon(false)
}
}
mapReady.addOnMapClickListener { point ->
- onMapClickReact(point)
+ onMapClickReact(point)
}
- // we start requesting the bus positions now
- observeBusPositionUpdates()
+ }
- //Restoring data
+ override fun onMapLibreInitialized(mapReady: MapLibreMap) {
+ // Start observing data now that everything is set up
+ observeStops()
+ observeBusPositionUpdates()
if (initialStopToShow!=null && initialStopToShow?.hasCoords() == true){
val s = initialStopToShow!!
if(s.hasCoords()){
mapReady.cameraPosition = CameraPosition.Builder().target(
LatLng(s.latitude!!, s.longitude!!)
).zoom(DEFAULT_ZOOM).build()
}
restoredMapCamera.set(true)
} else{
var boundsRestored = false
//restore the map state here
map?.let{
boundsRestored = mapStateViewModel.restoreMapState(it)
- mapStateViewModel.lastOpenStopID.value?.let{ sID->
- val s= stopsViewModel.getStopByID(sID)
- if (s==null) {
- if(sID.isNotEmpty())
- Log.w(DEBUG_TAG,"Wanted to open stop $sID in map but it was not loaded!")
- }
- else{
- openStopInBottomSheet(s) }
- }
+ mapStateViewModel.lastOpenStopID.value?.let{ sID->
+ val s= stopsViewModel.getStopByID(sID)
+ if (s==null) {
+ if(sID.isNotEmpty())
+ Log.w(DEBUG_TAG,"Wanted to open stop $sID in map but it was not loaded!")
+ }
+ else{
+ openStopInBottomSheet(s) }
+ }
}
if(!boundsRestored){
// we have not restored the bounds, open normally in target location
val lastLoc = mapStateViewModel.userLocationToShow
val defaultLoc = LatLng(DEFAULT_CENTER_LAT, DEFAULT_CENTER_LON)
val proposedLoc = lastLoc?.let{ LatLng(lastLoc.latitude, lastLoc.longitude)}
val targetLoc = if(proposedLoc == null || proposedLoc.distanceTo(defaultLoc) > MAX_DIST_KM*1000)
- defaultLoc
- else proposedLoc
+ defaultLoc
+ else proposedLoc
mapReady.cameraPosition = CameraPosition.Builder().target(targetLoc).zoom(DEFAULT_ZOOM).build()
}
restoredMapCamera.set(boundsRestored)
-
-
}
- mapInitialized = true
-
- //pendingLocationActivation = true
- //positionRequestLauncher.launch(Permissions.LOCATION_PERMISSIONS)
}
private fun onMapClickReact(point: LatLng): Boolean{
map?.let { mapReady ->
val screenPoint = mapReady.projection.toScreenLocation(point)
val stopsFeatures = mapReady.queryRenderedFeatures(screenPoint, STOPS_LAYER_ID)
val busNearby = mapReady.queryRenderedFeatures(screenPoint, BUSES_LAYER_ID)
Log.d(DEBUG_TAG, "Clicked on stops: $stopsFeatures \n and buses: $busNearby")
if (stopsFeatures.isNotEmpty()) {
val feature = stopsFeatures[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)
Log.d(DEBUG_TAG, "Decided click is on stop with id $id : $stop")
stop?.let { newstop ->
val sameStopClicked = shownStopInBottomSheet?.let { newstop.ID==it.ID } ?: false
Log.d(DEBUG_TAG, "Hiding clicked stop: $sameStopClicked")
if (isBottomSheetShowing()) {
hideStopOrBusBottomSheet()
}
if(!sameStopClicked){
openStopInBottomSheet(newstop)
//isBottomSheetShowing = true
//move camera
if (newstop.latitude != null && newstop.longitude != null)
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")
if (isBottomSheetShowing()) hideStopOrBusBottomSheet()
showVehicleTripInBottomSheet(vehid)
//move camera to center on vehicle
updatesByVehDict[vehid]?.let { dat ->
mapReady.animateCamera(
CameraUpdateFactory.newLatLng(LatLng(dat.posUpdate.latitude, dat.posUpdate.longitude)), 750
)
}
return true
}
}
return false
}
override fun showOpenStopWithSymbolLayer(): Boolean {
return false
}
override fun hideStopOrBusBottomSheet(){
if (shownStopInBottomSheet?.ID == initialStopToShow?.ID){
initialStopToShow = null
}
super.hideStopOrBusBottomSheet()
}
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()
}
override fun onResume() {
super.onResume()
//mapView.onResume() handled in GeneralMapLibreFragment
if(showBusLayer) {
//first, clean up all the old positions
livePositionsViewModel.clearOldPositionsUpdates()
if (livePositionsViewModel.useMQTTPositionsLiveData.value!!){
livePositionsViewModel.requestMatoPosUpdates(MQTTMatoClient.LINES_ALL)
usingMQTTPositions = true
}
else {
livePositionsViewModel.requestGTFSUpdates()
usingMQTTPositions = false
}
livePositionsViewModel.isLastWorkResultGood.observe(this) { d: Boolean ->
Log.d(
DEBUG_TAG, "Last trip download result is $d"
)
}
livePositionsViewModel.tripsGtfsIDsToQuery.observe(this) { dat: List<String> ->
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()
Log.d(DEBUG_TAG, "Fragment paused")
map?.let{
//if map is initialized
mapStateViewModel.saveMapState(it)
}
try{
//save last location
map?.locationComponent?.let{
if(locationInitialized && it.isLocationComponentActivated){
stopsViewModel.lastUserLocation = it.lastKnownLocation
}
}
}catch (e: Exception){
Log.w(DEBUG_TAG, "Cannot save lastKnowLocation from map location component,error: ${e.message}")
}
mapStateViewModel.lastOpenStopID.postValue(shownStopInBottomSheet?.ID)
if (livePositionsViewModel.useMQTTPositionsLiveData.value!!) livePositionsViewModel.stopMatoUpdates()
}
override fun onStop() {
super.onStop()
Log.d(DEBUG_TAG, "Fragment stopped!")
}
override fun onMapDestroy() {
mapStyle.removeLayer(STOPS_LAYER_ID)
mapStyle.removeSource(STOPS_SOURCE_ID)
mapStyle.removeLayer(BUSES_LAYER_ID)
mapStyle.removeSource(BUSES_SOURCE_ID)
}
override fun getBaseViewForSnackBar(): View? {
return mapView
}
private fun showVehicleTripInBottomSheet(veh: String) {
val data = updatesByVehDict[veh] ?: return
super.showVehicleTripInBottomSheet(veh) { patternCode, _ ->
map?.let { mapStateViewModel.saveMapState(it) }
fragmentListener?.openLineFromVehicle(
data.posUpdate.getLineGTFSFormat(),
patternCode,
mapStateViewModel.savedCameraState?.toBundle()
)
}
}
private fun hasToShowInitialStop(): Boolean{
return if(initialStopToShow==null) false
else !initialStopShown
}
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 && (s.ID in stopsShowing.map { it.ID })) {
val stopToShow = stopsShowing.first { it.ID == s.ID }
openStopInBottomSheet(stopToShow)
initialStopShown = true
}
}
}
}
/**
* Add the stops to the layers
*/
private fun displayStops(stops: List<Stop>?) {
if (stops.isNullOrEmpty()) return
if (stops.size==lastStopsSizeShown){
Log.d(DEBUG_TAG, "Not updating, have same number of stops")
return
}
/*if(stops.size> lastStopsSizeShown){
stopsRedrawnTimes = 0
} else{
stopsRedrawnTimes++
}
*/
val features = ArrayList<Feature>()//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,"Displaying ${features.size} stops")
// 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
}
}
// --------------- BUS LOCATIONS STUFF --------------------------
/**
* Start requesting position updates
*/
private fun observeBusPositionUpdates() {
livePositionsViewModel.updatesWithTripAndPatterns.observe(viewLifecycleOwner) { data: HashMap<String, Pair<LivePositionUpdate, TripAndPatternWithStops?>> ->
Log.d(
DEBUG_TAG,
"Have " + data.size + " trip updates, has Map start finished: $mapInitialized"
)
if (mapInitialized) updateBusPositionsInMap(data, hasVehicleTracking = true) { veh ->
showVehicleTripInBottomSheet(veh)
}
if (!isDetached && !livePositionsViewModel.useMQTTPositionsLiveData.value!!) livePositionsViewModel.requestDelayedGTFSUpdates(
3000
)
}
}
// ------ LOCATION STUFF -----
@SuppressLint("MissingPermission")
override fun onMapLocationComponentInitialized() {
//locationComponent.cameraMode = CameraMode.TRACKING
-
- locationComponent.renderMode = RenderMode.COMPASS
- locationComponent.locationEngine?.apply{
- // this is only called once
- getLastLocation(object : LocationEngineCallback<LocationEngineResult> {
- override fun onSuccess(res: LocationEngineResult?) {
- Log.d(DEBUG_TAG, "Got the last location, ${res?.lastLocation}")
- res?.lastLocation?.let { loc ->
- if(mapInitialized){
- val newLocation = LatLng(loc.latitude, loc.longitude)
- //center the position only if it is close enough and we are not showing a stop
- if(!showingBusStopOrVehicle() && newLocation.distanceTo(DEFAULT_LATLNG) < MAX_DIST_KM * 1000)
- map?.cameraPosition = CameraPosition.Builder().target(LatLng(loc.latitude, loc.longitude)).build()
+ locationComponent?.let { locComp ->
+
+ locComp.renderMode = RenderMode.COMPASS
+ locComp.locationEngine?.apply {
+ // this is only called once
+ getLastLocation(object : LocationEngineCallback<LocationEngineResult> {
+ override fun onSuccess(res: LocationEngineResult?) {
+ Log.d(DEBUG_TAG, "Got the last location, ${res?.lastLocation}")
+ res?.lastLocation?.let { loc ->
+ if (mapInitialized) {
+ val newLocation = LatLng(loc.latitude, loc.longitude)
+ //center the position only if it is close enough and we are not showing a stop
+ if (!showingBusStopOrVehicle() && newLocation.distanceTo(DEFAULT_LATLNG) < MAX_DIST_KM * 1000)
+ map?.cameraPosition =
+ CameraPosition.Builder().target(LatLng(loc.latitude, loc.longitude)).build()
+ } else
+ mapStateViewModel.userLocationToShow = loc
}
- else
- mapStateViewModel.userLocationToShow = loc
}
- }
- override fun onFailure(p0: java.lang.Exception) {
- if( p0 is MapLibreLocationEngine.NoLocationException)
+ override fun onFailure(p0: java.lang.Exception) {
+ if (p0 is MapLibreLocationEngine.NoLocationException)
Log.d(DEBUG_TAG, "Cannot find location: ${p0.message}")
- else
- Log.w(DEBUG_TAG, "Failed to get the last location, error: ${p0.message}",)
- }
+ else
+ Log.w(DEBUG_TAG, "Failed to get the last location, error: ${p0.message}",)
+ }
+
+ })
+ }
- })
}
- if(locationEnabledOnDevice){
- if(!showingBusStopOrVehicle() && !hasToShowInitialStop())
+ if (locationEnabledOnDevice) {
+ if (!showingBusStopOrVehicle() && !hasToShowInitialStop())
setFollowUserLocation(true)
}
}
override fun onMapLocationEnabled(active: Boolean) {
//Extra stuff to do
// this check should always pass
if(!(showingBusStopOrVehicle()) || hasToShowInitialStop())
setFollowUserLocation(active)
}
@SuppressLint("MissingPermission")
override fun onFirstReceivedLocation(location: Location) {
val it = location
//val notShowingStopOrVehicle = s//vehShowing.isNullOrEmpty() && shownStopInBottomSheet != null
if(locationInitialized && !receivedFirstLocation) {
//only zoom if the user position is close enough to the center
val newPoint = LatLng(it.latitude, it.longitude)
if(newPoint.distanceTo(DEFAULT_LATLNG) > MAX_DIST_KM * 1000){
//show Toast
if(!shownToastNoPosition) context?.let{ c->
Toast.makeText(c, R.string.too_far_not_showing_location, Toast.LENGTH_LONG).show()
shownToastNoPosition = true
}
setLocationComponentEnabled(false)
//Update UI Status
mapStateViewModel.locationUserActive.value = false
mapStateViewModel.followingUserPosition.value = false
} else if(!(showingBusStopOrVehicle()||hasToShowInitialStop())) {
map?.apply {
animateCamera(
CameraUpdateFactory.newCameraPosition(
CameraPosition.Builder().target(LatLng(location.latitude, location.longitude)).build()
),
1000
)
setLocationComponentEnabled(true)
locationComponent.cameraMode = CameraMode.TRACKING
mapStateViewModel.locationUserActive.value = true
}
setFollowUserLocation(true)
} else{
map?.apply {
setLocationComponentEnabled(true)
}
}
}
else{
//check for this is when the map is used
mapStateViewModel.userLocationToShow = location
}
}
override fun setLocationIconEnabled(enabled: Boolean){
if (enabled)
userLocationButton.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.location_circlew_red))
else
userLocationButton.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.location_circlew_grey))
}
private fun updateFollowingIcon(enabled: Boolean){
if(enabled)
followUserButton.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.walk_circle_active))
else
followUserButton.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.walk_circle_inactive))
}
/**
* This sets both the status on the component if it has been activated and the icon in the Fragment
*/
private fun setFollowUserLocation(enabled: Boolean){
if(locationInitialized) {
- if (enabled)
- locationComponent.cameraMode = CameraMode.TRACKING
- else locationComponent.cameraMode = CameraMode.NONE
+ locationComponent?.let{
+ it.cameraMode = if(enabled) CameraMode.TRACKING else CameraMode.NONE
+ }
}
//update the icon by updating the livedata
mapStateViewModel.followingUserPosition.value = enabled
}
companion object {
private const val STOPS_SOURCE_ID = "stops-source"
private const val STOPS_LAYER_ID = "stops-layer"
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 val DEFAULT_ZOOM = 14.3
private const val POSITION_FOUND_ZOOM = 16.5
private const val NO_POSITION_ZOOM = 17.1
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/fragments/NearbyStopsFragment.kt b/app/src/main/java/it/reyboz/bustorino/fragments/NearbyStopsFragment.kt
index 2ea66e5..9d8f6b3 100644
--- a/app/src/main/java/it/reyboz/bustorino/fragments/NearbyStopsFragment.kt
+++ b/app/src/main/java/it/reyboz/bustorino/fragments/NearbyStopsFragment.kt
@@ -1,860 +1,860 @@
/*
BusTO - Fragments components
Copyright (C) 2018 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 <http://www.gnu.org/licenses/>.
*/
package it.reyboz.bustorino.fragments
import android.content.Context
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.widget.ProgressBar
import android.widget.TextView
import androidx.appcompat.widget.AppCompatButton
import androidx.fragment.app.viewModels
import androidx.preference.PreferenceManager
import androidx.recyclerview.widget.RecyclerView
import androidx.work.WorkInfo
import com.google.android.material.button.MaterialButton
import it.reyboz.bustorino.BuildConfig
import it.reyboz.bustorino.R
import it.reyboz.bustorino.adapters.ArrivalsStopAdapter
import it.reyboz.bustorino.adapters.StopNearbyAdapter
import it.reyboz.bustorino.backend.*
import it.reyboz.bustorino.data.DatabaseUpdate
import it.reyboz.bustorino.middleware.AutoFitGridLayoutManager
import it.reyboz.bustorino.middleware.FusedNativeLocationProvider
import it.reyboz.bustorino.middleware.FusedNativeLocationProvider.LocationUpdateListener
-import it.reyboz.bustorino.util.Permissions
-import it.reyboz.bustorino.util.Permissions.Companion.bothLocationPermissionsGranted
+import it.reyboz.bustorino.util.PermissionsHelper
+import it.reyboz.bustorino.util.PermissionsHelper.Companion.bothLocationPermissionsGranted
import it.reyboz.bustorino.util.StopSorterByDistance
import it.reyboz.bustorino.viewmodels.NearbyStopsViewModel
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
class NearbyStopsFragment : ScreenBaseFragment() {
override fun getBaseViewForSnackBar(): View? {
return null
}
enum class FragType(val num: Int) {
STOPS(1), ARRIVALS(2);
companion object {
@JvmStatic
fun fromNum(i: Int): FragType {
when (i) {
1 -> return STOPS
2 -> return ARRIVALS
else -> throw IllegalArgumentException("type not recognized")
}
}
}
}
private enum class LocationShowingStatus {
SEARCHING, LOCATION_FOUND, DISABLED, NO_PERMISSION //NO_STOPS_NEARBY
}
private var mListener: FragmentListenerMain? = null
private var fragmentType = FragType.STOPS
private lateinit var gridRecyclerView: RecyclerView
private var dataAdapter: StopNearbyAdapter? = null
private var gridLayoutManager: AutoFitGridLayoutManager? = null
private var lastPosition: GPSPoint? = null
private var circlingProgressBar: ProgressBar? = null
private lateinit var flatProgressBar: ProgressBar
//protected SharedPreferences globalSharedPref;
//private SharedPreferences.OnSharedPreferenceChangeListener preferenceChangeListener;
private var messageTextView: TextView? = null
private lateinit var enableLocationButton : MaterialButton
private var titleTextView: TextView? = null
private var loadingTextView: TextView? = null
private var scrollListener: CommonScrollListener? = null
private var switchButton: AppCompatButton? = null
private var firstLocForStops = true
private var firstLocForArrivals = true
private var stopsMaxDistance = -3
private var stopsMinNumber = -1
//These are useful for the case of nearby arrivals
private var arrivalsStopAdapter: ArrivalsStopAdapter? = null
private var currentNearbyStops: ArrayList<Stop>? = null
private var showingStatus = LocationShowingStatus.NO_PERMISSION
private var isLocationEnabled = false
private var dataShownInAdapter = AtomicBoolean(false)
private var noDataMessageId = R.string.no_stops_nearby
private var loadingDataMessageId = R.string.position_searching_message
private val locationUpdateListener: LocationUpdateListener = object : LocationUpdateListener {
override fun onLocationUpdate(location: Location) {
if (location.getAccuracy() < MIN_ACCURACY) {
lastPosition = GPSPoint(location.getLatitude(), location.getLongitude())
viewModel.setLastLocation(location)
} else{
Log.d(DEBUG_TAG, "Refusing location ${location.latitude},${location.longitude} because accuracy: ${location.accuracy} > MIN_ACCURACY=$MIN_ACCURACY")
}
}
override fun onFusedStatusChanged(isEnabled: Boolean) {
Log.d(DEBUG_TAG, "Location provider is enabled: " + isEnabled)
isLocationEnabled = isEnabled
if(!dataShownInAdapter.get())
if (isEnabled) {
setShowingStatus(LocationShowingStatus.SEARCHING)
} else {
setShowingStatus(LocationShowingStatus.DISABLED)
}
}
}
private val locationPermissionLauncher = getPositionRequestLauncher(){ granted ->
startLocationUpdatesByType()
setShowingStatus(LocationShowingStatus.SEARCHING)
}
// Two different settings for the location provider
private val locationOptionsArrivals = FusedNativeLocationProvider.Options(5 * 1000L, 25f)
private val locationOptionsStops = FusedNativeLocationProvider.Options(1000L, 5f)
private var locationProvider: FusedNativeLocationProvider? = null
/*private val arrivalsListener: ArrivalsListener = object : ArrivalsListener {
override fun setProgress(completedRequests: Int, pendingRequests: Int) {
if (pendingRequests == 0) {
flatProgressBar.setIndeterminate(true)
flatProgressBar.setVisibility(View.GONE)
} else {
flatProgressBar.setIndeterminate(false)
flatProgressBar.progress = completedRequests
}
}
/*override fun onAllRequestsCancelled() {
if (flatProgressBar != null) flatProgressBar!!.setVisibility(View.GONE)
}
*/
override fun showCompletedArrivals(completedPalinas: ArrayList<Palina>) {
showArrivalsInRecycler(completedPalinas)
}
}
*/
//ViewModel
private val viewModel : NearbyStopsViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let{
setFragmentType(FragType.fromNum(it.getInt(FRAGMENT_TYPE_KEY)))
}
//locManager = (LocationManager) requireContext().getSystemService(Context.LOCATION_SERVICE);
//fragmentLocationListener = new FragmentLocationListener();
if (getContext() != null) {
//globalSharedPref = getContext().getSharedPreferences(getString(R.string.mainSharedPreferences), Context.MODE_PRIVATE);
//globalSharedPref.registerOnSharedPreferenceChangeListener(preferenceChangeListener);
}
//NearbyArrivalsDownloader nearbyArrivalsDownloader = new NearbyArrivalsDownloader(getContext().getApplicationContext(), arrivalsListener);
locationProvider = FusedNativeLocationProvider(requireContext())
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
val context = requireContext()
val root = inflater.inflate(R.layout.fragment_nearby_stops, container, false)
gridRecyclerView = root.findViewById<RecyclerView>(R.id.stopGridRecyclerView)
gridLayoutManager = AutoFitGridLayoutManager(
context.getApplicationContext(),
utils.convertDipToPixels(context, COLUMN_WIDTH_DP.toFloat()).toInt()
)
gridRecyclerView.setLayoutManager(gridLayoutManager)
gridRecyclerView.setHasFixedSize(false)
circlingProgressBar = root.findViewById<ProgressBar>(R.id.circularProgressBar)
flatProgressBar = root.findViewById(R.id.horizontalProgressBar)
messageTextView = root.findViewById<TextView>(R.id.messageTextView)
enableLocationButton = root.findViewById(R.id.grantLocationButton)
titleTextView = root.findViewById<TextView>(R.id.titleTextView)
loadingTextView = root.findViewById<TextView>(R.id.positionLoadingTextView)
switchButton = root.findViewById<AppCompatButton>(R.id.switchButton)
scrollListener = CommonScrollListener(mListener, false)
switchButton!!.setOnClickListener { v: View? -> switchFragmentType() }
if (BuildConfig.DEBUG) Log.d(DEBUG_TAG, "onCreateView")
val appContext = requireContext().applicationContext
DatabaseUpdate.watchUpdateWorkStatus(context, this){ workInfos ->
if (workInfos.isEmpty()) {
viewModel.setDBUpdateRunning(false)
return@watchUpdateWorkStatus
}
val wi = workInfos.get(0)
if (wi.state == WorkInfo.State.RUNNING && locationProvider!!.isRunning()) {
locationProvider!!.stopUpdates()
viewModel.setDBUpdateRunning(true)
} else {
//start the request
checkPermissionLocationStart()
viewModel.setDBUpdateRunning(false)
//actually restart request
}
}
//add location listener
locationProvider!!.addListener(locationUpdateListener)
enableLocationButton.setOnClickListener {
- locationPermissionLauncher.launch(Permissions.LOCATION_PERMISSIONS)
+ locationPermissionLauncher.launch(PermissionsHelper.LOCATION_PERMISSIONS)
}
return root
}
private fun checkPermissionLocationStart(){
Log.d(DEBUG_TAG, "Check permission and start location updates")
if (bothLocationPermissionsGranted(requireContext())) {
if (!locationProvider!!.isRunning()) {
startLocationUpdatesByType()
setShowingStatus(LocationShowingStatus.SEARCHING)
} else{
Log.w(DEBUG_TAG, "Asked to check and start location updates, but provider is already running")
}
} else {
setShowingStatus(LocationShowingStatus.NO_PERMISSION)
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
gridRecyclerView.setVisibility(View.INVISIBLE)
gridRecyclerView.addOnScrollListener(scrollListener!!)
//mListener?.readyGUIfor(FragmentKind.NEARBY_STOPS)
//observe the livedata
viewModel.stopsAtDistance.observe(getViewLifecycleOwner()) {stops ->
Log.d(DEBUG_TAG, "Received " + stops.size + " stops nearby")
var distance = viewModel.distanceMtLiveData.getValue()
if (distance == null) {
distance = 40
}
if ((stops.size < stopsMinNumber && distance <= stopsMaxDistance)) {
viewModel.setDistance(distance + 50)
//viewModel.requestStopsAtDistance(distance, true);
//Log.d(DEBUG_TAG, "Doubling distance now!");
return@observe // THIS WORKS AS AN `else`
}
displayStopsOrRequestArrivals(stops)
}
viewModel.locationLiveData.observe(getViewLifecycleOwner()) {loc ->
if(loc!=null){
setShowingStatus(LocationShowingStatus.LOCATION_FOUND)
}
//the stops are updated manually
}
viewModel.downloadingArrivals.observe(viewLifecycleOwner){ running ->
flatProgressBar.isIndeterminate = true
if(!running) flatProgressBar.visibility = View.GONE
else flatProgressBar.visibility = View.VISIBLE
}
/*viewModel.progressPerc.observe(viewLifecycleOwner){ progress ->
flatProgressBar.isIndeterminate = false
flatProgressBar.progress = progress
flatProgressBar.max = 100
if (progress<100){
flatProgressBar.visibility = View.VISIBLE
}
}
*/
viewModel.arrivalsDecoupled.observe(viewLifecycleOwner){ stoprouteList ->
if (getContext() == null) {
Log.e(DEBUG_TAG, "Trying to show arrivals in Recycler but we're not attached")
return@observe
}
showArrivals(stoprouteList)
//arrivalsStopAdapter.notifyDataSetChanged();
//showRecyclerHidingLoadMessage()
//if (mListener != null) mListener!!.readyGUIfor(FragmentKind.NEARBY_ARRIVALS)
}
//added
//checkPermissionLocationStart()
}
private fun displayStopsOrRequestArrivals(stops: ArrayList<Stop>){
if (!stops.isEmpty()) {
currentNearbyStops = stops
//displayStopsOrLaunchArrivalsRequest(stops, lastPosition)
viewModel.locationLiveData.value?.let{loc ->
when(fragmentType){
FragType.STOPS->{
lastPosition?.let{loc ->
Collections.sort(stops, StopSorterByDistance(loc))
showStopsInRecycler(stops,loc)
}
}
FragType.ARRIVALS -> {
lastPosition?.let{
Collections.sort(stops, StopSorterByDistance(loc))
}
viewModel.requestArrivalsForStops(stops)
}
}
}
} else{
showNoStopsMessage()
viewModel.cancelAllArrivalsRequests()
}
}
private fun showArrivals(stoprouteList: ArrayList<RouteWithStop>){
val context = requireContext()
if (firstLocForArrivals) {
mListener?.let{
lastPosition?.let{ pos ->
arrivalsStopAdapter = ArrivalsStopAdapter(stoprouteList, it, context, pos)
gridRecyclerView.setAdapter(arrivalsStopAdapter)
firstLocForArrivals = false
}
}
} else {
lastPosition?.let{ pos ->
arrivalsStopAdapter?.setRoutesPairListAndPosition(stoprouteList, pos)
}
}
dataShownInAdapter.set(true)
}
/**
* Internal bit used to start location updates
*/
private fun startLocationUpdatesByType() {
when (fragmentType) {
FragType.STOPS -> locationProvider!!.startUpdates(locationOptionsStops)
FragType.ARRIVALS -> locationProvider!!.startUpdates(locationOptionsArrivals)
}
}
/**
* Use this method to set the fragment type
* @param type the type, TYPE_ARRIVALS or TYPE_STOPS
*/
private fun setFragmentType(type: FragType) {
val isChanged = fragmentType != type
this.fragmentType = type
if (isChanged) {
startLocationUpdatesByType()
}
}
/**
* Set the location in the view model if it is good
* @param location new location
*/
/*
private fun updateLocationViewModel(location: Location, accuracy: Float = 150f) {
}
*/
private fun setShowingStatus(newStatus: LocationShowingStatus) {
var newStatus = newStatus
if (newStatus == showingStatus) {
return
}
if (BuildConfig.DEBUG) Log.d(DEBUG_TAG, "Changing showing status from $showingStatus to $newStatus")
if (!isLocationEnabled && newStatus != LocationShowingStatus.NO_PERMISSION) {
Log.d(DEBUG_TAG, "asked to show status: $newStatus but the position is disabled")
newStatus = LocationShowingStatus.DISABLED
}
when (newStatus) {
LocationShowingStatus.LOCATION_FOUND -> {
circlingProgressBar!!.setVisibility(View.GONE)
loadingTextView!!.setVisibility(View.GONE)
gridRecyclerView.setVisibility(View.VISIBLE)
messageTextView!!.setVisibility(View.GONE)
enableLocationButton.setVisibility(View.GONE)
}
LocationShowingStatus.NO_PERMISSION -> {
circlingProgressBar?.setVisibility(View.GONE)
flatProgressBar.setVisibility(View.GONE)
loadingTextView?.setVisibility(View.GONE)
messageTextView?.setText(R.string.enable_position_message_nearby)
messageTextView?.setVisibility(View.VISIBLE)
enableLocationButton.setVisibility(View.VISIBLE)
}
LocationShowingStatus.DISABLED -> {
//if (showingStatus== LocationShowingStatus.SEARCHING){
circlingProgressBar!!.setVisibility(View.GONE)
loadingTextView!!.setVisibility(View.GONE)
flatProgressBar.setVisibility(View.GONE)
//}
messageTextView!!.setText(R.string.enable_location_message)
messageTextView!!.setVisibility(View.VISIBLE)
enableLocationButton.setVisibility(View.GONE)
}
LocationShowingStatus.SEARCHING -> {
circlingProgressBar!!.setVisibility(View.VISIBLE)
flatProgressBar.setVisibility(View.GONE)
gridRecyclerView.setVisibility(View.GONE)
messageTextView!!.setVisibility(View.GONE)
enableLocationButton.setVisibility(View.GONE)
loadingTextView?.apply {
setText(loadingDataMessageId)
visibility = View.VISIBLE
}
}
}
showingStatus = newStatus
}
override fun onAttach(context: Context) {
super.onAttach(context)
if (context is FragmentListenerMain) {
mListener = context as FragmentListenerMain
} else {
throw RuntimeException(
context
.toString() + " must implement OnFragmentInteractionListener"
)
}
Log.d(DEBUG_TAG, "OnAttach called")
//viewModel = ViewModelProvider(this).get<NearbyStopsViewModel?>(NearbyStopsViewModel::class.java)
}
override fun onPause() {
super.onPause()
//gridRecyclerView.setAdapter(null)
Log.d(DEBUG_TAG, "On paused called")
locationProvider!!.stopUpdates()
}
override fun onResume() {
super.onResume()
//fix view if we were showing the stops or the arrivals
loadPreferencesStops()
setGuiForFragmentType(fragmentType)
//if(lastPosition == null){
viewModel.locationLiveData.value?.let{loc -> lastPosition = loc }
//}
if(bothLocationPermissionsGranted(requireContext())){
locationProvider?.apply {
if(isLocationEnabled()){
//location is enabled, start updates
startLocationUpdatesByType()
if(lastPosition == null){
setShowingStatus(LocationShowingStatus.SEARCHING)
}
} else{
setShowingStatus(LocationShowingStatus.DISABLED)
}
}
} else{
setShowingStatus(LocationShowingStatus.NO_PERMISSION)
}
//setupDataAndLayoutByFragmentType()
mListener!!.enableRefreshLayout(false)
if(fragmentType == FragType.ARRIVALS){
viewModel.arrivalsDecoupled.value?.let{
//re-do the adapter
firstLocForArrivals = true
showArrivals(it)
}
} else if(fragmentType == FragType.STOPS) {
viewModel.stopsAtDistance.value?.let {
//remake the adapter
firstLocForStops = true
displayStopsOrRequestArrivals(it)
}
}
/*
when (fragmentType) {
FragType.STOPS -> if (dataAdapter != null) {
//gridRecyclerView.setAdapter(dataAdapter);
circlingProgressBar!!.setVisibility(View.GONE)
loadingTextView!!.setVisibility(View.GONE)
}
FragType.ARRIVALS -> if (arrivalsStopAdapter != null) {
//gridRecyclerView.setAdapter(arrivalsStopAdapter);
circlingProgressBar!!.setVisibility(View.GONE)
loadingTextView!!.setVisibility(View.GONE)
}
}
*/
Log.d(DEBUG_TAG, "OnResume called")
if (getContext() == null) {
Log.e(DEBUG_TAG, "NULL CONTEXT, everything is going to crash now")
stopsMinNumber = 5
stopsMaxDistance = 600
}
//Re-read preferences
}
private fun loadPreferencesStops(){
val shpr = PreferenceManager.getDefaultSharedPreferences(requireContext().getApplicationContext())
//For some reason, they are all saved as strings
stopsMaxDistance = shpr.getInt(getString(R.string.pref_key_radius_recents), 600)
var isMinStopInt = true
try {
stopsMinNumber = shpr.getInt(getString(R.string.pref_key_num_recents), 5)
} catch (ex: ClassCastException) {
isMinStopInt = false
}
if (!isMinStopInt) try {
stopsMinNumber = shpr.getString(getString(R.string.pref_key_num_recents), "5")!!.toInt()
} catch (ex: NumberFormatException) {
stopsMinNumber = 5
}
if (BuildConfig.DEBUG) Log.d(
DEBUG_TAG,
"Max distance for stops: $stopsMaxDistance, Min number of stops: $stopsMinNumber"
)
}
override fun onDetach() {
super.onDetach()
mListener = null
//if (arrivalsManager != null) arrivalsManager!!.cancelAllRequests()
}
override fun onStart() {
super.onStart()
if(BuildConfig.DEBUG) Log.d(DEBUG_TAG, "onStart called")
//checkPermissionLocationStart()
}
/**
* Display the stops, or run new set of requests for arrivals
*/
/*private fun displayStopsOrLaunchArrivalsRequest(stops: ArrayList<Stop>, location: GPSPoint) {
if (stops.isEmpty()) {
setNoStopsLayout()
return
}
//quick trial to hopefully always get the stops in the correct order
when (fragment_type) {
FragType.STOPS -> {
setShowingStatus(LocationShowingStatus.STOPS_FOUND)
showStopsInRecycler(stops, location)
}
FragType.ARRIVALS -> {
viewModel.requestArrivalsForStops(stops)
//setShowingStatus(LocationShowingStatus.SEARCHING)
viewModel.arrivalsDecoupled.value?.let{
}
}
}
}
*/
/**
* Call when you need to switch the type of fragment
*/
private fun switchFragmentType() {
when (fragmentType) {
FragType.ARRIVALS -> {
viewModel.cancelAllArrivalsRequests()
setFragmentType(FragType.STOPS)
//when switching from arrivals
firstLocForStops = true
}
FragType.STOPS -> {
setFragmentType(FragType.ARRIVALS)
firstLocForArrivals = true
}
}
//now it's switched
setGuiForFragmentType(fragmentType)
viewModel.stopsAtDistance.value?.let{
//re-issue update, triggering chain
viewModel.stopsAtDistance.value = it
}
/*if(fragmentType == FragType.ARRIVALS) {
viewModel.stopsAtDistance.value?.let{
viewModel.requestArrivalsForStops(it)
}
}
*/
//
//setupDataAndLayoutByFragmentType()
}
private fun setGuiForFragmentType(fragmentType: FragType) {
when (fragmentType) {
FragType.STOPS ->{
switchButton!!.text = getString(R.string.show_arrivals)
titleTextView!!.text = getString(R.string.nearby_stops_message)
noDataMessageId = R.string.no_stops_nearby
loadingDataMessageId = R.string.position_searching_message
//switchButton?.backgroundTintList = ColorStateList.valueOf(
// ViewUtils.getColorFromTheme(requireContext(), R.attr.colorPrimaryDark))
}
FragType.ARRIVALS ->{
titleTextView!!.text = getString(R.string.nearby_arrivals_message)
switchButton!!.text = getString(R.string.show_stops)
noDataMessageId = R.string.no_stops_nearby_arrivals
loadingDataMessageId = R.string.searching_arrivals_indefinite
//switchButton?.backgroundTintList = ColorStateList.valueOf(
// ResourcesCompat.getColor(resources, R.color.light_blue_900, requireActivity().theme))
}
}
}
/**
* Prepare the views for the set fragment type
*/
/*private fun setupDataAndLayoutByFragmentType() {
var dataAvailable = false
if (fragmentType == FragType.STOPS) {
switchButton!!.text = getString(R.string.show_arrivals)
titleTextView!!.text = getString(R.string.nearby_stops_message)
viewModel.stopsAtDistance.value?.let { stops->
// if data adapter is not null set stops, otherwise
dataAdapter?.setStops(stops) ?: lastPosition?.let{ pos ->
dataAdapter = SquareStopAdapter(stops, mListener, pos)
}
Log.d(DEBUG_TAG, "Found ${stops.size} stops")
}
dataAdapter?.let{
gridRecyclerView.adapter = it
dataAvailable = true
}
mListener?.readyGUIfor(FragmentKind.NEARBY_STOPS)
} else if (fragmentType == FragType.ARRIVALS) {
titleTextView!!.text = getString(R.string.nearby_arrivals_message)
switchButton!!.text = getString(R.string.show_stops)
val arrivalsSorted = viewModel.arrivalsDecoupled.value
arrivalsSorted?.let{
arrivalsStopAdapter?.setRoutesPairListAndPosition(
it, lastPosition) ?: lastPosition?.let{pos ->
arrivalsStopAdapter = ArrivalsStopAdapter(it, mListener!!, requireContext(), pos)
}
}
arrivalsStopAdapter?.let{
gridRecyclerView.setAdapter(it)
}
mListener?.readyGUIfor(FragmentKind.NEARBY_ARRIVALS)
}
if(gridRecyclerView.adapter == null){
flatProgressBar.isIndeterminate = true
flatProgressBar.visibility = View.VISIBLE
} else{
flatProgressBar.visibility = View.GONE
flatProgressBar.isIndeterminate = false
}
}
*/
//useful methods
/**//// GUI METHODS //////// */
private fun showStopsInRecycler(stops: MutableList<Stop>, location: GPSPoint) {
// hide the progress bar
flatProgressBar.visibility = View.GONE
Collections.sort(stops, StopSorterByDistance(location))
if (dataAdapter == null) {
dataAdapter = StopNearbyAdapter(ArrayList(stops), lastPosition, false){
stop-> mListener?.requestArrivalsForStopID(stop.ID)
}
firstLocForStops = false
} else {
dataAdapter!!.setUserPosition(lastPosition)
dataAdapter!!.setStops(stops)
}
gridRecyclerView.setAdapter(dataAdapter)
if(gridRecyclerView.visibility != View.VISIBLE){
if(showingStatus == LocationShowingStatus.LOCATION_FOUND)
Log.e(DEBUG_TAG, "Visualization error: the recyclerView is not visible but location status is $showingStatus")
else{
Log.w(DEBUG_TAG, "Grid recyclerView should be visible for the stops, setting status ${LocationShowingStatus.LOCATION_FOUND}")
setShowingStatus(LocationShowingStatus.LOCATION_FOUND)
}
}
dataShownInAdapter.set(true)
//showRecyclerHidingLoadMessage();
/*if (gridRecyclerView!!.getVisibility() != View.VISIBLE) {
circlingProgressBar!!.setVisibility(View.GONE)
loadingTextView!!.setVisibility(View.GONE)
gridRecyclerView!!.setVisibility(View.VISIBLE)
}
messageTextView!!.setVisibility(View.GONE)
*/
}
/**
* Does exactly what is says on the tin
*/
/*private fun showRecyclerHidingLoadMessage() {
if (gridRecyclerView.getVisibility() != View.VISIBLE) {
circlingProgressBar!!.setVisibility(View.GONE)
loadingTextView!!.setVisibility(View.GONE)
gridRecyclerView.setVisibility(View.VISIBLE)
}
messageTextView!!.setVisibility(View.GONE)
}
*/
private fun showNoStopsMessage(){
messageTextView!!.setVisibility(View.VISIBLE)
messageTextView!!.setText(noDataMessageId)
flatProgressBar.visibility = View.GONE
circlingProgressBar!!.setVisibility(View.GONE)
loadingTextView!!.setVisibility(View.GONE)
enableLocationButton.setVisibility(View.GONE)
}
/*
* Local locationListener, to use for the GPS
*/
/*
class FragmentLocationListener implements LocationListenerCompat {
private long lastUpdateTime = -1;
public boolean isRegistered = false;
@Override
public void onLocationChanged(@NonNull Location location) {
if(viewModel==null){
return;
}
if(location.getAccuracy()<200) {
lastPosition = new GPSPoint(location.getLatitude(), location.getLongitude());
//viewModel.requestStopsAtDistance(location.getLatitude(), location.getLongitude(), distance, true);
viewModel.setLastLocation(location);
}
lastUpdateTime = System.currentTimeMillis();
//Log.d("BusTO:NearPositListen","can start request for stops: "+ !dbUpdateRunning);
}
@Override
public void onProviderEnabled(@NonNull String provider) {
Log.d(DEBUG_TAG, "Location provider "+provider+" enabled");
if(provider.equals(LocationManager.GPS_PROVIDER)){
setShowingStatus(LocationShowingStatus.SEARCHING);
}
}
@Override
public void onProviderDisabled(@NonNull String provider) {
Log.d(DEBUG_TAG, "Location provider "+provider+" disabled");
if(provider.equals(LocationManager.GPS_PROVIDER)) {
setShowingStatus(LocationShowingStatus.DISABLED);
}
}
@Override
public void onStatusChanged(@NonNull String provider, int status, @Nullable Bundle extras) {
LocationListenerCompat.super.onStatusChanged(provider, status, extras);
}
}
*/
companion object {
private const val DEBUG_TAG = "NearbyStopsFragment"
private const val FRAGMENT_TYPE_KEY = "FragmentType"
const val FRAGMENT_TAG: String = "NearbyStopsFrag"
const val COLUMN_WIDTH_DP: Int = 250
const val MIN_ACCURACY = 200.0
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
* @return A new instance of fragment NearbyStopsFragment.
*/
@JvmStatic
fun newInstance(type: FragType): NearbyStopsFragment {
//if(fragmentType != TYPE_STOPS && fragmentType != TYPE_ARRIVALS )
// throw new IllegalArgumentException("WRONG KIND OF FRAGMENT USED");
val fragment = NearbyStopsFragment()
val args = Bundle(1)
args.putInt(FRAGMENT_TYPE_KEY, type.num)
fragment.setArguments(args)
return fragment
}
}
}
diff --git a/app/src/main/java/it/reyboz/bustorino/util/Permissions.kt b/app/src/main/java/it/reyboz/bustorino/util/PermissionsHelper.kt
similarity index 90%
rename from app/src/main/java/it/reyboz/bustorino/util/Permissions.kt
rename to app/src/main/java/it/reyboz/bustorino/util/PermissionsHelper.kt
index 2dc9894..1e69ee6 100644
--- a/app/src/main/java/it/reyboz/bustorino/util/Permissions.kt
+++ b/app/src/main/java/it/reyboz/bustorino/util/PermissionsHelper.kt
@@ -1,147 +1,144 @@
package it.reyboz.bustorino.util
import android.Manifest
import android.app.Activity
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
-import android.location.Criteria
-import android.location.LocationManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import androidx.activity.result.ActivityResultLauncher
-import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityCompat.shouldShowRequestPermissionRationale
import androidx.core.content.ContextCompat
-import androidx.core.content.ContextCompat.startActivity
import it.reyboz.bustorino.R
import java.util.concurrent.atomic.AtomicInteger
-import kotlin.concurrent.atomics.AtomicInt
-class Permissions private constructor(private val appContext: Context) {
+class PermissionsHelper private constructor(private val appContext: Context) {
/*
@get:RequiresApi(api = Build.VERSION_CODES.TIRAMISU)
val notificationPermissions: Array<String>
//final static public String[] NOTIFICATION_PERMISSION={Manifest.permission.POST_NOTIFICATIONS};
get() = arrayOf<String>(Manifest.permission.POST_NOTIFICATIONS)
*/
private var askedTimesLocation = AtomicInteger(0)
-
- fun checkRequestLocationPermissions(activity: Activity, launcher: ActivityResultLauncher<Array<String>>): Boolean {
+ /**
+ * Check if we launch the permission request or not
+ */
+ fun checkRequestLocationPermissions(activity: Activity, launcher: ActivityResultLauncher<Array<String>>, maxTimes:Int = 4): Boolean {
//activity.getSharedPreferences(, Context.MODE_PRIVATE)
var launched = false
if(shouldShowRequestPermissionRationale(activity,Manifest.permission.ACCESS_FINE_LOCATION)){
Toast.makeText(activity, R.string.enable_position_message_map, Toast.LENGTH_LONG).show()
} /*else{
//cannot show the dialog anymore, go to the settings
openShowAppSettingsLocationDialog()
}
*/
val reqTimes = askedTimesLocation.getAndIncrement()
Log.d(DEBUG_TAG, "Requesting location permissions, asked ${reqTimes} times ")
- if(reqTimes > 4){
+ if(reqTimes > maxTimes){
openShowAppSettingsLocationDialog()
} else{
launcher.launch(LOCATION_PERMISSIONS)
launched = true
}
return launched
}
/**
* Show alert dialog to enable location permission
*/
fun openShowAppSettingsLocationDialog() {
val context = appContext
val builder = AlertDialog.Builder(context)
builder.setTitle(R.string.no_permission_dialog_title)
builder.setMessage(R.string.no_permission_dialog_text_location)
builder.setPositiveButton(
R.string.no_permission_dialog_open,
DialogInterface.OnClickListener { dialogInterface: DialogInterface?, i: Int ->
val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
intent.setData(Uri.fromParts("package", context.getPackageName(), null))
context.startActivity(intent)
})
builder.setNegativeButton(android.R.string.cancel, null)
builder.show()
}
fun assertLocationPermissions(con: Context, activity: Activity) {
if (!isPermissionGranted(con, Manifest.permission.ACCESS_FINE_LOCATION) ||
!isPermissionGranted(con, Manifest.permission.ACCESS_COARSE_LOCATION)
) {
ActivityCompat.requestPermissions(
activity,
arrayOf<String>(Manifest.permission.ACCESS_FINE_LOCATION),
PERMISSION_REQUEST_POSITION
)
}
}
companion object{
const val DEBUG_TAG: String = "BusTO -Permissions"
const val PERMISSION_REQUEST_POSITION: Int = 33
const val LOCATION_PERMISSION_GIVEN: String = "loc_permission"
const val STORAGE_PERMISSION_REQ: Int = 291
const val PERMISSION_OK: Int = 0
const val PERMISSION_ASKING: Int = 11
const val PERMISSION_NEG_CANNOT_ASK: Int = -3
@JvmField
val LOCATION_PERMISSIONS: Array<String> = arrayOf(
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
)
@JvmStatic
fun isPermissionGranted(con: Context, permission: String): Boolean {
return ContextCompat.checkSelfPermission(con, permission) == PackageManager.PERMISSION_GRANTED
}
@JvmStatic
fun bothLocationPermissionsGranted(con: Context): Boolean {
return isPermissionGranted(con, Manifest.permission.ACCESS_FINE_LOCATION) &&
isPermissionGranted(con, Manifest.permission.ACCESS_COARSE_LOCATION)
}
@JvmStatic
fun anyLocationPermissionsGranted(con: Context): Boolean {
return isPermissionGranted(con, Manifest.permission.ACCESS_FINE_LOCATION) ||
isPermissionGranted(con, Manifest.permission.ACCESS_COARSE_LOCATION)
}
/**
* Check if the system requires the POST_NOTIFICATION permission to send notifications
* @return true if required
*/
@JvmStatic
fun isNotificationPermissionNeeded() = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU)
@Volatile
- private var instance: Permissions? = null
+ private var instance: PermissionsHelper? = null
fun getInstance(context: Context) =
instance ?: synchronized(this) {
- instance ?: Permissions(context.applicationContext).also { instance = it }
+ instance ?: PermissionsHelper(context.applicationContext).also { instance = it }
}
}
}
diff --git a/app/src/main/java/it/reyboz/bustorino/viewmodels/MapStateViewModel.kt b/app/src/main/java/it/reyboz/bustorino/viewmodels/MapStateViewModel.kt
index dd11e50..407f904 100644
--- a/app/src/main/java/it/reyboz/bustorino/viewmodels/MapStateViewModel.kt
+++ b/app/src/main/java/it/reyboz/bustorino/viewmodels/MapStateViewModel.kt
@@ -1,54 +1,67 @@
package it.reyboz.bustorino.viewmodels
import android.location.Location
+import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import it.reyboz.bustorino.map.MapCameraState
import org.maplibre.android.camera.CameraPosition
import org.maplibre.android.geometry.LatLng
import org.maplibre.android.maps.MapLibreMap
+import java.util.concurrent.atomic.AtomicBoolean
class MapStateViewModel : ViewModel() {
var savedCameraState: MapCameraState? = null
private set
val lastOpenStopID = MutableLiveData<String>()
fun saveMapState(map: MapLibreMap){
val cp = map.cameraPosition
val newBbox = map.projection.visibleRegion.latLngBounds
val cameraState = MapCameraState(
- latitude = newBbox.center.latitude,
- longitude = newBbox.center.longitude,
+ latitude = cp.target?.latitude ?: newBbox.center.latitude,
+ longitude = cp.target?.longitude ?: newBbox.center.longitude,
zoom = cp.zoom,
bearing = cp.bearing,
tilt = cp.tilt
)
+ Log.d(DEBUG_TAG, "Saved camera state: $cameraState")
savedCameraState = cameraState
}
fun restoreMapState(map: MapLibreMap): Boolean {
return restoreMapState(map, this.savedCameraState)
}
var userLocationToShow: Location? = null
+ var mapInitOnce = AtomicBoolean(false)
val locationUserActive = MutableLiveData(false)
+ //val locationUserAvailable = MutableLiveData(false)
val followingUserPosition = MutableLiveData(false)
val locationDeviceEnabled = MutableLiveData(false)
+ fun setLocationNotAvailable(){
+ //locationUserAvailable.value = false
+ locationUserActive.value = false
+ }
+
companion object{
fun restoreMapState(map: MapLibreMap, savedCameraState: MapCameraState?): Boolean {
val state = savedCameraState ?: return false
map.cameraPosition = CameraPosition.Builder()
.target(LatLng(state.latitude, state.longitude))
.zoom(state.zoom)
.bearing(state.bearing)
.tilt(state.tilt)
.build()
+ Log.d(DEBUG_TAG, "Restored camera state: $state")
return true
}
+
+ const val DEBUG_TAG ="BusTO-MapState"
}
}
\ No newline at end of file

File Metadata

Mime Type
text/x-diff
Expires
Thu, Nov 19, 02:09 (12 h, 49 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
2263830
Default Alt Text
(276 KB)

Event Timeline