From ca5448286aff9b4e800904019e14a34fd7b98c20 Mon Sep 17 00:00:00 2001 From: Victor Shcherb Date: Tue, 19 May 2020 18:40:48 +0200 Subject: [PATCH 1/5] Small refactoring transport --- .../osmand/router/TransportRoutePlanner.java | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/OsmAnd-java/src/main/java/net/osmand/router/TransportRoutePlanner.java b/OsmAnd-java/src/main/java/net/osmand/router/TransportRoutePlanner.java index c7fcf5163e..4cdcfc0a26 100644 --- a/OsmAnd-java/src/main/java/net/osmand/router/TransportRoutePlanner.java +++ b/OsmAnd-java/src/main/java/net/osmand/router/TransportRoutePlanner.java @@ -834,13 +834,17 @@ public class TransportRoutePlanner { // could be global ? TLongObjectHashMap loadedTransportStops = new TLongObjectHashMap(); - TIntObjectHashMap localFileRoutes = new TIntObjectHashMap<>(); //reference, route + for (BinaryMapIndexReader r : routeMap.keySet()) { sr.clearSearchResults(); List stops = r.searchTransportIndex(sr); - localFileRoutes.clear(); - mergeTransportStops(r, loadedTransportStops, stops, localFileRoutes, routeMap.get(r)); + TIntArrayList routesToLoad = mergeTransportStops(r, loadedTransportStops, stops); + + TIntObjectHashMap loadedRoutes = routeMap.get(r); +// localFileRoutes.clear(); + TIntObjectHashMap localFileRoutes = new TIntObjectHashMap<>(); //reference, route + loadRoutes(r, localFileRoutes, loadedRoutes, routesToLoad); for (TransportStop stop : stops) { // skip missing stops @@ -850,7 +854,7 @@ public class TransportRoutePlanner { long stopId = stop.getId(); TransportStop multifileStop = loadedTransportStops.get(stopId); int[] rrs = stop.getReferencesToRoutes(); - // clear up so it won't be used as it is multi file stop + // clear up so it won't be used because there is multi file stop stop.setReferencesToRoutes(null); if (rrs != null && !multifileStop.isDeleted()) { for (int rr : rrs) { @@ -880,15 +884,11 @@ public class TransportRoutePlanner { } - public static List mergeTransportStops(BinaryMapIndexReader reader, - TLongObjectHashMap loadedTransportStops, - List stops, - TIntObjectHashMap localFileRoutes, - TIntObjectHashMap loadedRoutes - ) throws IOException { + public TIntArrayList mergeTransportStops(BinaryMapIndexReader reader, TLongObjectHashMap loadedTransportStops, + List stops) throws IOException { TIntArrayList routesToLoad = new TIntArrayList(); - TIntArrayList localRoutesToLoad = new TIntArrayList(); Iterator it = stops.iterator(); + TIntArrayList localRoutesToLoad = new TIntArrayList(); while (it.hasNext()) { TransportStop stop = it.next(); long stopId = stop.getId(); @@ -899,7 +899,7 @@ public class TransportRoutePlanner { if (multifileStop == null) { loadedTransportStops.put(stopId, stop); multifileStop = stop; - if(!stop.isDeleted()) { + if (!stop.isDeleted()) { localRoutesToLoad.addAll(stop.getReferencesToRoutes()); } } else if (multifileStop.isDeleted()){ @@ -932,7 +932,11 @@ public class TransportRoutePlanner { routesToLoad.addAll(localRoutesToLoad); multifileStop.putReferencesToRoutes(reader.getFile().getName(), localRoutesToLoad.toArray()); //add valid stop and references to routes } + return routesToLoad; + } + private void loadRoutes(BinaryMapIndexReader reader, TIntObjectHashMap localFileRoutes, + TIntObjectHashMap loadedRoutes, TIntArrayList routesToLoad) throws IOException { // load/combine routes if (routesToLoad.size() > 0) { routesToLoad.sort(); @@ -954,8 +958,6 @@ public class TransportRoutePlanner { loadedRoutes.putAll(localFileRoutes); } } - - return stops; } private TransportRoute getCombinedRoute(TransportRoute route) throws IOException { From 1dc4813d3c5c8e5c4e19d4bd88b5a59d170b73ef Mon Sep 17 00:00:00 2001 From: Vitaliy Date: Tue, 19 May 2020 21:36:58 +0300 Subject: [PATCH 2/5] Check xml file before import --- OsmAnd/res/values/strings.xml | 4 +- .../net/osmand/plus/helpers/ImportHelper.java | 142 ++++++++++++++---- 2 files changed, 116 insertions(+), 30 deletions(-) diff --git a/OsmAnd/res/values/strings.xml b/OsmAnd/res/values/strings.xml index c59d5301a9..1973a0cee4 100644 --- a/OsmAnd/res/values/strings.xml +++ b/OsmAnd/res/values/strings.xml @@ -10,7 +10,9 @@ - For wording and consistency, please note https://osmand.net/help-online?id=technical-articles#Creating_a_Consistent_User_Experience Thx - Hardy ---> World overview map (detailed) +--> + Unsupported type + World overview map (detailed) Could not find any such profiles. Change app profile Add profile diff --git a/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java b/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java index 9716ebadf4..25a077208f 100644 --- a/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java +++ b/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java @@ -41,13 +41,6 @@ import net.osmand.plus.GPXDatabase; import net.osmand.plus.OsmandApplication; import net.osmand.plus.OsmandPlugin; import net.osmand.plus.R; -import net.osmand.plus.settings.backend.SettingsHelper; -import net.osmand.plus.settings.backend.SettingsHelper.CheckDuplicatesListener; -import net.osmand.plus.settings.backend.SettingsHelper.PluginSettingsItem; -import net.osmand.plus.settings.backend.SettingsHelper.ProfileSettingsItem; -import net.osmand.plus.settings.backend.SettingsHelper.SettingsCollectListener; -import net.osmand.plus.settings.backend.SettingsHelper.SettingsImportListener; -import net.osmand.plus.settings.backend.SettingsHelper.SettingsItem; import net.osmand.plus.activities.ActivityResultListener; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.activities.TrackActivity; @@ -58,12 +51,21 @@ import net.osmand.plus.base.bottomsheetmenu.simpleitems.DividerHalfItem; import net.osmand.plus.base.bottomsheetmenu.simpleitems.ShortDescriptionItem; import net.osmand.plus.base.bottomsheetmenu.simpleitems.TitleItem; import net.osmand.plus.rastermaps.OsmandRasterMapsPlugin; +import net.osmand.plus.settings.backend.SettingsHelper; +import net.osmand.plus.settings.backend.SettingsHelper.CheckDuplicatesListener; +import net.osmand.plus.settings.backend.SettingsHelper.PluginSettingsItem; +import net.osmand.plus.settings.backend.SettingsHelper.ProfileSettingsItem; +import net.osmand.plus.settings.backend.SettingsHelper.SettingsCollectListener; +import net.osmand.plus.settings.backend.SettingsHelper.SettingsImportListener; +import net.osmand.plus.settings.backend.SettingsHelper.SettingsItem; import net.osmand.plus.settings.fragments.ImportSettingsFragment; import net.osmand.plus.views.OsmandMapTileView; import net.osmand.router.RoutingConfiguration; import net.osmand.util.Algorithms; import org.apache.commons.logging.Log; +import org.xmlpull.v1.XmlPullParser; +import org.xmlpull.v1.XmlPullParserException; import java.io.ByteArrayInputStream; import java.io.File; @@ -109,7 +111,8 @@ public class ImportHelper { public enum ImportType { SETTINGS(OSMAND_SETTINGS_FILE_EXT), - ROUTING(ROUTING_FILE_EXT); + ROUTING(ROUTING_FILE_EXT), + RENDERING(RENDERER_INDEX_EXT); ImportType(String extension) { this.extension = extension; @@ -194,10 +197,8 @@ public class ImportHelper { handleSqliteTileImport(intentUri, fileName); } else if (fileName != null && fileName.endsWith(OSMAND_SETTINGS_FILE_EXT)) { handleOsmAndSettingsImport(intentUri, fileName, extras, null); - } else if (fileName != null && fileName.endsWith(RENDERER_INDEX_EXT)) { - handleRenderingFileImport(intentUri, fileName); } else if (fileName != null && fileName.endsWith(ROUTING_FILE_EXT)) { - handleRoutingFileImport(intentUri, fileName, null); + handleXmlFileImport(intentUri, fileName); } else { handleFavouritesImport(intentUri, fileName, saveFile, useImportDir, false); } @@ -896,48 +897,131 @@ public class ImportHelper { } @SuppressLint("StaticFieldLeak") - private void handleRenderingFileImport(final Uri intentUri, final String fileName) { + private void handleXmlFileImport(final Uri intentUri, final String fileName) { final AsyncTask renderingImportTask = new AsyncTask() { - String mFileName; - ProgressDialog progress; + private String destFileName; + private ImportType importType; + private ProgressDialog progress; @Override protected void onPreExecute() { if (AndroidUtils.isActivityNotDestroyed(activity)) { progress = ProgressDialog.show(activity, app.getString(R.string.loading_smth, ""), app.getString(R.string.loading_data)); } - mFileName = fileName; + destFileName = fileName; } @Override protected String doInBackground(Void... voids) { - File renderingDir = app.getAppPath(IndexConstants.RENDERERS_DIR); - if (!renderingDir.exists()) { - renderingDir.mkdirs(); + checkImportType(); + if (importType != null) { + File dest = getDestinationFile(); + if (dest != null) { + return copyFile(app, dest, intentUri, true); + } } - File dest = new File(renderingDir, mFileName); - while (dest.exists()) { - mFileName = AndroidUtils.createNewFileName(mFileName); - dest = new File(renderingDir, mFileName); - } - return copyFile(app, dest, intentUri, true); + return app.getString(R.string.file_import_error, destFileName, app.getString(R.string.unsupported_type_error)); } @Override protected void onPostExecute(String error) { - File renderingDir = app.getAppPath(IndexConstants.RENDERERS_DIR); - File file = new File(renderingDir, mFileName); + File destDir = getDestinationDir(); + File file = new File(destDir, destFileName); if (error == null && file.exists()) { - app.getRendererRegistry().updateExternalRenderers(); - app.showShortToastMessage(app.getString(R.string.file_imported_successfully, mFileName)); + if (importType == ImportType.RENDERING) { + app.getRendererRegistry().updateExternalRenderers(); + app.showShortToastMessage(app.getString(R.string.file_imported_successfully, destFileName)); + hideProgress(); + } else if (importType == ImportType.ROUTING) { + loadRoutingFiles(app, new AppInitializer.LoadRoutingFilesCallback() { + @Override + public void onRoutingFilesLoaded() { + hideProgress(); + RoutingConfiguration.Builder builder = app.getCustomRoutingConfig(destFileName); + if (builder != null) { + app.showShortToastMessage(app.getString(R.string.file_imported_successfully, destFileName)); + } else { + app.showToastMessage(app.getString(R.string.file_does_not_contain_routing_rules, destFileName)); + } + } + }); + } } else { - app.showShortToastMessage(app.getString(R.string.file_import_error, mFileName, error)); + hideProgress(); + app.showShortToastMessage(app.getString(R.string.file_import_error, destFileName, error)); } + } + + private void hideProgress() { if (progress != null && AndroidUtils.isActivityNotDestroyed(activity)) { progress.dismiss(); } } + + private File getDestinationDir() { + if (importType == ImportType.ROUTING) { + return app.getAppPath(IndexConstants.ROUTING_PROFILES_DIR); + } else if (importType == ImportType.RENDERING) { + return app.getAppPath(IndexConstants.RENDERERS_DIR); + } + return null; + } + + private File getDestinationFile() { + File destDir = getDestinationDir(); + if (destDir != null) { + if (!destDir.exists()) { + destDir.mkdirs(); + } + File destFile = new File(destDir, destFileName); + while (destFile.exists()) { + destFileName = AndroidUtils.createNewFileName(destFileName); + destFile = new File(destDir, destFileName); + } + return destFile; + } + return null; + } + + private void checkImportType() { + InputStream is = null; + try { + final ParcelFileDescriptor pFD = app.getContentResolver().openFileDescriptor(intentUri, "r"); + if (pFD != null) { + is = new FileInputStream(pFD.getFileDescriptor()); + XmlPullParser parser = PlatformUtil.newXMLPullParser(); + parser.setInput(is, "UTF-8"); + int tok; + while ((tok = parser.next()) != XmlPullParser.END_DOCUMENT) { + if (tok == XmlPullParser.START_TAG) { + String name = parser.getName(); + if ("osmand_routing_config".equals(name)) { + importType = ImportType.ROUTING; + } else if ("renderingStyle".equals(name)) { + importType = ImportType.RENDERING; + } + break; + } + } + try { + pFD.close(); + } catch (IOException e) { + log.error(e); + } + } + } catch (FileNotFoundException | XmlPullParserException e) { + log.error(e); + } catch (IOException e) { + log.error(e); + } finally { + if (is != null) try { + is.close(); + } catch (IOException e) { + log.error(e); + } + } + } }; if (app.isApplicationInitializing()) { app.getAppInitializer().addListener(new AppInitializer.AppInitializeListener() { From 7c86a40225503a93124d46061b749368b72b1df6 Mon Sep 17 00:00:00 2001 From: Vitaliy Date: Wed, 20 May 2020 12:26:12 +0300 Subject: [PATCH 3/5] Move import dialog to separate class --- .../main/java/net/osmand/util/Algorithms.java | 26 +++ .../osmand/plus/activities/MapActivity.java | 2 +- .../ImportGpxBottomSheetDialogFragment.java | 94 ++++++++ .../net/osmand/plus/helpers/ImportHelper.java | 220 ++---------------- 4 files changed, 144 insertions(+), 198 deletions(-) create mode 100644 OsmAnd/src/net/osmand/plus/dialogs/ImportGpxBottomSheetDialogFragment.java diff --git a/OsmAnd-java/src/main/java/net/osmand/util/Algorithms.java b/OsmAnd-java/src/main/java/net/osmand/util/Algorithms.java index cd35c0a8ee..338bb9089e 100644 --- a/OsmAnd-java/src/main/java/net/osmand/util/Algorithms.java +++ b/OsmAnd-java/src/main/java/net/osmand/util/Algorithms.java @@ -250,6 +250,32 @@ public class Algorithms { return test == 0x504b0304; } + /** + * Checks, whether the child directory is a subdirectory of the parent + * directory. + * + * @param parent the parent directory. + * @param child the suspected child directory. + * @return true if the child is a subdirectory of the parent directory. + */ + public static boolean isSubDirectory(File parent, File child) { + try { + parent = parent.getCanonicalFile(); + child = child.getCanonicalFile(); + + File dir = child; + while (dir != null) { + if (parent.equals(dir)) { + return true; + } + dir = dir.getParentFile(); + } + } catch (IOException e) { + return false; + } + return false; + } + private static int readInt(InputStream in) throws IOException { int ch1 = in.read(); int ch2 = in.read(); diff --git a/OsmAnd/src/net/osmand/plus/activities/MapActivity.java b/OsmAnd/src/net/osmand/plus/activities/MapActivity.java index 933cf09a48..75330977de 100644 --- a/OsmAnd/src/net/osmand/plus/activities/MapActivity.java +++ b/OsmAnd/src/net/osmand/plus/activities/MapActivity.java @@ -101,7 +101,7 @@ import net.osmand.plus.firstusage.FirstUsageWizardFragment; import net.osmand.plus.helpers.AndroidUiHelper; import net.osmand.plus.helpers.DiscountHelper; import net.osmand.plus.helpers.ImportHelper; -import net.osmand.plus.helpers.ImportHelper.ImportGpxBottomSheetDialogFragment; +import net.osmand.plus.dialogs.ImportGpxBottomSheetDialogFragment; import net.osmand.plus.helpers.IntentHelper; import net.osmand.plus.helpers.LockHelper; import net.osmand.plus.helpers.LockHelper.LockUIAdapter; diff --git a/OsmAnd/src/net/osmand/plus/dialogs/ImportGpxBottomSheetDialogFragment.java b/OsmAnd/src/net/osmand/plus/dialogs/ImportGpxBottomSheetDialogFragment.java new file mode 100644 index 0000000000..cf371f006e --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/dialogs/ImportGpxBottomSheetDialogFragment.java @@ -0,0 +1,94 @@ +package net.osmand.plus.dialogs; + +import android.os.Bundle; +import android.text.style.ForegroundColorSpan; +import android.view.View; + +import net.osmand.AndroidUtils; +import net.osmand.GPXUtilities.GPXFile; +import net.osmand.plus.R; +import net.osmand.plus.base.MenuBottomSheetDialogFragment; +import net.osmand.plus.base.bottomsheetmenu.BaseBottomSheetItem; +import net.osmand.plus.base.bottomsheetmenu.SimpleBottomSheetItem; +import net.osmand.plus.base.bottomsheetmenu.simpleitems.DividerHalfItem; +import net.osmand.plus.base.bottomsheetmenu.simpleitems.ShortDescriptionItem; +import net.osmand.plus.base.bottomsheetmenu.simpleitems.TitleItem; +import net.osmand.plus.helpers.ImportHelper; + +public class ImportGpxBottomSheetDialogFragment extends MenuBottomSheetDialogFragment { + + public static final String TAG = "ImportGpxBottomSheetDialogFragment"; + + private ImportHelper importHelper; + + private GPXFile gpxFile; + private String fileName; + private boolean save; + private boolean useImportDir; + + public void setImportHelper(ImportHelper importHelper) { + this.importHelper = importHelper; + } + + public void setGpxFile(GPXFile gpxFile) { + this.gpxFile = gpxFile; + } + + public void setFileName(String fileName) { + this.fileName = fileName; + } + + public void setSave(boolean save) { + this.save = save; + } + + public void setUseImportDir(boolean useImportDir) { + this.useImportDir = useImportDir; + } + + @Override + public void createMenuItems(Bundle savedInstanceState) { + items.add(new TitleItem(getString(R.string.import_file))); + + int nameColor = getResolvedColor(nightMode ? R.color.active_color_primary_dark : R.color.active_color_primary_light); + int descrColor = getResolvedColor(nightMode ? R.color.text_color_secondary_dark : R.color.text_color_secondary_light); + String descr = getString(R.string.import_gpx_file_description); + if (!descr.contains("%s")) { + descr = "%s " + descr; + } + + CharSequence txt = AndroidUtils.getStyledString(descr, fileName, new ForegroundColorSpan(descrColor), + new ForegroundColorSpan(nameColor)); + items.add(new ShortDescriptionItem(txt)); + + BaseBottomSheetItem asFavoritesItem = new SimpleBottomSheetItem.Builder() + .setIcon(getContentIcon(R.drawable.ic_action_favorite)) + .setTitle(getString(R.string.import_as_favorites)) + .setLayoutId(R.layout.bottom_sheet_item_simple) + .setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + importHelper.importFavoritesFromGpx(gpxFile, fileName); + dismiss(); + } + }) + .create(); + items.add(asFavoritesItem); + + items.add(new DividerHalfItem(getContext())); + + BaseBottomSheetItem asGpxItem = new SimpleBottomSheetItem.Builder() + .setIcon(getContentIcon(R.drawable.ic_action_polygom_dark)) + .setTitle(getString(R.string.import_as_gpx)) + .setLayoutId(R.layout.bottom_sheet_item_simple) + .setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + importHelper.handleGpxImport(gpxFile, fileName, save, useImportDir); + dismiss(); + } + }) + .create(); + items.add(asGpxItem); + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java b/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java index 25a077208f..cbc6800ba8 100644 --- a/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java +++ b/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java @@ -12,8 +12,6 @@ import android.os.Bundle; import android.os.ParcelFileDescriptor; import android.provider.OpenableColumns; import android.provider.Settings; -import android.text.style.ForegroundColorSpan; -import android.view.View; import android.widget.Toast; import androidx.annotation.NonNull; @@ -44,12 +42,7 @@ import net.osmand.plus.R; import net.osmand.plus.activities.ActivityResultListener; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.activities.TrackActivity; -import net.osmand.plus.base.MenuBottomSheetDialogFragment; -import net.osmand.plus.base.bottomsheetmenu.BaseBottomSheetItem; -import net.osmand.plus.base.bottomsheetmenu.SimpleBottomSheetItem; -import net.osmand.plus.base.bottomsheetmenu.simpleitems.DividerHalfItem; -import net.osmand.plus.base.bottomsheetmenu.simpleitems.ShortDescriptionItem; -import net.osmand.plus.base.bottomsheetmenu.simpleitems.TitleItem; +import net.osmand.plus.dialogs.ImportGpxBottomSheetDialogFragment; import net.osmand.plus.rastermaps.OsmandRasterMapsPlugin; import net.osmand.plus.settings.backend.SettingsHelper; import net.osmand.plus.settings.backend.SettingsHelper.CheckDuplicatesListener; @@ -144,21 +137,29 @@ public class ImportHelper { handleFileImport(contentUri, name, extras, useImportDir); } + public void importFavoritesFromGpx(final GPXFile gpxFile, final String fileName) { + importFavoritesImpl(gpxFile, fileName, false); + } + + public void handleGpxImport(GPXFile result, String name, boolean save, boolean useImportDir) { + handleResult(result, name, save, useImportDir, false); + } + public boolean handleGpxImport(final Uri contentUri, final boolean useImportDir) { String name = getNameFromContentUri(app, contentUri); - boolean isOsmandSubdir = isSubDirectory(app.getAppPath(IndexConstants.GPX_INDEX_DIR), new File(contentUri.getPath())); + boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(IndexConstants.GPX_INDEX_DIR), new File(contentUri.getPath())); if (!isOsmandSubdir && name != null) { String nameLC = name.toLowerCase(); if (nameLC.endsWith(GPX_FILE_EXT)) { - name = name.substring(0, name.length() - 4) + GPX_FILE_EXT; + name = name.substring(0, name.length() - GPX_FILE_EXT.length()) + GPX_FILE_EXT; handleGpxImport(contentUri, name, true, useImportDir); return true; } else if (nameLC.endsWith(KML_SUFFIX)) { - name = name.substring(0, name.length() - 4) + KML_SUFFIX; + name = name.substring(0, name.length() - KML_SUFFIX.length()) + KML_SUFFIX; handleKmlImport(contentUri, name, true, useImportDir); return true; } else if (nameLC.endsWith(KMZ_SUFFIX)) { - name = name.substring(0, name.length() - 4) + KMZ_SUFFIX; + name = name.substring(0, name.length() - KMZ_SUFFIX.length()) + KMZ_SUFFIX; handleKmzImport(contentUri, name, true, useImportDir); return true; } @@ -170,7 +171,7 @@ public class ImportHelper { String scheme = uri.getScheme(); boolean isFileIntent = "file".equals(scheme); boolean isContentIntent = "content".equals(scheme); - boolean isOsmandSubdir = isSubDirectory(app.getAppPath(IndexConstants.GPX_INDEX_DIR), new File(uri.getPath())); + boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(IndexConstants.GPX_INDEX_DIR), new File(uri.getPath())); final boolean saveFile = !isFileIntent || !isOsmandSubdir; String fileName = ""; if (isFileIntent) { @@ -183,7 +184,7 @@ public class ImportHelper { public void handleFileImport(Uri intentUri, String fileName, Bundle extras, boolean useImportDir) { final boolean isFileIntent = "file".equals(intentUri.getScheme()); - final boolean isOsmandSubdir = isSubDirectory(app.getAppPath(IndexConstants.GPX_INDEX_DIR), new File(intentUri.getPath())); + final boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(IndexConstants.GPX_INDEX_DIR), new File(intentUri.getPath())); final boolean saveFile = !isFileIntent || !isOsmandSubdir; @@ -198,7 +199,7 @@ public class ImportHelper { } else if (fileName != null && fileName.endsWith(OSMAND_SETTINGS_FILE_EXT)) { handleOsmAndSettingsImport(intentUri, fileName, extras, null); } else if (fileName != null && fileName.endsWith(ROUTING_FILE_EXT)) { - handleXmlFileImport(intentUri, fileName); + handleXmlFileImport(intentUri, fileName, null); } else { handleFavouritesImport(intentUri, fileName, saveFile, useImportDir, false); } @@ -661,7 +662,7 @@ public class ImportHelper { if (importType.equals(ImportType.SETTINGS)) { handleOsmAndSettingsImport(data, fileName, resultData.getExtras(), callback); } else if (importType.equals(ImportType.ROUTING)){ - handleRoutingFileImport(data, fileName, callback); + handleXmlFileImport(data, fileName, callback); } } else { app.showToastMessage(app.getString(R.string.not_support_file_type_with_ext, @@ -675,81 +676,6 @@ public class ImportHelper { mapActivity.startActivityForResult(intent, IMPORT_FILE_REQUEST); } - @SuppressLint("StaticFieldLeak") - private void handleRoutingFileImport(final Uri uri, final String fileName, final CallbackWithObject callback) { - final AsyncTask routingImportTask = new AsyncTask() { - - String mFileName; - ProgressDialog progress; - - @Override - protected void onPreExecute() { - if (AndroidUtils.isActivityNotDestroyed(activity)) { - progress = ProgressDialog.show(activity, app.getString(R.string.loading_smth, ""), app.getString(R.string.loading_data)); - } - mFileName = fileName; - } - - @Override - protected String doInBackground(Void... voids) { - File routingDir = app.getAppPath(IndexConstants.ROUTING_PROFILES_DIR); - if (!routingDir.exists()) { - routingDir.mkdirs(); - } - File dest = new File(routingDir, mFileName); - while (dest.exists()) { - mFileName = AndroidUtils.createNewFileName(mFileName); - dest = new File(routingDir, mFileName); - } - return copyFile(app, dest, uri, true); - } - - @Override - protected void onPostExecute(String error) { - File routingDir = app.getAppPath(IndexConstants.ROUTING_PROFILES_DIR); - final File file = new File(routingDir, mFileName); - if (error == null && file.exists()) { - loadRoutingFiles(app, new AppInitializer.LoadRoutingFilesCallback() { - @Override - public void onRoutingFilesLoaded() { - if (progress != null && AndroidUtils.isActivityNotDestroyed(activity)) { - progress.dismiss(); - } - RoutingConfiguration.Builder builder = app.getCustomRoutingConfig(mFileName); - if (builder != null) { - app.showShortToastMessage(app.getString(R.string.file_imported_successfully, mFileName)); - if (callback != null) { - callback.processResult(builder); - } - } else { - app.showToastMessage(app.getString(R.string.file_does_not_contain_routing_rules, mFileName)); - } - } - }); - } else { - if (progress != null && AndroidUtils.isActivityNotDestroyed(activity)) { - progress.dismiss(); - } - app.showShortToastMessage(app.getString(R.string.file_import_error, mFileName, error)); - } - } - }; - if (app.isApplicationInitializing()) { - app.getAppInitializer().addListener(new AppInitializer.AppInitializeListener() { - @Override - public void onProgress(AppInitializer init, AppInitializer.InitEvents event) { - } - - @Override - public void onFinish(AppInitializer init) { - routingImportTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } - }); - } else { - routingImportTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } - } - private void handleOsmAndSettingsImport(Uri intentUri, String fileName, Bundle extras, CallbackWithObject> callback) { if (extras != null && extras.containsKey(SettingsHelper.SETTINGS_VERSION_KEY) && extras.containsKey(SettingsHelper.SETTINGS_LATEST_CHANGES_KEY)) { int version = extras.getInt(SettingsHelper.SETTINGS_VERSION_KEY, -1); @@ -897,7 +823,8 @@ public class ImportHelper { } @SuppressLint("StaticFieldLeak") - private void handleXmlFileImport(final Uri intentUri, final String fileName) { + private void handleXmlFileImport(final Uri intentUri, final String fileName, + final CallbackWithObject routingCallback) { final AsyncTask renderingImportTask = new AsyncTask() { private String destFileName; @@ -940,6 +867,9 @@ public class ImportHelper { hideProgress(); RoutingConfiguration.Builder builder = app.getCustomRoutingConfig(destFileName); if (builder != null) { + if (routingCallback != null) { + routingCallback.processResult(builder); + } app.showShortToastMessage(app.getString(R.string.file_imported_successfully, destFileName)); } else { app.showToastMessage(app.getString(R.string.file_does_not_contain_routing_rules, destFileName)); @@ -1281,108 +1211,4 @@ public class ImportHelper { } return favourites; } - - /** - * Checks, whether the child directory is a subdirectory of the parent - * directory. - * - * @param parent the parent directory. - * @param child the suspected child directory. - * @return true if the child is a subdirectory of the parent directory. - */ - public boolean isSubDirectory(File parent, File child) { - try { - parent = parent.getCanonicalFile(); - child = child.getCanonicalFile(); - - File dir = child; - while (dir != null) { - if (parent.equals(dir)) { - return true; - } - dir = dir.getParentFile(); - } - } catch (IOException e) { - return false; - } - return false; - } - - public static class ImportGpxBottomSheetDialogFragment extends MenuBottomSheetDialogFragment { - - public static final String TAG = "ImportGpxBottomSheetDialogFragment"; - - private ImportHelper importHelper; - - private GPXFile gpxFile; - private String fileName; - private boolean save; - private boolean useImportDir; - - public void setImportHelper(ImportHelper importHelper) { - this.importHelper = importHelper; - } - - public void setGpxFile(GPXFile gpxFile) { - this.gpxFile = gpxFile; - } - - public void setFileName(String fileName) { - this.fileName = fileName; - } - - public void setSave(boolean save) { - this.save = save; - } - - public void setUseImportDir(boolean useImportDir) { - this.useImportDir = useImportDir; - } - - @Override - public void createMenuItems(Bundle savedInstanceState) { - items.add(new TitleItem(getString(R.string.import_file))); - - int nameColor = getResolvedColor(nightMode ? R.color.active_color_primary_dark : R.color.active_color_primary_light); - int descrColor = getResolvedColor(nightMode ? R.color.text_color_secondary_dark : R.color.text_color_secondary_light); - String descr = getString(R.string.import_gpx_file_description); - if(!descr.contains("%s")) { - descr = "%s " +descr; - } - - CharSequence txt = AndroidUtils.getStyledString(descr, fileName, new ForegroundColorSpan(descrColor), - new ForegroundColorSpan(nameColor)); - items.add(new ShortDescriptionItem(txt)); - - BaseBottomSheetItem asFavoritesItem = new SimpleBottomSheetItem.Builder() - .setIcon(getContentIcon(R.drawable.ic_action_favorite)) - .setTitle(getString(R.string.import_as_favorites)) - .setLayoutId(R.layout.bottom_sheet_item_simple) - .setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - importHelper.importFavoritesImpl(gpxFile, fileName, false); - dismiss(); - } - }) - .create(); - items.add(asFavoritesItem); - - items.add(new DividerHalfItem(getContext())); - - BaseBottomSheetItem asGpxItem = new SimpleBottomSheetItem.Builder() - .setIcon(getContentIcon(R.drawable.ic_action_polygom_dark)) - .setTitle(getString(R.string.import_as_gpx)) - .setLayoutId(R.layout.bottom_sheet_item_simple) - .setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View v) { - importHelper.handleResult(gpxFile, fileName, save, useImportDir, false); - dismiss(); - } - }) - .create(); - items.add(asGpxItem); - } - } -} +} \ No newline at end of file From 3295814f173cce06e06c9b152eac63f5990657ab Mon Sep 17 00:00:00 2001 From: Vitaliy Date: Wed, 20 May 2020 12:51:11 +0300 Subject: [PATCH 4/5] Move import tasks execution --- .../net/osmand/plus/helpers/ImportHelper.java | 126 +++++++----------- 1 file changed, 51 insertions(+), 75 deletions(-) diff --git a/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java b/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java index cbc6800ba8..4ed8de3185 100644 --- a/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java +++ b/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java @@ -31,8 +31,6 @@ import net.osmand.PlatformUtil; import net.osmand.data.FavouritePoint; import net.osmand.data.FavouritePoint.BackgroundType; import net.osmand.plus.AppInitializer; -import net.osmand.plus.AppInitializer.AppInitializeListener; -import net.osmand.plus.AppInitializer.InitEvents; import net.osmand.plus.CustomOsmandPlugin; import net.osmand.plus.FavouritesDbHelper; import net.osmand.plus.GPXDatabase; @@ -340,58 +338,45 @@ public class ImportHelper { @SuppressLint("StaticFieldLeak") private void importFavoritesImpl(final GPXFile gpxFile, final String fileName, final boolean forceImportFavourites) { - if(!app.isApplicationInitializing()) { - new AsyncTask() { - ProgressDialog progress = null; + final AsyncTask favoritesImportTask = new AsyncTask() { + ProgressDialog progress = null; - @Override - protected void onPreExecute() { - if (AndroidUtils.isActivityNotDestroyed(activity)) { - progress = ProgressDialog.show(activity, app.getString(R.string.loading_smth, ""), - app.getString(R.string.loading_data)); - } + @Override + protected void onPreExecute() { + if (AndroidUtils.isActivityNotDestroyed(activity)) { + progress = ProgressDialog.show(activity, app.getString(R.string.loading_smth, ""), + app.getString(R.string.loading_data)); } + } - @Override - protected GPXFile doInBackground(Void... nothing) { - final List favourites = asFavourites(gpxFile.getPoints(), + @Override + protected GPXFile doInBackground(Void... nothing) { + final List favourites = asFavourites(gpxFile.getPoints(), fileName, forceImportFavourites); - final FavouritesDbHelper favoritesHelper = app.getFavorites(); - for (final FavouritePoint favourite : favourites) { - favoritesHelper.deleteFavourite(favourite, false); - favoritesHelper.addFavourite(favourite, false); - } - favoritesHelper.sortAll(); - favoritesHelper.saveCurrentPointsIntoFile(); - return null; + final FavouritesDbHelper favoritesHelper = app.getFavorites(); + for (final FavouritePoint favourite : favourites) { + favoritesHelper.deleteFavourite(favourite, false); + favoritesHelper.addFavourite(favourite, false); } + favoritesHelper.sortAll(); + favoritesHelper.saveCurrentPointsIntoFile(); + return null; + } - @Override - protected void onPostExecute(GPXFile result) { - if (progress != null && AndroidUtils.isActivityNotDestroyed(activity)) { - progress.dismiss(); - } - Toast.makeText(activity, R.string.fav_imported_sucessfully, Toast.LENGTH_LONG) - .show(); - final Intent newIntent = new Intent(activity, + @Override + protected void onPostExecute(GPXFile result) { + if (progress != null && AndroidUtils.isActivityNotDestroyed(activity)) { + progress.dismiss(); + } + Toast.makeText(activity, R.string.fav_imported_sucessfully, Toast.LENGTH_LONG).show(); + final Intent newIntent = new Intent(activity, app.getAppCustomization().getFavoritesActivity()); - newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - newIntent.putExtra(TAB_ID, FAV_TAB); - activity.startActivity(newIntent); - } - }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } else { - app.getAppInitializer().addListener(new AppInitializeListener() { - - @Override - public void onProgress(AppInitializer init, InitEvents event) {} - - @Override - public void onFinish(AppInitializer init) { - importFavoritesImpl(gpxFile, fileName, forceImportFavourites); - } - }); - } + newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + newIntent.putExtra(TAB_ID, FAV_TAB); + activity.startActivity(newIntent); + } + }; + executeImportTask(favoritesImportTask); } @SuppressLint("StaticFieldLeak") @@ -751,20 +736,7 @@ public class ImportHelper { } } }; - if (app.isApplicationInitializing()) { - app.getAppInitializer().addListener(new AppInitializer.AppInitializeListener() { - @Override - public void onProgress(AppInitializer init, AppInitializer.InitEvents event) { - } - - @Override - public void onFinish(AppInitializer init) { - settingsImportTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } - }); - } else { - settingsImportTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } + executeImportTask(settingsImportTask); } private void handlePluginImport(final PluginSettingsItem pluginItem, final File file) { @@ -953,20 +925,7 @@ public class ImportHelper { } } }; - if (app.isApplicationInitializing()) { - app.getAppInitializer().addListener(new AppInitializer.AppInitializeListener() { - @Override - public void onProgress(AppInitializer init, AppInitializer.InitEvents event) { - } - - @Override - public void onFinish(AppInitializer init) { - renderingImportTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } - }); - } else { - renderingImportTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); - } + executeImportTask(renderingImportTask); } private void handleResult(final GPXFile result, final String name, final boolean save, @@ -1211,4 +1170,21 @@ public class ImportHelper { } return favourites; } + + private void executeImportTask(final AsyncTask importTask) { + if (app.isApplicationInitializing()) { + app.getAppInitializer().addListener(new AppInitializer.AppInitializeListener() { + @Override + public void onProgress(AppInitializer init, AppInitializer.InitEvents event) { + } + + @Override + public void onFinish(AppInitializer init) { + importTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } + }); + } else { + importTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + } + } } \ No newline at end of file From 801c61f5ae4a5285b04306d8024eb6e6fcf3829e Mon Sep 17 00:00:00 2001 From: Vitaliy Date: Wed, 20 May 2020 13:43:15 +0300 Subject: [PATCH 5/5] Add check for render file extension --- .../src/main/java/net/osmand/util/Algorithms.java | 6 ++++-- OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java | 11 ++++++++--- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/OsmAnd-java/src/main/java/net/osmand/util/Algorithms.java b/OsmAnd-java/src/main/java/net/osmand/util/Algorithms.java index 338bb9089e..720ecf5107 100644 --- a/OsmAnd-java/src/main/java/net/osmand/util/Algorithms.java +++ b/OsmAnd-java/src/main/java/net/osmand/util/Algorithms.java @@ -90,9 +90,11 @@ public class Algorithms { return def; } - public static String getFileNameWithoutExtension(File f) { - String name = f.getName(); + return getFileNameWithoutExtension(f.getName()); + } + + public static String getFileNameWithoutExtension(String name) { int i = name.indexOf('.'); if (i >= 0) { name = name.substring(0, i); diff --git a/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java b/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java index 4ed8de3185..96914f4e13 100644 --- a/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java +++ b/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java @@ -876,6 +876,10 @@ public class ImportHelper { if (!destDir.exists()) { destDir.mkdirs(); } + if (importType == ImportType.RENDERING && !destFileName.endsWith(RENDERER_INDEX_EXT)) { + String fileName = Algorithms.getFileNameWithoutExtension(destFileName); + destFileName = fileName + RENDERER_INDEX_EXT; + } File destFile = new File(destDir, destFileName); while (destFile.exists()) { destFileName = AndroidUtils.createNewFileName(destFileName); @@ -1171,7 +1175,8 @@ public class ImportHelper { return favourites; } - private void executeImportTask(final AsyncTask importTask) { + @SuppressWarnings("unchecked") + private

void executeImportTask(final AsyncTask importTask, final P... requests) { if (app.isApplicationInitializing()) { app.getAppInitializer().addListener(new AppInitializer.AppInitializeListener() { @Override @@ -1180,11 +1185,11 @@ public class ImportHelper { @Override public void onFinish(AppInitializer init) { - importTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + importTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, requests); } }); } else { - importTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); + importTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, requests); } } } \ No newline at end of file