From 4774382258c4d89dce9dd36f02a940b43ab5e95d Mon Sep 17 00:00:00 2001 From: Vitaliy Date: Tue, 6 Oct 2020 19:48:33 +0300 Subject: [PATCH] Move import async tasks and ImportHelper to separate package --- .../osmand/plus/activities/MapActivity.java | 2 +- .../ImportGpxBottomSheetDialogFragment.java | 2 +- .../plus/importfiles/BaseImportAsyncTask.java | 45 ++ .../plus/importfiles/FavoritesImportTask.java | 59 ++ .../plus/importfiles/GpxImportTask.java | 59 ++ .../GpxOrFavouritesImportTask.java | 83 +++ .../ImportHelper.java | 625 ++---------------- .../plus/importfiles/KmlImportTask.java | 71 ++ .../plus/importfiles/KmzImportTask.java | 67 ++ .../plus/importfiles/ObfImportTask.java | 52 ++ .../plus/importfiles/SettingsImportTask.java | 158 +++++ .../importfiles/SqliteTileImportTask.java | 50 ++ .../plus/importfiles/XmlImportTask.java | 149 +++++ .../StartPlanRouteBottomSheet.java | 4 +- .../plus/myplaces/FavoritesActivity.java | 4 +- ...electProfileBottomSheetDialogFragment.java | 2 +- .../FollowTrackFragment.java | 4 +- .../backend/OsmAndAppCustomization.java | 2 +- .../fragments/MainSettingsFragment.java | 2 +- 19 files changed, 858 insertions(+), 582 deletions(-) create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/BaseImportAsyncTask.java create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/FavoritesImportTask.java create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/GpxImportTask.java create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/GpxOrFavouritesImportTask.java rename OsmAnd/src/net/osmand/plus/{helpers => importfiles}/ImportHelper.java (50%) create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/KmlImportTask.java create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/KmzImportTask.java create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/ObfImportTask.java create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/SettingsImportTask.java create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/SqliteTileImportTask.java create mode 100644 OsmAnd/src/net/osmand/plus/importfiles/XmlImportTask.java diff --git a/OsmAnd/src/net/osmand/plus/activities/MapActivity.java b/OsmAnd/src/net/osmand/plus/activities/MapActivity.java index 2816e7d5b0..2e840f8b64 100644 --- a/OsmAnd/src/net/osmand/plus/activities/MapActivity.java +++ b/OsmAnd/src/net/osmand/plus/activities/MapActivity.java @@ -99,7 +99,7 @@ import net.osmand.plus.firstusage.FirstUsageWelcomeFragment; 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.importfiles.ImportHelper; 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 index cf371f006e..4bc4e1589a 100644 --- a/OsmAnd/src/net/osmand/plus/dialogs/ImportGpxBottomSheetDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/dialogs/ImportGpxBottomSheetDialogFragment.java @@ -13,7 +13,7 @@ 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; +import net.osmand.plus.importfiles.ImportHelper; public class ImportGpxBottomSheetDialogFragment extends MenuBottomSheetDialogFragment { diff --git a/OsmAnd/src/net/osmand/plus/importfiles/BaseImportAsyncTask.java b/OsmAnd/src/net/osmand/plus/importfiles/BaseImportAsyncTask.java new file mode 100644 index 0000000000..4ebafcb8cc --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/BaseImportAsyncTask.java @@ -0,0 +1,45 @@ +package net.osmand.plus.importfiles; + +import android.app.ProgressDialog; +import android.os.AsyncTask; + +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentActivity; + +import net.osmand.AndroidUtils; +import net.osmand.plus.OsmandApplication; +import net.osmand.plus.R; + +import java.lang.ref.WeakReference; + +abstract class BaseImportAsyncTask extends AsyncTask { + + protected OsmandApplication app; + protected WeakReference activityRef; + protected ProgressDialog progress; + + public BaseImportAsyncTask(@NonNull FragmentActivity activity) { + app = (OsmandApplication) activity.getApplicationContext(); + activityRef = new WeakReference<>(activity); + } + + @Override + protected void onPreExecute() { + showProgress(); + } + + protected void showProgress() { + FragmentActivity activity = activityRef.get(); + if (AndroidUtils.isActivityNotDestroyed(activity)) { + String title = app.getString(R.string.loading_smth, ""); + progress = ProgressDialog.show(activity, title, app.getString(R.string.loading_data)); + } + } + + protected void hideProgress() { + FragmentActivity activity = activityRef.get(); + if (progress != null && AndroidUtils.isActivityNotDestroyed(activity)) { + progress.dismiss(); + } + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/importfiles/FavoritesImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/FavoritesImportTask.java new file mode 100644 index 0000000000..2793e1e0ab --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/FavoritesImportTask.java @@ -0,0 +1,59 @@ +package net.osmand.plus.importfiles; + +import android.content.Intent; + +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentActivity; + +import net.osmand.GPXUtilities; +import net.osmand.GPXUtilities.GPXFile; +import net.osmand.data.FavouritePoint; +import net.osmand.plus.FavouritesDbHelper; +import net.osmand.plus.R; + +import java.util.List; + +import static net.osmand.plus.importfiles.ImportHelper.asFavourites; +import static net.osmand.plus.myplaces.FavoritesActivity.FAV_TAB; +import static net.osmand.plus.myplaces.FavoritesActivity.TAB_ID; + +class FavoritesImportTask extends BaseImportAsyncTask { + + private GPXFile gpxFile; + private String fileName; + private boolean forceImportFavourites; + + public FavoritesImportTask(@NonNull FragmentActivity activity, @NonNull GPXFile gpxFile, + @NonNull String fileName, boolean forceImportFavourites) { + super(activity); + this.gpxFile = gpxFile; + this.fileName = fileName; + this.forceImportFavourites = forceImportFavourites; + } + + @Override + protected GPXFile doInBackground(Void... nothing) { + List favourites = asFavourites(app, gpxFile.getPoints(), fileName, forceImportFavourites); + FavouritesDbHelper favoritesHelper = app.getFavorites(); + for (FavouritePoint favourite : favourites) { + favoritesHelper.deleteFavourite(favourite, false); + favoritesHelper.addFavourite(favourite, false); + } + favoritesHelper.sortAll(); + favoritesHelper.saveCurrentPointsIntoFile(); + return null; + } + + @Override + protected void onPostExecute(GPXUtilities.GPXFile result) { + hideProgress(); + FragmentActivity activity = activityRef.get(); + if (activity != null) { + app.showToastMessage(R.string.fav_imported_sucessfully); + Intent newIntent = new Intent(activity, app.getAppCustomization().getFavoritesActivity()); + newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + newIntent.putExtra(TAB_ID, FAV_TAB); + activity.startActivity(newIntent); + } + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/importfiles/GpxImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/GpxImportTask.java new file mode 100644 index 0000000000..1e76f15a26 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/GpxImportTask.java @@ -0,0 +1,59 @@ +package net.osmand.plus.importfiles; + +import android.net.Uri; + +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentActivity; + +import net.osmand.GPXUtilities; +import net.osmand.GPXUtilities.GPXFile; +import net.osmand.util.Algorithms; + +import java.io.FileNotFoundException; +import java.io.InputStream; + +class GpxImportTask extends BaseImportAsyncTask { + + private ImportHelper importHelper; + private Uri gpxFile; + private String fileName; + private boolean save; + private boolean useImportDir; + private boolean showInDetailsActivity; + + public GpxImportTask(@NonNull ImportHelper importHelper, @NonNull FragmentActivity activity, + @NonNull Uri gpxFile, @NonNull String fileName, boolean save, boolean useImportDir, + boolean showInDetailsActivity) { + super(activity); + this.importHelper = importHelper; + this.gpxFile = gpxFile; + this.fileName = fileName; + this.save = save; + this.useImportDir = useImportDir; + this.showInDetailsActivity = showInDetailsActivity; + } + + @Override + protected GPXFile doInBackground(Void... nothing) { + InputStream is = null; + try { + is = app.getContentResolver().openInputStream(gpxFile); + if (is != null) { + return GPXUtilities.loadGPXFile(is); + } + } catch (FileNotFoundException e) { + // + } catch (SecurityException e) { + ImportHelper.log.error(e.getMessage(), e); + } finally { + Algorithms.closeStream(is); + } + return null; + } + + @Override + protected void onPostExecute(GPXUtilities.GPXFile result) { + hideProgress(); + importHelper.handleResult(result, fileName, save, useImportDir, false, showInDetailsActivity); + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/importfiles/GpxOrFavouritesImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/GpxOrFavouritesImportTask.java new file mode 100644 index 0000000000..48eadfb5b1 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/GpxOrFavouritesImportTask.java @@ -0,0 +1,83 @@ +package net.osmand.plus.importfiles; + +import android.net.Uri; + +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentActivity; + +import net.osmand.GPXUtilities; +import net.osmand.GPXUtilities.GPXFile; +import net.osmand.util.Algorithms; + +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +import static net.osmand.plus.importfiles.KmlImportTask.loadGpxFromKml; + +class GpxOrFavouritesImportTask extends BaseImportAsyncTask { + + private ImportHelper importHelper; + private Uri fileUri; + private String fileName; + private boolean save; + private boolean useImportDir; + private boolean forceImportFavourites; + private boolean forceImportGpx; + + public GpxOrFavouritesImportTask(@NonNull ImportHelper importHelper, @NonNull FragmentActivity activity, + @NonNull Uri fileUri, String fileName, boolean save, boolean useImportDir, + boolean forceImportFavourites, boolean forceImportGpx) { + super(activity); + this.importHelper = importHelper; + this.fileUri = fileUri; + this.fileName = fileName; + this.save = save; + this.useImportDir = useImportDir; + this.forceImportFavourites = forceImportFavourites; + this.forceImportGpx = forceImportGpx; + } + + @Override + protected GPXFile doInBackground(Void... nothing) { + InputStream is = null; + ZipInputStream zis = null; + try { + is = app.getContentResolver().openInputStream(fileUri); + if (is != null) { + if (fileName != null && fileName.endsWith(ImportHelper.KML_SUFFIX)) { + return loadGpxFromKml(is); + } else if (fileName != null && fileName.endsWith(ImportHelper.KMZ_SUFFIX)) { + try { + zis = new ZipInputStream(is); + ZipEntry entry; + while ((entry = zis.getNextEntry()) != null) { + if (entry.getName().endsWith(ImportHelper.KML_SUFFIX)) { + return loadGpxFromKml(zis); + } + } + } catch (Exception e) { + return null; + } + } else { + return GPXUtilities.loadGPXFile(is); + } + } + } catch (FileNotFoundException e) { + // + } catch (SecurityException e) { + ImportHelper.log.error(e.getMessage(), e); + } finally { + Algorithms.closeStream(is); + Algorithms.closeStream(zis); + } + return null; + } + + @Override + protected void onPostExecute(final GPXUtilities.GPXFile result) { + hideProgress(); + importHelper.importGpxOrFavourites(result, fileName, save, useImportDir, forceImportFavourites, forceImportGpx); + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java b/OsmAnd/src/net/osmand/plus/importfiles/ImportHelper.java similarity index 50% rename from OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java rename to OsmAnd/src/net/osmand/plus/importfiles/ImportHelper.java index febffa73bf..f5b47604ac 100644 --- a/OsmAnd/src/net/osmand/plus/helpers/ImportHelper.java +++ b/OsmAnd/src/net/osmand/plus/importfiles/ImportHelper.java @@ -1,7 +1,5 @@ -package net.osmand.plus.helpers; +package net.osmand.plus.importfiles; -import android.annotation.SuppressLint; -import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; @@ -17,65 +15,47 @@ import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; -import androidx.fragment.app.FragmentManager; -import net.osmand.AndroidUtils; import net.osmand.CallbackWithObject; import net.osmand.GPXUtilities; import net.osmand.GPXUtilities.GPXFile; import net.osmand.GPXUtilities.WptPt; -import net.osmand.IProgress; import net.osmand.IndexConstants; import net.osmand.PlatformUtil; import net.osmand.data.FavouritePoint; import net.osmand.data.FavouritePoint.BackgroundType; import net.osmand.plus.AppInitializer; -import net.osmand.plus.CustomOsmandPlugin; -import net.osmand.plus.FavouritesDbHelper; import net.osmand.plus.GPXDatabase.GpxDataItem; import net.osmand.plus.OsmandApplication; -import net.osmand.plus.OsmandPlugin; 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.dialogs.ImportGpxBottomSheetDialogFragment; import net.osmand.plus.measurementtool.MeasurementToolFragment; -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; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; -import java.util.zip.ZipEntry; -import java.util.zip.ZipInputStream; import static android.app.Activity.RESULT_OK; +import static net.osmand.IndexConstants.BINARY_MAP_INDEX_EXT; import static net.osmand.IndexConstants.GPX_FILE_EXT; +import static net.osmand.IndexConstants.GPX_INDEX_DIR; import static net.osmand.IndexConstants.OSMAND_SETTINGS_FILE_EXT; import static net.osmand.IndexConstants.RENDERER_INDEX_EXT; import static net.osmand.IndexConstants.ROUTING_FILE_EXT; @@ -83,8 +63,6 @@ import static net.osmand.IndexConstants.SQLITE_CHART_FILE_EXT; import static net.osmand.IndexConstants.SQLITE_EXT; import static net.osmand.IndexConstants.WPT_CHART_FILE_EXT; import static net.osmand.data.FavouritePoint.DEFAULT_BACKGROUND_TYPE; -import static net.osmand.plus.AppInitializer.loadRoutingFiles; -import static net.osmand.plus.myplaces.FavoritesActivity.FAV_TAB; import static net.osmand.plus.myplaces.FavoritesActivity.GPX_TAB; import static net.osmand.plus.myplaces.FavoritesActivity.TAB_ID; @@ -124,6 +102,7 @@ public class ImportHelper { public interface OnGpxImportCompleteListener { void onImportComplete(boolean success); + void onSaveComplete(boolean success, GPXFile result); } @@ -138,7 +117,7 @@ public class ImportHelper { } public void handleContentImport(final Uri contentUri, Bundle extras, final boolean useImportDir) { - final String name = getNameFromContentUri(app, contentUri); + String name = getNameFromContentUri(app, contentUri); handleFileImport(contentUri, name, extras, useImportDir); } @@ -156,7 +135,7 @@ public class ImportHelper { public boolean handleGpxImport(final Uri contentUri, final boolean useImportDir, boolean showInDetailsActivity) { String name = getNameFromContentUri(app, contentUri); - boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(IndexConstants.GPX_INDEX_DIR), new File(contentUri.getPath())); + boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(GPX_INDEX_DIR), new File(contentUri.getPath())); if (!isOsmandSubdir && name != null) { String nameLC = name.toLowerCase(); if (nameLC.endsWith(GPX_FILE_EXT)) { @@ -180,7 +159,7 @@ public class ImportHelper { String scheme = uri.getScheme(); boolean isFileIntent = "file".equals(scheme); boolean isContentIntent = "content".equals(scheme); - boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(IndexConstants.GPX_INDEX_DIR), new File(uri.getPath())); + boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(GPX_INDEX_DIR), new File(uri.getPath())); final boolean saveFile = !isFileIntent || !isOsmandSubdir; String fileName = ""; if (isFileIntent) { @@ -193,7 +172,7 @@ public class ImportHelper { public void handleFileImport(Uri intentUri, String fileName, Bundle extras, boolean useImportDir) { boolean isFileIntent = "file".equals(intentUri.getScheme()); - boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(IndexConstants.GPX_INDEX_DIR), new File(intentUri.getPath())); + boolean isOsmandSubdir = Algorithms.isSubDirectory(app.getAppPath(GPX_INDEX_DIR), new File(intentUri.getPath())); boolean saveFile = !isFileIntent || !isOsmandSubdir; if (fileName == null) { @@ -202,7 +181,7 @@ public class ImportHelper { handleKmlImport(intentUri, fileName, saveFile, useImportDir); } else if (fileName.endsWith(KMZ_SUFFIX)) { handleKmzImport(intentUri, fileName, saveFile, useImportDir); - } else if (fileName.endsWith(IndexConstants.BINARY_MAP_INDEX_EXT)) { + } else if (fileName.endsWith(BINARY_MAP_INDEX_EXT)) { handleObfImport(intentUri, fileName); } else if (fileName.endsWith(SQLITE_EXT)) { handleSqliteTileImport(intentUri, fileName); @@ -221,9 +200,8 @@ public class ImportHelper { public static String getNameFromContentUri(OsmandApplication app, Uri contentUri) { try { - final String name; - final Cursor returnCursor = app.getContentResolver().query(contentUri, - new String[] {OpenableColumns.DISPLAY_NAME}, null, null, null); + String name; + Cursor returnCursor = app.getContentResolver().query(contentUri, new String[] {OpenableColumns.DISPLAY_NAME}, null, null, null); if (returnCursor != null && returnCursor.moveToFirst()) { int columnIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); if (columnIndex != -1) { @@ -244,251 +222,52 @@ public class ImportHelper { } } - @SuppressLint("StaticFieldLeak") - private void handleGpxImport(final Uri gpxFile, final String fileName, final boolean save, final boolean useImportDir, - final boolean showInDetailsActivity) { - AsyncTask gpxImportTask = new BaseImportAsyncTask() { - - @Override - protected GPXFile doInBackground(Void... nothing) { - InputStream is = null; - try { - is = app.getContentResolver().openInputStream(gpxFile); - if (is != null) { - return GPXUtilities.loadGPXFile(is); - } - } catch (FileNotFoundException e) { - // - } catch (SecurityException e) { - log.error(e.getMessage(), e); - } finally { - Algorithms.closeStream(is); - } - return null; - } - - @Override - protected void onPostExecute(GPXFile result) { - hideProgress(); - handleResult(result, fileName, save, useImportDir, false, showInDetailsActivity); - } - }; - executeImportTask(gpxImportTask); + private void handleGpxImport(Uri gpxFile, String fileName, boolean save, boolean useImportDir, boolean showInDetailsActivity) { + executeImportTask(new GpxImportTask(this, activity, gpxFile, fileName, save, useImportDir, showInDetailsActivity)); } - @SuppressLint("StaticFieldLeak") - private void handleGpxOrFavouritesImport(final Uri fileUri, final String fileName, final boolean save, - final boolean useImportDir, final boolean forceImportFavourites, - final boolean forceImportGpx) { - AsyncTask gpxOrFavouritesImportTask = new BaseImportAsyncTask() { - - @Override - protected GPXFile doInBackground(Void... nothing) { - InputStream is = null; - ZipInputStream zis = null; - try { - is = app.getContentResolver().openInputStream(fileUri); - if (is != null) { - if (fileName != null && fileName.endsWith(KML_SUFFIX)) { - final String result = Kml2Gpx.toGpx(is); - if (result != null) { - try { - return GPXUtilities.loadGPXFile(new ByteArrayInputStream(result.getBytes("UTF-8"))); - } catch (UnsupportedEncodingException e) { - return null; - } - } - } else if (fileName != null && fileName.endsWith(KMZ_SUFFIX)) { - try { - zis = new ZipInputStream(is); - ZipEntry entry; - while ((entry = zis.getNextEntry()) != null) { - if (entry.getName().endsWith(KML_SUFFIX)) { - final String result = Kml2Gpx.toGpx(zis); - if (result != null) { - try { - return GPXUtilities.loadGPXFile(new ByteArrayInputStream(result.getBytes("UTF-8"))); - } catch (UnsupportedEncodingException e) { - return null; - } - } - } - } - } catch (Exception e) { - return null; - } - } else { - return GPXUtilities.loadGPXFile(is); - } - } - } catch (FileNotFoundException e) { - // - } catch (SecurityException e) { - log.error(e.getMessage(), e); - } finally { - Algorithms.closeStream(is); - Algorithms.closeStream(zis); - } - return null; - } - - @Override - protected void onPostExecute(final GPXFile result) { - hideProgress(); - importGpxOrFavourites(result, fileName, save, useImportDir, forceImportFavourites, forceImportGpx); - } - }; - executeImportTask(gpxOrFavouritesImportTask); + private void handleGpxOrFavouritesImport(Uri fileUri, String fileName, boolean save, boolean useImportDir, + boolean forceImportFavourites, boolean forceImportGpx) { + executeImportTask(new GpxOrFavouritesImportTask(this, activity, fileUri, fileName, save, useImportDir, forceImportFavourites, forceImportGpx)); } - @SuppressLint("StaticFieldLeak") - private void importFavoritesImpl(final GPXFile gpxFile, final String fileName, final boolean forceImportFavourites) { - AsyncTask favoritesImportTask = new BaseImportAsyncTask() { - - @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; - } - - @Override - protected void onPostExecute(GPXFile result) { - hideProgress(); - 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); - } - }; - executeImportTask(favoritesImportTask); + private void importFavoritesImpl(GPXFile gpxFile, String fileName, boolean forceImportFavourites) { + executeImportTask(new FavoritesImportTask(activity, gpxFile, fileName, forceImportFavourites)); } - @SuppressLint("StaticFieldLeak") - private void handleKmzImport(final Uri kmzFile, final String name, final boolean save, final boolean useImportDir) { - AsyncTask kmzImportTask = new BaseImportAsyncTask() { - - @Override - protected GPXFile doInBackground(Void... voids) { - InputStream is = null; - ZipInputStream zis = null; - try { - is = app.getContentResolver().openInputStream(kmzFile); - if (is != null) { - zis = new ZipInputStream(is); - - ZipEntry entry; - while ((entry = zis.getNextEntry()) != null) { - if (entry.getName().endsWith(KML_SUFFIX)) { - final String result = Kml2Gpx.toGpx(zis); - if (result != null) { - try { - return GPXUtilities.loadGPXFile(new ByteArrayInputStream(result.getBytes("UTF-8"))); - } catch (UnsupportedEncodingException e) { - return null; - } - } - } - } - } - } catch (Exception e) { - log.error(e.getMessage(), e); - } finally { - Algorithms.closeStream(is); - Algorithms.closeStream(zis); - } - return null; - } - - @Override - protected void onPostExecute(GPXFile result) { - hideProgress(); - handleResult(result, name, save, useImportDir, false); - } - - }; - executeImportTask(kmzImportTask); + private void handleKmzImport(Uri kmzFile, String name, boolean save, boolean useImportDir) { + executeImportTask(new KmzImportTask(this, activity, kmzFile, name, save, useImportDir)); } - @SuppressLint("StaticFieldLeak") - private void handleKmlImport(final Uri kmlFile, final String name, final boolean save, final boolean useImportDir) { - AsyncTask kmlImportTask = new BaseImportAsyncTask() { - - @Override - protected GPXFile doInBackground(Void... nothing) { - InputStream is = null; - try { - is = app.getContentResolver().openInputStream(kmlFile); - if (is != null) { - final String result = Kml2Gpx.toGpx(is); - if (result != null) { - try { - return GPXUtilities.loadGPXFile(new ByteArrayInputStream(result.getBytes("UTF-8"))); - } catch (UnsupportedEncodingException e) { - return null; - } - } - } - } catch (FileNotFoundException e) { - // - } catch (SecurityException e) { - log.error(e.getMessage(), e); - } finally { - Algorithms.closeStream(is); - } - return null; - } - - @Override - protected void onPostExecute(GPXFile result) { - hideProgress(); - handleResult(result, name, save, useImportDir, false); - } - }; - executeImportTask(kmlImportTask); + private void handleKmlImport(Uri kmlFile, String name, boolean save, boolean useImportDir) { + executeImportTask(new KmlImportTask(this, activity, kmlFile, name, save, useImportDir)); } - @SuppressLint("StaticFieldLeak") - private void handleObfImport(final Uri obfFile, final String name) { - AsyncTask obfImportTask = new BaseImportAsyncTask() { - - @Override - protected String doInBackground(Void... voids) { - String error = copyFile(app, getObfDestFile(name), obfFile, false); - if (error == null) { - app.getResourceManager().reloadIndexes(IProgress.EMPTY_PROGRESS, new ArrayList()); - app.getDownloadThread().updateLoadedFiles(); - return app.getString(R.string.map_imported_successfully); - } - return app.getString(R.string.map_import_error) + ": " + error; - } - - @Override - protected void onPostExecute(String message) { - hideProgress(); - app.showShortToastMessage(message); - } - }; - executeImportTask(obfImportTask); + private void handleObfImport(Uri obfFile, String name) { + executeImportTask(new ObfImportTask(activity, obfFile, name)); } - @NonNull - private File getObfDestFile(@NonNull String name) { - if (name.endsWith(IndexConstants.BINARY_ROAD_MAP_INDEX_EXT)) { - return app.getAppPath(IndexConstants.ROADS_INDEX_DIR + name); - } else if (name.endsWith(IndexConstants.BINARY_WIKI_MAP_INDEX_EXT)) { - return app.getAppPath(IndexConstants.WIKI_INDEX_DIR + name); + private void handleSqliteTileImport(Uri uri, String name) { + executeImportTask(new SqliteTileImportTask(activity, uri, name)); + } + + 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); + String latestChanges = extras.getString(SettingsHelper.SETTINGS_LATEST_CHANGES_KEY); + handleOsmAndSettingsImport(intentUri, fileName, latestChanges, version, callback); + } else { + handleOsmAndSettingsImport(intentUri, fileName, null, -1, callback); } - return app.getAppPath(name); + } + + private void handleOsmAndSettingsImport(Uri uri, String name, String latestChanges, int version, + CallbackWithObject> callback) { + executeImportTask(new SettingsImportTask(activity, uri, name, latestChanges, version, callback)); + } + + private void handleXmlFileImport(Uri intentUri, String fileName, CallbackWithObject routingCallback) { + executeImportTask(new XmlImportTask(activity, intentUri, fileName, routingCallback)); } @Nullable @@ -538,36 +317,6 @@ public class ImportHelper { return error; } - @SuppressLint("StaticFieldLeak") - private void handleSqliteTileImport(final Uri uri, final String name) { - AsyncTask sqliteTileImportTask = new BaseImportAsyncTask() { - - @Override - protected String doInBackground(Void... voids) { - return copyFile(app, app.getAppPath(IndexConstants.TILES_INDEX_DIR + name), uri, false); - } - - @Override - protected void onPostExecute(String error) { - hideProgress(); - if (error == null) { - OsmandRasterMapsPlugin plugin = OsmandPlugin.getPlugin(OsmandRasterMapsPlugin.class); - if (plugin != null && !plugin.isActive() && !plugin.needsInstallation()) { - OsmandPlugin.enablePlugin(getMapActivity(), app, plugin, true); - } - MapActivity mapActivity = getMapActivity(); - if (mapActivity != null) { - mapActivity.getMapLayers().selectMapLayer(mapActivity.getMapView(), null, null); - } - Toast.makeText(app, app.getString(R.string.map_imported_successfully), Toast.LENGTH_SHORT).show(); - } else { - Toast.makeText(app, app.getString(R.string.map_import_error) + ": " + error, Toast.LENGTH_SHORT).show(); - } - } - }; - executeImportTask(sqliteTileImportTask); - } - public void chooseFileToImport(final ImportType importType, final CallbackWithObject callback) { final MapActivity mapActivity = getMapActivity(); if (mapActivity == null) { @@ -627,255 +376,13 @@ public class ImportHelper { return intent; } - 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); - String latestChanges = extras.getString(SettingsHelper.SETTINGS_LATEST_CHANGES_KEY); - handleOsmAndSettingsImport(intentUri, fileName, latestChanges, version, callback); - } else { - handleOsmAndSettingsImport(intentUri, fileName, null, -1, callback); - } - } - - @SuppressLint("StaticFieldLeak") - private void handleOsmAndSettingsImport(final Uri uri, final String name, final String latestChanges, final int version, - final CallbackWithObject> callback) { - AsyncTask settingsImportTask = new BaseImportAsyncTask() { - - @Override - protected String doInBackground(Void... voids) { - File tempDir = app.getAppPath(IndexConstants.TEMP_DIR); - if (!tempDir.exists()) { - tempDir.mkdirs(); - } - File dest = new File(tempDir, name); - return copyFile(app, dest, uri, true); - } - - @Override - protected void onPostExecute(String error) { - File tempDir = app.getAppPath(IndexConstants.TEMP_DIR); - final File file = new File(tempDir, name); - if (error == null && file.exists()) { - app.getSettingsHelper().collectSettings(file, latestChanges, version, new SettingsCollectListener() { - @Override - public void onSettingsCollectFinished(boolean succeed, boolean empty, @NonNull List items) { - hideProgress(); - if (succeed) { - List pluginIndependentItems = new ArrayList<>(); - List pluginSettingsItems = new ArrayList<>(); - for (SettingsItem item : items) { - if (item instanceof PluginSettingsItem) { - pluginSettingsItems.add((PluginSettingsItem) item); - } else if (Algorithms.isEmpty(item.getPluginId())) { - pluginIndependentItems.add(item); - } - } - for (PluginSettingsItem pluginItem : pluginSettingsItems) { - handlePluginImport(pluginItem, file); - } - if (!pluginIndependentItems.isEmpty()) { - FragmentManager fragmentManager = activity.getSupportFragmentManager(); - ImportSettingsFragment.showInstance(fragmentManager, pluginIndependentItems, file); - } - } else if (empty) { - app.showShortToastMessage(app.getString(R.string.file_import_error, name, app.getString(R.string.shared_string_unexpected_error))); - } - } - }); - } else { - hideProgress(); - app.showShortToastMessage(app.getString(R.string.file_import_error, name, error)); - } - } - }; - executeImportTask(settingsImportTask); - } - - private void handlePluginImport(final PluginSettingsItem pluginItem, final File file) { - final ProgressDialog progress = new ProgressDialog(activity); - progress.setTitle(app.getString(R.string.loading_smth, "")); - progress.setMessage(app.getString(R.string.importing_from, pluginItem.getPublicName(app))); - progress.setIndeterminate(true); - progress.setCancelable(false); - - if (AndroidUtils.isActivityNotDestroyed(activity)) { - progress.show(); - } - - final SettingsImportListener importListener = new SettingsImportListener() { - @Override - public void onSettingsImportFinished(boolean succeed, @NonNull List items) { - if (AndroidUtils.isActivityNotDestroyed(activity)) { - progress.dismiss(); - } - CustomOsmandPlugin plugin = pluginItem.getPlugin(); - plugin.loadResources(); - - for (SettingsItem item : items) { - if (item instanceof ProfileSettingsItem) { - ((ProfileSettingsItem) item).applyAdditionalPrefs(); - } - } - if (!Algorithms.isEmpty(plugin.getDownloadMaps())) { - app.getDownloadThread().runReloadIndexFilesSilent(); - } - if (!Algorithms.isEmpty(plugin.getRendererNames())) { - app.getRendererRegistry().updateExternalRenderers(); - } - if (!Algorithms.isEmpty(plugin.getRouterNames())) { - loadRoutingFiles(app, null); - } - if (activity != null) { - plugin.onInstall(app, activity); - } - String pluginId = pluginItem.getPluginId(); - File pluginDir = new File(app.getAppPath(null), IndexConstants.PLUGINS_DIR + pluginId); - app.getSettingsHelper().exportSettings(pluginDir, "items", null, items, false); - } - }; - List pluginItems = new ArrayList<>(pluginItem.getPluginDependentItems()); - pluginItems.add(0, pluginItem); - app.getSettingsHelper().checkDuplicates(file, pluginItems, pluginItems, new CheckDuplicatesListener() { - @Override - public void onDuplicatesChecked(@NonNull List duplicates, List items) { - for (SettingsItem item : items) { - item.setShouldReplace(true); - } - app.getSettingsHelper().importSettings(file, items, "", 1, importListener); - } - }); - } - - @SuppressLint("StaticFieldLeak") - private void handleXmlFileImport(final Uri intentUri, final String fileName, - final CallbackWithObject routingCallback) { - AsyncTask renderingImportTask = new BaseImportAsyncTask() { - - private String destFileName; - private ImportType importType; - - @Override - protected void onPreExecute() { - showProgress(); - destFileName = fileName; - } - - @Override - protected String doInBackground(Void... voids) { - checkImportType(); - if (importType != null) { - File dest = getDestinationFile(); - if (dest != null) { - 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 destDir = getDestinationDir(); - File file = new File(destDir, destFileName); - if (error == null && file.exists()) { - 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) { - 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)); - } - } - }); - } - } else { - hideProgress(); - app.showShortToastMessage(app.getString(R.string.file_import_error, destFileName, error)); - } - } - - 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(); - } - 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); - destFile = new File(destDir, destFileName); - } - return destFile; - } - return null; - } - - private void checkImportType() { - InputStream is = null; - try { - is = app.getContentResolver().openInputStream(intentUri); - if (is != null) { - 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; - } - } - Algorithms.closeStream(is); - } - } catch (FileNotFoundException | XmlPullParserException e) { - log.error(e); - } catch (IOException e) { - log.error(e); - } catch (SecurityException e) { - log.error(e.getMessage(), e); - } finally { - Algorithms.closeStream(is); - } - } - }; - executeImportTask(renderingImportTask); - } - - private void handleResult(GPXFile result, String name, boolean save, - boolean useImportDir, boolean forceImportFavourites) { + protected void handleResult(GPXFile result, String name, boolean save, + boolean useImportDir, boolean forceImportFavourites) { handleResult(result, name, save, useImportDir, forceImportFavourites, true); } - private void handleResult(final GPXFile result, final String name, final boolean save, - final boolean useImportDir, boolean forceImportFavourites, boolean showInDetailsActivity) { + protected void handleResult(final GPXFile result, final String name, final boolean save, + final boolean useImportDir, boolean forceImportFavourites, boolean showInDetailsActivity) { if (result != null) { if (result.error != null) { Toast.makeText(activity, result.error.getMessage(), Toast.LENGTH_LONG).show(); @@ -937,7 +444,7 @@ public class ImportHelper { if (useImportDir) { importDir = app.getAppPath(IndexConstants.GPX_IMPORT_DIR); } else { - importDir = app.getAppPath(IndexConstants.GPX_INDEX_DIR); + importDir = app.getAppPath(GPX_INDEX_DIR); } //noinspection ResultOfMethodCallIgnored importDir.mkdirs(); @@ -1058,9 +565,9 @@ public class ImportHelper { } } - private void importGpxOrFavourites(final GPXFile gpxFile, final String fileName, final boolean save, - final boolean useImportDir, final boolean forceImportFavourites, - final boolean forceImportGpx) { + protected void importGpxOrFavourites(final GPXFile gpxFile, final String fileName, final boolean save, + final boolean useImportDir, final boolean forceImportFavourites, + final boolean forceImportGpx) { if (gpxFile == null || gpxFile.isPointsEmpty()) { if (forceImportFavourites) { final DialogInterface.OnClickListener importAsTrackListener = new DialogInterface.OnClickListener() { @@ -1083,11 +590,10 @@ public class ImportHelper { .setPositiveButton(R.string.shared_string_import, importAsTrackListener) .setNegativeButton(R.string.shared_string_cancel, importAsTrackListener) .show(); - return; } else { handleResult(gpxFile, fileName, save, useImportDir, false); - return; } + return; } if (forceImportFavourites) { @@ -1110,7 +616,7 @@ public class ImportHelper { } } - private List asFavourites(final List wptPts, String fileName, boolean forceImportFavourites) { + protected static List asFavourites(OsmandApplication app, List wptPts, String fileName, boolean forceImportFavourites) { final List favourites = new ArrayList<>(); for (WptPt p : wptPts) { if (p.name != null) { @@ -1155,27 +661,4 @@ public class ImportHelper { importTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, requests); } } - - protected abstract class BaseImportAsyncTask extends AsyncTask { - - protected ProgressDialog progress; - - @Override - protected void onPreExecute() { - showProgress(); - } - - protected void showProgress() { - if (AndroidUtils.isActivityNotDestroyed(activity)) { - String title = app.getString(R.string.loading_smth, ""); - progress = ProgressDialog.show(activity, title, app.getString(R.string.loading_data)); - } - } - - protected void hideProgress() { - if (progress != null && AndroidUtils.isActivityNotDestroyed(activity)) { - progress.dismiss(); - } - } - } } \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/importfiles/KmlImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/KmlImportTask.java new file mode 100644 index 0000000000..38c557e8c7 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/KmlImportTask.java @@ -0,0 +1,71 @@ +package net.osmand.plus.importfiles; + +import android.net.Uri; + +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentActivity; + +import net.osmand.GPXUtilities; +import net.osmand.GPXUtilities.GPXFile; +import net.osmand.plus.helpers.Kml2Gpx; +import net.osmand.util.Algorithms; + +import java.io.ByteArrayInputStream; +import java.io.FileNotFoundException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; + +class KmlImportTask extends BaseImportAsyncTask { + + private ImportHelper importHelper; + private Uri uri; + private String name; + private boolean save; + private boolean useImportDir; + + public KmlImportTask(@NonNull ImportHelper importHelper, @NonNull FragmentActivity activity, + @NonNull Uri uri, String name, boolean save, boolean useImportDir) { + super(activity); + this.importHelper = importHelper; + this.uri = uri; + this.name = name; + this.save = save; + this.useImportDir = useImportDir; + } + + @Override + protected GPXFile doInBackground(Void... nothing) { + InputStream is = null; + try { + is = app.getContentResolver().openInputStream(uri); + if (is != null) { + return loadGpxFromKml(is); + } + } catch (FileNotFoundException e) { + // + } catch (SecurityException e) { + ImportHelper.log.error(e.getMessage(), e); + } finally { + Algorithms.closeStream(is); + } + return null; + } + + @Override + protected void onPostExecute(GPXFile result) { + hideProgress(); + importHelper.handleResult(result, name, save, useImportDir, false); + } + + protected static GPXFile loadGpxFromKml(@NonNull InputStream is) { + String result = Kml2Gpx.toGpx(is); + if (result != null) { + try { + return GPXUtilities.loadGPXFile(new ByteArrayInputStream(result.getBytes("UTF-8"))); + } catch (UnsupportedEncodingException e) { + return null; + } + } + return null; + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/importfiles/KmzImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/KmzImportTask.java new file mode 100644 index 0000000000..420f4feff4 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/KmzImportTask.java @@ -0,0 +1,67 @@ +package net.osmand.plus.importfiles; + +import android.net.Uri; + +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentActivity; + +import net.osmand.GPXUtilities; +import net.osmand.GPXUtilities.GPXFile; +import net.osmand.util.Algorithms; + +import java.io.InputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +import static net.osmand.plus.importfiles.ImportHelper.KML_SUFFIX; +import static net.osmand.plus.importfiles.KmlImportTask.loadGpxFromKml; + +class KmzImportTask extends BaseImportAsyncTask { + + private ImportHelper importHelper; + private Uri uri; + private String name; + private boolean save; + private boolean useImportDir; + + public KmzImportTask(@NonNull ImportHelper importHelper, @NonNull FragmentActivity activity, + @NonNull Uri uri, @NonNull String name, boolean save, boolean useImportDir) { + super(activity); + this.importHelper = importHelper; + this.uri = uri; + this.name = name; + this.save = save; + this.useImportDir = useImportDir; + } + + @Override + protected GPXFile doInBackground(Void... voids) { + InputStream is = null; + ZipInputStream zis = null; + try { + is = app.getContentResolver().openInputStream(uri); + if (is != null) { + zis = new ZipInputStream(is); + + ZipEntry entry; + while ((entry = zis.getNextEntry()) != null) { + if (entry.getName().endsWith(KML_SUFFIX)) { + return loadGpxFromKml(is); + } + } + } + } catch (Exception e) { + ImportHelper.log.error(e.getMessage(), e); + } finally { + Algorithms.closeStream(is); + Algorithms.closeStream(zis); + } + return null; + } + + @Override + protected void onPostExecute(GPXUtilities.GPXFile result) { + hideProgress(); + importHelper.handleResult(result, name, save, useImportDir, false); + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/importfiles/ObfImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/ObfImportTask.java new file mode 100644 index 0000000000..e4a82faff9 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/ObfImportTask.java @@ -0,0 +1,52 @@ +package net.osmand.plus.importfiles; + +import android.net.Uri; + +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentActivity; + +import net.osmand.IProgress; +import net.osmand.IndexConstants; +import net.osmand.plus.R; + +import java.io.File; +import java.util.ArrayList; + +class ObfImportTask extends BaseImportAsyncTask { + + private Uri uri; + private String name; + + public ObfImportTask(@NonNull FragmentActivity activity, @NonNull Uri uri, String name) { + super(activity); + this.uri = uri; + this.name = name; + } + + @Override + protected String doInBackground(Void... voids) { + String error = ImportHelper.copyFile(app, getObfDestFile(name), uri, false); + if (error == null) { + app.getResourceManager().reloadIndexes(IProgress.EMPTY_PROGRESS, new ArrayList()); + app.getDownloadThread().updateLoadedFiles(); + return app.getString(R.string.map_imported_successfully); + } + return app.getString(R.string.map_import_error) + ": " + error; + } + + @Override + protected void onPostExecute(String message) { + hideProgress(); + app.showShortToastMessage(message); + } + + @NonNull + private File getObfDestFile(@NonNull String name) { + if (name.endsWith(IndexConstants.BINARY_ROAD_MAP_INDEX_EXT)) { + return app.getAppPath(IndexConstants.ROADS_INDEX_DIR + name); + } else if (name.endsWith(IndexConstants.BINARY_WIKI_MAP_INDEX_EXT)) { + return app.getAppPath(IndexConstants.WIKI_INDEX_DIR + name); + } + return app.getAppPath(name); + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/importfiles/SettingsImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/SettingsImportTask.java new file mode 100644 index 0000000000..7800714610 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/SettingsImportTask.java @@ -0,0 +1,158 @@ +package net.osmand.plus.importfiles; + +import android.app.ProgressDialog; +import android.net.Uri; + +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentActivity; +import androidx.fragment.app.FragmentManager; + +import net.osmand.AndroidUtils; +import net.osmand.CallbackWithObject; +import net.osmand.IndexConstants; +import net.osmand.plus.CustomOsmandPlugin; +import net.osmand.plus.R; +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.util.Algorithms; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import static net.osmand.IndexConstants.TEMP_DIR; +import static net.osmand.plus.AppInitializer.loadRoutingFiles; + +class SettingsImportTask extends BaseImportAsyncTask { + + private Uri uri; + private String name; + private String latestChanges; + private int version; + private CallbackWithObject> callback; + + public SettingsImportTask(@NonNull FragmentActivity activity, @NonNull Uri uri, + @NonNull String name, String latestChanges, int version, + CallbackWithObject> callback) { + super(activity); + this.uri = uri; + this.name = name; + this.latestChanges = latestChanges; + this.version = version; + this.callback = callback; + } + + @Override + protected String doInBackground(Void... voids) { + File tempDir = app.getAppPath(TEMP_DIR); + if (!tempDir.exists()) { + tempDir.mkdirs(); + } + File dest = new File(tempDir, name); + return ImportHelper.copyFile(app, dest, uri, true); + } + + @Override + protected void onPostExecute(String error) { + File tempDir = app.getAppPath(TEMP_DIR); + final File file = new File(tempDir, name); + if (error == null && file.exists()) { + app.getSettingsHelper().collectSettings(file, latestChanges, version, new SettingsCollectListener() { + @Override + public void onSettingsCollectFinished(boolean succeed, boolean empty, @NonNull List items) { + hideProgress(); + if (succeed) { + List pluginIndependentItems = new ArrayList<>(); + List pluginSettingsItems = new ArrayList<>(); + for (SettingsItem item : items) { + if (item instanceof PluginSettingsItem) { + pluginSettingsItems.add((PluginSettingsItem) item); + } else if (Algorithms.isEmpty(item.getPluginId())) { + pluginIndependentItems.add(item); + } + } + for (PluginSettingsItem pluginItem : pluginSettingsItems) { + handlePluginImport(pluginItem, file); + } + if (!pluginIndependentItems.isEmpty()) { + FragmentActivity activity = activityRef.get(); + if (activity != null) { + FragmentManager fragmentManager = activity.getSupportFragmentManager(); + ImportSettingsFragment.showInstance(fragmentManager, pluginIndependentItems, file); + } + } + } else if (empty) { + app.showShortToastMessage(app.getString(R.string.file_import_error, name, app.getString(R.string.shared_string_unexpected_error))); + } + } + }); + } else { + hideProgress(); + app.showShortToastMessage(app.getString(R.string.file_import_error, name, error)); + } + } + + private void handlePluginImport(final PluginSettingsItem pluginItem, final File file) { + FragmentActivity activity = activityRef.get(); + final ProgressDialog progress; + if (AndroidUtils.isActivityNotDestroyed(activity)) { + progress = new ProgressDialog(activity); + progress.setTitle(app.getString(R.string.loading_smth, "")); + progress.setMessage(app.getString(R.string.importing_from, pluginItem.getPublicName(app))); + progress.setIndeterminate(true); + progress.setCancelable(false); + progress.show(); + } else { + progress = null; + } + + final SettingsImportListener importListener = new SettingsImportListener() { + @Override + public void onSettingsImportFinished(boolean succeed, @NonNull List items) { + FragmentActivity activity = activityRef.get(); + if (progress != null && AndroidUtils.isActivityNotDestroyed(activity)) { + progress.dismiss(); + } + CustomOsmandPlugin plugin = pluginItem.getPlugin(); + plugin.loadResources(); + + for (SettingsItem item : items) { + if (item instanceof ProfileSettingsItem) { + ((ProfileSettingsItem) item).applyAdditionalPrefs(); + } + } + if (!Algorithms.isEmpty(plugin.getDownloadMaps())) { + app.getDownloadThread().runReloadIndexFilesSilent(); + } + if (!Algorithms.isEmpty(plugin.getRendererNames())) { + app.getRendererRegistry().updateExternalRenderers(); + } + if (!Algorithms.isEmpty(plugin.getRouterNames())) { + loadRoutingFiles(app, null); + } + if (activity != null) { + plugin.onInstall(app, activity); + } + String pluginId = pluginItem.getPluginId(); + File pluginDir = new File(app.getAppPath(null), IndexConstants.PLUGINS_DIR + pluginId); + app.getSettingsHelper().exportSettings(pluginDir, "items", null, items, false); + } + }; + List pluginItems = new ArrayList<>(pluginItem.getPluginDependentItems()); + pluginItems.add(0, pluginItem); + app.getSettingsHelper().checkDuplicates(file, pluginItems, pluginItems, new CheckDuplicatesListener() { + @Override + public void onDuplicatesChecked(@NonNull List duplicates, List items) { + for (SettingsItem item : items) { + item.setShouldReplace(true); + } + app.getSettingsHelper().importSettings(file, items, "", 1, importListener); + } + }); + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/importfiles/SqliteTileImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/SqliteTileImportTask.java new file mode 100644 index 0000000000..d9a177a016 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/SqliteTileImportTask.java @@ -0,0 +1,50 @@ +package net.osmand.plus.importfiles; + +import android.net.Uri; +import android.widget.Toast; + +import androidx.annotation.NonNull; +import androidx.fragment.app.FragmentActivity; + +import net.osmand.plus.OsmandPlugin; +import net.osmand.plus.R; +import net.osmand.plus.activities.MapActivity; +import net.osmand.plus.rastermaps.OsmandRasterMapsPlugin; + +import static net.osmand.IndexConstants.TILES_INDEX_DIR; + +class SqliteTileImportTask extends BaseImportAsyncTask { + + private Uri uri; + private String name; + + public SqliteTileImportTask(@NonNull FragmentActivity activity, @NonNull Uri uri, @NonNull String name) { + super(activity); + this.uri = uri; + this.name = name; + } + + @Override + protected String doInBackground(Void... voids) { + return ImportHelper.copyFile(app, app.getAppPath(TILES_INDEX_DIR + name), uri, false); + } + + @Override + protected void onPostExecute(String error) { + hideProgress(); + if (error == null) { + FragmentActivity activity = activityRef.get(); + OsmandRasterMapsPlugin plugin = OsmandPlugin.getPlugin(OsmandRasterMapsPlugin.class); + if (plugin != null && !plugin.isActive() && !plugin.needsInstallation()) { + OsmandPlugin.enablePlugin(activity, app, plugin, true); + } + if (activity instanceof MapActivity) { + MapActivity mapActivity = (MapActivity) activity; + mapActivity.getMapLayers().selectMapLayer(mapActivity.getMapView(), null, null); + } + Toast.makeText(app, app.getString(R.string.map_imported_successfully), Toast.LENGTH_SHORT).show(); + } else { + Toast.makeText(app, app.getString(R.string.map_import_error) + ": " + error, Toast.LENGTH_SHORT).show(); + } + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/importfiles/XmlImportTask.java b/OsmAnd/src/net/osmand/plus/importfiles/XmlImportTask.java new file mode 100644 index 0000000000..bc66d77a76 --- /dev/null +++ b/OsmAnd/src/net/osmand/plus/importfiles/XmlImportTask.java @@ -0,0 +1,149 @@ +package net.osmand.plus.importfiles; + +import android.net.Uri; + +import androidx.annotation.NonNull; +import androidx.annotation.Nullable; +import androidx.fragment.app.FragmentActivity; + +import net.osmand.AndroidUtils; +import net.osmand.CallbackWithObject; +import net.osmand.IndexConstants; +import net.osmand.PlatformUtil; +import net.osmand.plus.AppInitializer.LoadRoutingFilesCallback; +import net.osmand.plus.R; +import net.osmand.plus.importfiles.ImportHelper.ImportType; +import net.osmand.router.RoutingConfiguration.Builder; +import net.osmand.util.Algorithms; + +import org.xmlpull.v1.XmlPullParser; +import org.xmlpull.v1.XmlPullParserException; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; + +import static net.osmand.IndexConstants.RENDERER_INDEX_EXT; +import static net.osmand.plus.AppInitializer.loadRoutingFiles; + +class XmlImportTask extends BaseImportAsyncTask { + + private Uri intentUri; + private String destFileName; + private ImportType importType; + private CallbackWithObject routingCallback; + + public XmlImportTask(@NonNull FragmentActivity activity, @NonNull Uri intentUri, + @NonNull String fileName, @Nullable CallbackWithObject routingCallback) { + super(activity); + this.intentUri = intentUri; + this.destFileName = fileName; + this.routingCallback = routingCallback; + } + + @Override + protected String doInBackground(Void... voids) { + checkImportType(); + if (importType != null) { + File dest = getDestinationFile(); + if (dest != null) { + return ImportHelper.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 destDir = getDestinationDir(); + File file = new File(destDir, destFileName); + if (error == null && file.exists()) { + 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 LoadRoutingFilesCallback() { + @Override + public void onRoutingFilesLoaded() { + hideProgress(); + 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)); + } + } + }); + } + } else { + hideProgress(); + app.showShortToastMessage(app.getString(R.string.file_import_error, destFileName, error)); + } + } + + 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(); + } + 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); + destFile = new File(destDir, destFileName); + } + return destFile; + } + return null; + } + + private void checkImportType() { + InputStream is = null; + try { + is = app.getContentResolver().openInputStream(intentUri); + if (is != null) { + 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; + } + } + Algorithms.closeStream(is); + } + } catch (FileNotFoundException | XmlPullParserException e) { + ImportHelper.log.error(e); + } catch (IOException e) { + ImportHelper.log.error(e); + } catch (SecurityException e) { + ImportHelper.log.error(e.getMessage(), e); + } finally { + Algorithms.closeStream(is); + } + } +} \ No newline at end of file diff --git a/OsmAnd/src/net/osmand/plus/measurementtool/StartPlanRouteBottomSheet.java b/OsmAnd/src/net/osmand/plus/measurementtool/StartPlanRouteBottomSheet.java index b81b015f32..fe02db28b8 100644 --- a/OsmAnd/src/net/osmand/plus/measurementtool/StartPlanRouteBottomSheet.java +++ b/OsmAnd/src/net/osmand/plus/measurementtool/StartPlanRouteBottomSheet.java @@ -28,8 +28,8 @@ import net.osmand.plus.base.bottomsheetmenu.simpleitems.DividerItem; import net.osmand.plus.base.bottomsheetmenu.simpleitems.TitleItem; import net.osmand.plus.helpers.GpxTrackAdapter; import net.osmand.plus.helpers.GpxUiHelper.GPXInfo; -import net.osmand.plus.helpers.ImportHelper; -import net.osmand.plus.helpers.ImportHelper.OnGpxImportCompleteListener; +import net.osmand.plus.importfiles.ImportHelper; +import net.osmand.plus.importfiles.ImportHelper.OnGpxImportCompleteListener; import org.apache.commons.logging.Log; diff --git a/OsmAnd/src/net/osmand/plus/myplaces/FavoritesActivity.java b/OsmAnd/src/net/osmand/plus/myplaces/FavoritesActivity.java index f310802c44..c77cfbfc0d 100644 --- a/OsmAnd/src/net/osmand/plus/myplaces/FavoritesActivity.java +++ b/OsmAnd/src/net/osmand/plus/myplaces/FavoritesActivity.java @@ -30,8 +30,8 @@ import net.osmand.plus.R; import net.osmand.plus.activities.FavoritesTreeFragment; import net.osmand.plus.activities.MapActivity; import net.osmand.plus.activities.TabActivity; -import net.osmand.plus.helpers.ImportHelper; -import net.osmand.plus.helpers.ImportHelper.OnGpxImportCompleteListener; +import net.osmand.plus.importfiles.ImportHelper; +import net.osmand.plus.importfiles.ImportHelper.OnGpxImportCompleteListener; import net.osmand.plus.settings.backend.OsmAndAppCustomization; import net.osmand.plus.settings.backend.OsmandSettings; import net.osmand.plus.views.controls.PagerSlidingTabStrip; diff --git a/OsmAnd/src/net/osmand/plus/profiles/SelectProfileBottomSheetDialogFragment.java b/OsmAnd/src/net/osmand/plus/profiles/SelectProfileBottomSheetDialogFragment.java index c7d7ec843c..743c9897ad 100644 --- a/OsmAnd/src/net/osmand/plus/profiles/SelectProfileBottomSheetDialogFragment.java +++ b/OsmAnd/src/net/osmand/plus/profiles/SelectProfileBottomSheetDialogFragment.java @@ -40,7 +40,7 @@ import org.apache.commons.logging.Log; import java.util.ArrayList; import java.util.List; -import static net.osmand.plus.helpers.ImportHelper.ImportType.ROUTING; +import static net.osmand.plus.importfiles.ImportHelper.ImportType.ROUTING; public class SelectProfileBottomSheetDialogFragment extends BasePreferenceBottomSheet { diff --git a/OsmAnd/src/net/osmand/plus/routepreparationmenu/FollowTrackFragment.java b/OsmAnd/src/net/osmand/plus/routepreparationmenu/FollowTrackFragment.java index ee2bf6b38e..48eba555cb 100644 --- a/OsmAnd/src/net/osmand/plus/routepreparationmenu/FollowTrackFragment.java +++ b/OsmAnd/src/net/osmand/plus/routepreparationmenu/FollowTrackFragment.java @@ -40,8 +40,8 @@ import net.osmand.plus.base.ContextMenuScrollFragment; import net.osmand.plus.helpers.AndroidUiHelper; import net.osmand.plus.helpers.GpxUiHelper; import net.osmand.plus.helpers.GpxUiHelper.GPXInfo; -import net.osmand.plus.helpers.ImportHelper; -import net.osmand.plus.helpers.ImportHelper.OnGpxImportCompleteListener; +import net.osmand.plus.importfiles.ImportHelper; +import net.osmand.plus.importfiles.ImportHelper.OnGpxImportCompleteListener; import net.osmand.plus.measurementtool.GpxData; import net.osmand.plus.measurementtool.GpxData.ActionType; import net.osmand.plus.measurementtool.MeasurementEditingContext; diff --git a/OsmAnd/src/net/osmand/plus/settings/backend/OsmAndAppCustomization.java b/OsmAnd/src/net/osmand/plus/settings/backend/OsmAndAppCustomization.java index b23edbbea1..c8025bc2d5 100644 --- a/OsmAnd/src/net/osmand/plus/settings/backend/OsmAndAppCustomization.java +++ b/OsmAnd/src/net/osmand/plus/settings/backend/OsmAndAppCustomization.java @@ -31,7 +31,7 @@ import net.osmand.plus.activities.PluginsActivity; import net.osmand.plus.activities.SettingsActivity; import net.osmand.plus.activities.TrackActivity; import net.osmand.plus.download.DownloadActivity; -import net.osmand.plus.helpers.ImportHelper; +import net.osmand.plus.importfiles.ImportHelper; import net.osmand.plus.helpers.WaypointHelper; import net.osmand.plus.myplaces.FavoritesActivity; import net.osmand.plus.routing.RouteCalculationResult; diff --git a/OsmAnd/src/net/osmand/plus/settings/fragments/MainSettingsFragment.java b/OsmAnd/src/net/osmand/plus/settings/fragments/MainSettingsFragment.java index 6aac50bc9c..2428290517 100644 --- a/OsmAnd/src/net/osmand/plus/settings/fragments/MainSettingsFragment.java +++ b/OsmAnd/src/net/osmand/plus/settings/fragments/MainSettingsFragment.java @@ -31,7 +31,7 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Set; -import static net.osmand.plus.helpers.ImportHelper.ImportType.SETTINGS; +import static net.osmand.plus.importfiles.ImportHelper.ImportType.SETTINGS; import static net.osmand.plus.profiles.SelectProfileBottomSheetDialogFragment.DIALOG_TYPE; import static net.osmand.plus.profiles.SelectProfileBottomSheetDialogFragment.IS_PROFILE_IMPORTED_ARG; import static net.osmand.plus.profiles.SelectProfileBottomSheetDialogFragment.PROFILE_KEY_ARG;