From 4e2e3b370ccc9f1a07e157d4bec736ffc528e4b3 Mon Sep 17 00:00:00 2001 From: OMGeeky Date: Thu, 8 Dec 2022 17:55:37 +0100 Subject: [PATCH] formatting --- .../activity/LoadSaveActivity.java | 824 +++++++++--------- .../rpg/AndorsTrail/util/AndroidStorage.java | 604 +++++++------ 2 files changed, 700 insertions(+), 728 deletions(-) diff --git a/AndorsTrail/app/src/main/java/com/gpl/rpg/AndorsTrail/activity/LoadSaveActivity.java b/AndorsTrail/app/src/main/java/com/gpl/rpg/AndorsTrail/activity/LoadSaveActivity.java index d51798569..712936f67 100644 --- a/AndorsTrail/app/src/main/java/com/gpl/rpg/AndorsTrail/activity/LoadSaveActivity.java +++ b/AndorsTrail/app/src/main/java/com/gpl/rpg/AndorsTrail/activity/LoadSaveActivity.java @@ -120,8 +120,7 @@ public final class LoadSaveActivity extends AndorsTrailBaseActivity implements O boolean hasSavegames = !Savegames.getUsedSavegameSlots(this).isEmpty(); exportSaves.setEnabled(hasSavegames); - } - else{ + } else { exportImportContainer.setVisibility(View.GONE); } } @@ -131,12 +130,17 @@ public final class LoadSaveActivity extends AndorsTrailBaseActivity implements O private static final int WRITE_EXTERNAL_STORAGE_REQUEST = 2; private void checkAndRequestPermissions() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q) { - if (getApplicationContext().checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { - this.requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE_REQUEST); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M + && Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q) { + if (getApplicationContext().checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) + != PackageManager.PERMISSION_GRANTED) { + this.requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, + READ_EXTERNAL_STORAGE_REQUEST); } - if (getApplicationContext().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { - this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE_REQUEST); + if (getApplicationContext().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) + != PackageManager.PERMISSION_GRANTED) { + this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, + WRITE_EXTERNAL_STORAGE_REQUEST); } } } @@ -150,15 +154,15 @@ public final class LoadSaveActivity extends AndorsTrailBaseActivity implements O } } - private void addSavegameSlotButtons(ViewGroup parent, - LayoutParams params, - List usedSavegameSlots) { - int unused = 1; - for (int slot : usedSavegameSlots) { - final FileHeader header = Savegames.quickload(this, slot); - if (header == null) { - continue; - } + private void addSavegameSlotButtons(ViewGroup parent, + LayoutParams params, + List usedSavegameSlots) { + int unused = 1; + for (int slot : usedSavegameSlots) { + final FileHeader header = Savegames.quickload(this, slot); + if (header == null) { + continue; + } while (unused < slot) { Button b = new Button(this); @@ -182,93 +186,92 @@ public final class LoadSaveActivity extends AndorsTrailBaseActivity implements O } } - private void cancelLoadSaveActivity(int slot){ + private void cancelLoadSaveActivity(int slot) { completeLoadSaveActivity(slot, false); } private void completeLoadSaveActivity(int slot) { completeLoadSaveActivity(slot, true); } + private void completeLoadSaveActivity(int slot, boolean success) { Intent i = new Intent(); if (slot == SLOT_NUMBER_CREATE_NEW_SLOT) { slot = getFirstFreeSlot(); } else if (slot == SLOT_NUMBER_EXPORT_SAVEGAMES - || slot == SLOT_NUMBER_IMPORT_SAVEGAMES - || slot == SLOT_NUMBER_IMPORT_WORLDMAP) { + || slot == SLOT_NUMBER_IMPORT_SAVEGAMES + || slot == SLOT_NUMBER_IMPORT_WORLDMAP) { i.putExtra("import_export", true); - if(slot == SLOT_NUMBER_IMPORT_WORLDMAP){ + if (slot == SLOT_NUMBER_IMPORT_WORLDMAP) { i.putExtra("import_worldmap", true); } - if(slot == SLOT_NUMBER_IMPORT_SAVEGAMES){ + if (slot == SLOT_NUMBER_IMPORT_SAVEGAMES) { i.putExtra("import_savegames", true); } - if(slot == SLOT_NUMBER_EXPORT_SAVEGAMES){ + if (slot == SLOT_NUMBER_EXPORT_SAVEGAMES) { i.putExtra("export", true); } - } - else if (slot < SLOT_NUMBER_FIRST_SLOT) { - slot = SLOT_NUMBER_FIRST_SLOT; - } + } else if (slot < SLOT_NUMBER_FIRST_SLOT) { + slot = SLOT_NUMBER_FIRST_SLOT; + } - i.putExtra("slot", slot); - if (success) { - setResult(Activity.RESULT_OK, i); - } - else { - setResult(Activity.RESULT_CANCELED, i); - } - LoadSaveActivity.this.finish(); - } + i.putExtra("slot", slot); + if (success) { + setResult(Activity.RESULT_OK, i); + } else { + setResult(Activity.RESULT_CANCELED, i); + } + LoadSaveActivity.this.finish(); + } - private int getFirstFreeSlot() { - int slot; - List usedSlots = Savegames.getUsedSavegameSlots(this); - if (usedSlots.isEmpty()) { - slot = SLOT_NUMBER_FIRST_SLOT; - } - else { - slot = Collections.max(usedSlots) + 1; - } - return slot; - } + private int getFirstFreeSlot() { + int slot; + List usedSlots = Savegames.getUsedSavegameSlots(this); + if (usedSlots.isEmpty()) { + slot = SLOT_NUMBER_FIRST_SLOT; + } else { + slot = Collections.max(usedSlots) + 1; + } + return slot; + } - private String getConfirmOverwriteQuestion(int slot) { - if (isLoading) { - return null; - } + private String getConfirmOverwriteQuestion(int slot) { + if (isLoading) { + return null; + } return getConfirmOverwriteQuestionIgnoringLoading(slot); } - private String getConfirmOverwriteQuestionIgnoringLoading(int slot) { - if (slot == SLOT_NUMBER_CREATE_NEW_SLOT) { - return null;//creating a new savegame - } + private String getConfirmOverwriteQuestionIgnoringLoading(int slot) { + if (slot == SLOT_NUMBER_CREATE_NEW_SLOT) { + return null;//creating a new savegame + } - if (!Savegames.getSlotFile(slot, this).exists()) { - return null;//nothing in slot to overwrite - } + if (!Savegames.getSlotFile(slot, this).exists()) { + return null;//nothing in slot to overwrite + } - if (preferences.displayOverwriteSavegame == AndorsTrailPreferences.CONFIRM_OVERWRITE_SAVEGAME_ALWAYS) { + if (preferences.displayOverwriteSavegame + == AndorsTrailPreferences.CONFIRM_OVERWRITE_SAVEGAME_ALWAYS) { return getString(R.string.loadsave_save_overwrite_confirmation_all); } if (preferences.displayOverwriteSavegame == AndorsTrailPreferences.CONFIRM_OVERWRITE_SAVEGAME_NEVER) { return null; } - final String currentPlayerName = model.player.getName(); - final FileHeader header = Savegames.quickload(this, slot); - if (header == null) { - return null; - } + final String currentPlayerName = model.player.getName(); + final FileHeader header = Savegames.quickload(this, slot); + if (header == null) { + return null; + } - final String savedPlayerName = header.playerName; - if (currentPlayerName.equals(savedPlayerName)) { - return null; //if the names match - } + final String savedPlayerName = header.playerName; + if (currentPlayerName.equals(savedPlayerName)) { + return null; //if the names match + } return getString(R.string.loadsave_save_overwrite_confirmation, savedPlayerName, currentPlayerName); } @@ -277,49 +280,49 @@ public final class LoadSaveActivity extends AndorsTrailBaseActivity implements O public void onClick(View view) { final int slot = (Integer) view.getTag(); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { - switch (slot) { - case SLOT_NUMBER_IMPORT_WORLDMAP: - clickImportWorldmap(); - return; - case SLOT_NUMBER_IMPORT_SAVEGAMES: - clickImportSaveGames(); - return; - case SLOT_NUMBER_EXPORT_SAVEGAMES: - clickExportSaveGames(); - return; - } - } - if (!isLoading - && slot != SLOT_NUMBER_CREATE_NEW_SLOT - && AndorsTrailApplication.CURRENT_VERSION - == AndorsTrailApplication.DEVELOPMENT_INCOMPATIBLE_SAVEGAME_VERSION) { - if (!isOverwriteTargetInIncompatibleVersion(slot)) { - saveOrOverwriteSavegame(slot); - } - } - else if (isLoading) { - loadSaveGame(slot); - } - else { - saveOrOverwriteSavegame(slot); - } - } + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { + switch (slot) { + case SLOT_NUMBER_IMPORT_WORLDMAP: + clickImportWorldmap(); + return; + case SLOT_NUMBER_IMPORT_SAVEGAMES: + clickImportSaveGames(); + return; + case SLOT_NUMBER_EXPORT_SAVEGAMES: + clickExportSaveGames(); + return; + } + } + if (!isLoading + && slot != SLOT_NUMBER_CREATE_NEW_SLOT + && AndorsTrailApplication.CURRENT_VERSION + == AndorsTrailApplication.DEVELOPMENT_INCOMPATIBLE_SAVEGAME_VERSION) { + if (!isOverwriteTargetInIncompatibleVersion(slot)) { + saveOrOverwriteSavegame(slot); + } + } else if (isLoading) { + loadSaveGame(slot); + } else { + saveOrOverwriteSavegame(slot); + } + } - private void saveOrOverwriteSavegame(int slot) { - final String message = getConfirmOverwriteQuestion(slot); - if (message != null) { - showConfirmOverwriteQuestion(slot, message); - } - else { - completeLoadSaveActivity(slot); - } - } + private void saveOrOverwriteSavegame(int slot) { + final String message = getConfirmOverwriteQuestion(slot); + if (message != null) { + showConfirmOverwriteQuestion(slot, message); + } else { + completeLoadSaveActivity(slot); + } + } private boolean isOverwriteTargetInIncompatibleVersion(int slot) { final FileHeader header = Savegames.quickload(this, slot); - if (header != null && header.fileversion != AndorsTrailApplication.DEVELOPMENT_INCOMPATIBLE_SAVEGAME_VERSION) { - final CustomDialog d = CustomDialogFactory.createErrorDialog(this, "Overwriting not allowed", "You are currently using a development version of Andor's trail. Overwriting a regular savegame is not allowed in development mode."); + if (header != null + && header.fileversion != AndorsTrailApplication.DEVELOPMENT_INCOMPATIBLE_SAVEGAME_VERSION) { + final CustomDialog d = CustomDialogFactory.createErrorDialog(this, + "Overwriting not allowed", + "You are currently using a development version of Andor's trail. Overwriting a regular savegame is not allowed in development mode."); CustomDialogFactory.show(d); return true; } @@ -333,24 +336,24 @@ public final class LoadSaveActivity extends AndorsTrailBaseActivity implements O Uri uri = data.getData(); Context context = getApplicationContext(); - ContentResolver resolver = AndorsTrailApplication.getApplicationFromActivity(this).getContentResolver(); + ContentResolver resolver = AndorsTrailApplication.getApplicationFromActivity(this) + .getContentResolver(); - File storageDir = AndroidStorage.getStorageDirectory(context, - Constants.FILENAME_SAVEGAME_DIRECTORY); - DocumentFile target = DocumentFile.fromTreeUri(context, uri); - if (target == null) { - return; - } + File storageDir = AndroidStorage.getStorageDirectory(context, Constants.FILENAME_SAVEGAME_DIRECTORY); + DocumentFile target = DocumentFile.fromTreeUri(context, uri); + if (target == null) { + return; + } - File[] files = storageDir.listFiles(); - if (files == null) { - showErrorExportingSaveGamesUnknown(); - return; - } + File[] files = storageDir.listFiles(); + if (files == null) { + showErrorExportingSaveGamesUnknown(); + return; + } - boolean hasExistingFiles = false; - for (File file : files) { - String fileName = file.getName(); + boolean hasExistingFiles = false; + for (File file : files) { + String fileName = file.getName(); DocumentFile existingFile = target.findFile(fileName); if (existingFile != null) { @@ -359,127 +362,118 @@ public final class LoadSaveActivity extends AndorsTrailBaseActivity implements O } } - if (hasExistingFiles) { - showConfirmOverwriteByExportQuestion(resolver, target, files); - } - else { - exportSaveGamesFolderContentToFolder(target, files); - } - } + if (hasExistingFiles) { + showConfirmOverwriteByExportQuestion(resolver, target, files); + } else { + exportSaveGamesFolderContentToFolder(target, files); + } + } - @RequiresApi(api = Build.VERSION_CODES.P) - private void exportSaveGamesFolderContentToFolder(DocumentFile target, File[] files) { - DocumentFile[] sourceFiles = new DocumentFile[files.length]; + @RequiresApi(api = Build.VERSION_CODES.P) + private void exportSaveGamesFolderContentToFolder(DocumentFile target, File[] files) { + DocumentFile[] sourceFiles = new DocumentFile[files.length]; - File[] worldmapFiles = null; + File[] worldmapFiles = null; - for (int i = 0; i < files.length; i++) { - File file = files[i]; - if (file.isFile()) { - sourceFiles[i] = DocumentFile.fromFile(file); - } - else if (file.isDirectory() && Objects.equals(file.getName(), - Constants.FILENAME_WORLDMAP_DIRECTORY)) { - worldmapFiles = file.listFiles(); - } - } - Context context = this; - File[] finalWorldmapFiles = worldmapFiles; - AndroidStorage.copyDocumentFilesToDirAsync(sourceFiles, - context, - target, - getString(R.string.loadsave_exporting_savegames), - (success) -> { - if (success) { - AndroidStorage.createZipDocumentFileFromFilesAsync( - finalWorldmapFiles, - context, - target, - Constants.FILENAME_WORLDMAP_DIRECTORY, - getString(R.string.loadsave_exporting_worldmap), - (successWorldmap) -> completeLoadSaveActivity( - SLOT_NUMBER_EXPORT_SAVEGAMES, - successWorldmap)); - } - else { - completeLoadSaveActivity( - SLOT_NUMBER_EXPORT_SAVEGAMES, - false); - } - }); + for (int i = 0; i < files.length; i++) { + File file = files[i]; + if (file.isFile()) { + sourceFiles[i] = DocumentFile.fromFile(file); + } else if (file.isDirectory() && Objects.equals(file.getName(), + Constants.FILENAME_WORLDMAP_DIRECTORY)) { + worldmapFiles = file.listFiles(); + } + } + Context context = this; + File[] finalWorldmapFiles = worldmapFiles; + AndroidStorage.copyDocumentFilesToDirAsync(sourceFiles, + context, + target, + getString(R.string.loadsave_exporting_savegames), + (success) -> { + if (success) { + AndroidStorage.createZipDocumentFileFromFilesAsync( + finalWorldmapFiles, + context, + target, + Constants.FILENAME_WORLDMAP_DIRECTORY, + getString(R.string.loadsave_exporting_worldmap), + (successWorldmap) -> completeLoadSaveActivity( + SLOT_NUMBER_EXPORT_SAVEGAMES, + successWorldmap)); + } else { + completeLoadSaveActivity( + SLOT_NUMBER_EXPORT_SAVEGAMES, + false); + } + }); } - @RequiresApi(api = Build.VERSION_CODES.P) - private void importSaveGames(Intent data) { - Uri uri = data.getData(); - ClipData uris = data.getClipData(); + @RequiresApi(api = Build.VERSION_CODES.P) + private void importSaveGames(Intent data) { + Uri uri = data.getData(); + ClipData uris = data.getClipData(); if (uri == null && uris == null) { //no file was selected return; } - Context context = getApplicationContext(); - ContentResolver resolver = AndorsTrailApplication.getApplicationFromActivity(this) - .getContentResolver(); + Context context = getApplicationContext(); + ContentResolver resolver = AndorsTrailApplication.getApplicationFromActivity(this) + .getContentResolver(); File storageDir = AndroidStorage.getStorageDirectory(context, Constants.FILENAME_SAVEGAME_DIRECTORY); DocumentFile appSavegameFolder = DocumentFile.fromFile(storageDir); - List uriList = new ArrayList<>(); - if (uri != null) { - uriList.add(uri); - } - else { - for (int i = 0; i < uris.getItemCount(); i++) { - uriList.add(uris.getItemAt(i).getUri()); - } - } - importSaveGamesFromUris(context, resolver, appSavegameFolder, uriList); - } + List uriList = new ArrayList<>(); + if (uri != null) { + uriList.add(uri); + } else { + for (int i = 0; i < uris.getItemCount(); i++) { + uriList.add(uris.getItemAt(i).getUri()); + } + } + importSaveGamesFromUris(context, resolver, appSavegameFolder, uriList); + } - @RequiresApi(api = Build.VERSION_CODES.P) - private void importSaveGamesFromUris(Context context, - ContentResolver resolver, - DocumentFile appSavegameFolder, - List uriList) { - int count = uriList.size(); + @RequiresApi(api = Build.VERSION_CODES.P) + private void importSaveGamesFromUris(Context context, + ContentResolver resolver, + DocumentFile appSavegameFolder, + List uriList) { + int count = uriList.size(); ArrayList alreadyExistingFiles = new ArrayList<>(); ArrayList newFiles = new ArrayList<>(); - for (int i = 0; i < count; i++) { - Uri item = uriList.get(i); - DocumentFile itemFile = DocumentFile.fromSingleUri(context, item); - boolean fileAlreadyExists = getExistsSavegameInOwnFiles(itemFile, appSavegameFolder); - if (fileAlreadyExists) { - alreadyExistingFiles.add(itemFile); - } - else { - newFiles.add(itemFile); - } - } + for (int i = 0; i < count; i++) { + Uri item = uriList.get(i); + DocumentFile itemFile = DocumentFile.fromSingleUri(context, item); + boolean fileAlreadyExists = getExistsSavegameInOwnFiles(itemFile, appSavegameFolder); + if (fileAlreadyExists) { + alreadyExistingFiles.add(itemFile); + } else { + newFiles.add(itemFile); + } + } - if (alreadyExistingFiles.size() > 0) { - showConfirmOverwriteByImportQuestion(resolver, - appSavegameFolder, - alreadyExistingFiles, - newFiles); - } - else { - importSaveGames(resolver, appSavegameFolder, newFiles); - } - } + if (alreadyExistingFiles.size() > 0) { + showConfirmOverwriteByImportQuestion(resolver, appSavegameFolder, alreadyExistingFiles, newFiles); + } else { + importSaveGames(resolver, appSavegameFolder, newFiles); + } + } - @RequiresApi(api = Build.VERSION_CODES.P) - private void importSaveGames(ContentResolver resolver, - DocumentFile appSavegameFolder, - List saveFiles) { - int size = saveFiles.size(); - DocumentFile[] sources = new DocumentFile[size]; - DocumentFile[] targets = new DocumentFile[size]; + @RequiresApi(api = Build.VERSION_CODES.P) + private void importSaveGames(ContentResolver resolver, + DocumentFile appSavegameFolder, + List saveFiles) { + int size = saveFiles.size(); + DocumentFile[] sources = new DocumentFile[size]; + DocumentFile[] targets = new DocumentFile[size]; boolean saveAsNew = false; for (int i = 0; i < size; i++) { @@ -505,20 +499,19 @@ public final class LoadSaveActivity extends AndorsTrailBaseActivity implements O targets[i] = getOrCreateDocumentFile(appSavegameFolder, targetName); } - AndroidStorage.copyDocumentFilesFromToAsync(sources, - this, - targets, - getString(R.string.loadsave_importing_savegames), - (sucess) -> completeLoadSaveActivity( - SLOT_NUMBER_IMPORT_SAVEGAMES, - sucess)); - } + AndroidStorage.copyDocumentFilesFromToAsync(sources, + this, + targets, + getString(R.string.loadsave_importing_savegames), + (sucess) -> completeLoadSaveActivity( + SLOT_NUMBER_IMPORT_SAVEGAMES, + sucess)); + } - private boolean getExistsSavegameInOwnFiles(DocumentFile savegameFile, - DocumentFile appSavegameFolder) { - if (savegameFile == null) { - return false; - } + private boolean getExistsSavegameInOwnFiles(DocumentFile savegameFile, DocumentFile appSavegameFolder) { + if (savegameFile == null) { + return false; + } DocumentFile foundFile = appSavegameFolder.findFile(Objects.requireNonNull(savegameFile.getName())); return foundFile != null && foundFile.exists(); @@ -541,109 +534,106 @@ public final class LoadSaveActivity extends AndorsTrailBaseActivity implements O } } - private DocumentFile getOrCreateDocumentFile(DocumentFile folder, String targetName) { - DocumentFile targetFile = folder.findFile(targetName);//try finding the file - if (targetFile == null)//no file found, creating new one - { - targetFile = folder.createFile(Constants.NO_FILE_EXTENSION_MIME_TYPE, targetName); - } - return targetFile; - } + private DocumentFile getOrCreateDocumentFile(DocumentFile folder, String targetName) { + DocumentFile targetFile = folder.findFile(targetName);//try finding the file + if (targetFile == null)//no file found, creating new one + { + targetFile = folder.createFile(Constants.NO_FILE_EXTENSION_MIME_TYPE, targetName); + } + return targetFile; + } @RequiresApi(api = Build.VERSION_CODES.P) private void importWorldmap(Intent data) { Uri uri = data.getData(); - Context context = AndorsTrailApplication.getApplicationFromActivity(this) - .getApplicationContext(); + Context context = AndorsTrailApplication.getApplicationFromActivity(this).getApplicationContext(); - DocumentFile chosenZip = DocumentFile.fromSingleUri(context, uri); - if (chosenZip == null || !chosenZip.isFile()) { - showErrorImportingWorldmapWrongDirectory(); - return; - } - String chosenZipName = chosenZip.getName(); - if (!chosenZipName.startsWith(Constants.FILENAME_WORLDMAP_DIRECTORY)) { - showErrorImportingWorldmapWrongDirectory(); - return; - } + DocumentFile chosenZip = DocumentFile.fromSingleUri(context, uri); + if (chosenZip == null || !chosenZip.isFile()) { + showErrorImportingWorldmapWrongDirectory(); + return; + } + String chosenZipName = chosenZip.getName(); + if (!chosenZipName.startsWith(Constants.FILENAME_WORLDMAP_DIRECTORY)) { + showErrorImportingWorldmapWrongDirectory(); + return; + } - File ownWorldmapFolder = getOwnWorldmapFolder(context); + File ownWorldmapFolder = getOwnWorldmapFolder(context); - AndroidStorage.unzipDocumentFileToDirectoryAsync(chosenZip, - this, - ownWorldmapFolder, - false, - getString(R.string.loadsave_importing_worldmap), - (success) -> completeLoadSaveActivity( - SLOT_NUMBER_IMPORT_WORLDMAP, - success)); - } + AndroidStorage.unzipDocumentFileToDirectoryAsync(chosenZip, + this, + ownWorldmapFolder, + false, + getString(R.string.loadsave_importing_worldmap), + (success) -> completeLoadSaveActivity( + SLOT_NUMBER_IMPORT_WORLDMAP, + success)); + } - private File getOwnWorldmapFolder(Context context) { - File storageDir = AndroidStorage.getStorageDirectory(context, - Constants.FILENAME_SAVEGAME_DIRECTORY); - File ownWorldmapFolder = null; - for (File f : storageDir.listFiles()) { - if (f.getName().equals(Constants.FILENAME_WORLDMAP_DIRECTORY)) { - ownWorldmapFolder = f; - break; - } - } - if (ownWorldmapFolder == null) { - ownWorldmapFolder = new File(storageDir, Constants.FILENAME_WORLDMAP_DIRECTORY); - ownWorldmapFolder.mkdir(); - } - return ownWorldmapFolder; - } + private File getOwnWorldmapFolder(Context context) { + File storageDir = AndroidStorage.getStorageDirectory(context, Constants.FILENAME_SAVEGAME_DIRECTORY); + File ownWorldmapFolder = null; + for (File f : storageDir.listFiles()) { + if (f.getName().equals(Constants.FILENAME_WORLDMAP_DIRECTORY)) { + ownWorldmapFolder = f; + break; + } + } + if (ownWorldmapFolder == null) { + ownWorldmapFolder = new File(storageDir, Constants.FILENAME_WORLDMAP_DIRECTORY); + ownWorldmapFolder.mkdir(); + } + return ownWorldmapFolder; + } - @RequiresApi(api = Build.VERSION_CODES.P) - private void clickExportSaveGames() { - showStartExportInfo(view -> startActivityForResult(AndroidStorage.getNewOpenDirectoryIntent(), - -SLOT_NUMBER_EXPORT_SAVEGAMES)); - } + @RequiresApi(api = Build.VERSION_CODES.P) + private void clickExportSaveGames() { + showStartExportInfo(view -> startActivityForResult(AndroidStorage.getNewOpenDirectoryIntent(), + -SLOT_NUMBER_EXPORT_SAVEGAMES)); + } - @RequiresApi(api = Build.VERSION_CODES.P) - private void clickImportSaveGames() { - showStartImportSavesInfo(view -> startActivityForResult(AndroidStorage.getNewSelectMultipleSavegameFilesIntent(), - -SLOT_NUMBER_IMPORT_SAVEGAMES)); - } + @RequiresApi(api = Build.VERSION_CODES.P) + private void clickImportSaveGames() { + showStartImportSavesInfo(view -> startActivityForResult(AndroidStorage.getNewSelectMultipleSavegameFilesIntent(), + -SLOT_NUMBER_IMPORT_SAVEGAMES)); + } - @RequiresApi(api = Build.VERSION_CODES.P) - private void clickImportWorldmap() { - showStartImportWorldmapInfo(view -> startActivityForResult(AndroidStorage.getNewSelectZipIntent(), - -SLOT_NUMBER_IMPORT_WORLDMAP)); + @RequiresApi(api = Build.VERSION_CODES.P) + private void clickImportWorldmap() { + showStartImportWorldmapInfo(view -> startActivityForResult(AndroidStorage.getNewSelectZipIntent(), + -SLOT_NUMBER_IMPORT_WORLDMAP)); } - @RequiresApi(api = Build.VERSION_CODES.P) - private void showConfirmOverwriteByExportQuestion(ContentResolver resolver, - DocumentFile targetFolder, - File[] files) { - final CustomDialog d = CustomDialogFactory.createDialog(this, - getString(R.string.loadsave_export_overwrite_confirmation_title), - getResources().getDrawable(android.R.drawable.ic_dialog_alert), - getString(R.string.loadsave_export_overwrite_confirmation), - null, - true); + @RequiresApi(api = Build.VERSION_CODES.P) + private void showConfirmOverwriteByExportQuestion(ContentResolver resolver, + DocumentFile targetFolder, + File[] files) { + final CustomDialog d = CustomDialogFactory.createDialog(this, + getString(R.string.loadsave_export_overwrite_confirmation_title), + getResources().getDrawable(android.R.drawable.ic_dialog_alert), + getString(R.string.loadsave_export_overwrite_confirmation), + null, + true); - CustomDialogFactory.addButton(d, - android.R.string.yes, - v -> exportSaveGamesFolderContentToFolder(targetFolder, - files)); - CustomDialogFactory.addDismissButton(d, android.R.string.no); + CustomDialogFactory.addButton(d, + android.R.string.yes, + v -> exportSaveGamesFolderContentToFolder(targetFolder, files)); + CustomDialogFactory.addDismissButton(d, android.R.string.no); CustomDialogFactory.show(d); } - @RequiresApi(api = Build.VERSION_CODES.P) - private void showConfirmOverwriteByImportQuestion(ContentResolver resolver, - DocumentFile appSavegameFolder, - List alreadyExistingFiles, - List newFiles) { - final String title = getString(R.string.loadsave_import_overwrite_confirmation_title); - String message = getString(R.string.loadsave_import_file_exists_question); + @RequiresApi(api = Build.VERSION_CODES.P) + private void showConfirmOverwriteByImportQuestion(ContentResolver resolver, + DocumentFile appSavegameFolder, + List alreadyExistingFiles, + List newFiles) { + final String title = getString(R.string.loadsave_import_overwrite_confirmation_title); + String message = getString(R.string.loadsave_import_file_exists_question); StringBuilder sb = new StringBuilder(); sb.append('\n'); @@ -651,9 +641,9 @@ public final class LoadSaveActivity extends AndorsTrailBaseActivity implements O Context context = AndorsTrailApplication.getApplicationFromActivity(this).getApplicationContext(); - ArrayList dialogs = new ArrayList(amount) ; + ArrayList dialogs = new ArrayList<>(amount); - for (int i = 0; i < amount ; i++) { + for (int i = 0; i < amount; i++) { DocumentFile alreadyExistingFile = alreadyExistingFiles.get(i); int slot = getSlotFromSavegameFileName(alreadyExistingFile.getName()); FileHeader existingFileHeader = Savegames.quickload(context, slot); @@ -669,29 +659,27 @@ public final class LoadSaveActivity extends AndorsTrailBaseActivity implements O continue; } - StringBuilder messageSb = new StringBuilder(); - String existingFileDescription = - getString(R.string.loadsave_import_existing_description, - Integer.toString(slot), - existingFileHeader.describe()); - String importedFileDescription = - getString(R.string.loadsave_import_imported_description, - Integer.toString(slot), - importedFileHeader.describe()); - messageSb.append(getString(R.string.loadsave_import_file_exists_question, - existingFileDescription, - importedFileDescription)); + StringBuilder messageSb = new StringBuilder(); + String existingFileDescription = getString(R.string.loadsave_import_existing_description, + Integer.toString(slot), + existingFileHeader.describe()); + String importedFileDescription = getString(R.string.loadsave_import_imported_description, + Integer.toString(slot), + importedFileHeader.describe()); + messageSb.append(getString(R.string.loadsave_import_file_exists_question, + existingFileDescription, + importedFileDescription)); String m = messageSb.toString(); CustomDialog dialog = CustomDialogFactory.createDialog(this, - title, - getResources().getDrawable(android.R.drawable.ic_dialog_alert), - m, - null, - true, - false, - true); + title, + getResources().getDrawable(android.R.drawable.ic_dialog_alert), + m, + null, + true, + false, + true); CustomDialogFactory.addButton(dialog, R.string.loadsave_import_option_keep_existing, v -> { //do nothing @@ -703,13 +691,12 @@ public final class LoadSaveActivity extends AndorsTrailBaseActivity implements O GoToNextConflictOrFinish(resolver, appSavegameFolder, newFiles, dialogs); }); - CustomDialogFactory.addButton(dialog, R.string.loadsave_import_option_add_as_new, - v -> { - newFiles.add(null);//add a null element as marker to know later if the next file - // should be imported as new or overwrite the existing one - newFiles.add(alreadyExistingFile); - GoToNextConflictOrFinish(resolver, appSavegameFolder, newFiles, dialogs); - }); + CustomDialogFactory.addButton(dialog, R.string.loadsave_import_option_add_as_new, v -> { + newFiles.add(null);//add a null element as marker to know later if the next file + // should be imported as new or overwrite the existing one + newFiles.add(alreadyExistingFile); + GoToNextConflictOrFinish(resolver, appSavegameFolder, newFiles, dialogs); + }); CustomDialogFactory.addCancelButton(dialog, android.R.string.cancel); CustomDialogFactory.setCancelListener(dialog, v -> { @@ -722,27 +709,26 @@ public final class LoadSaveActivity extends AndorsTrailBaseActivity implements O GoToNextConflictOrFinish(resolver, appSavegameFolder, newFiles, dialogs); } - @RequiresApi(api = Build.VERSION_CODES.P) - private void GoToNextConflictOrFinish(ContentResolver resolver, - DocumentFile appSavegameFolder, - List newFiles, - ArrayList dialogs) { - if (dialogs.stream().count() > 0) { - CustomDialog d = dialogs.remove(0); - CustomDialogFactory.show(d); - } - else { - importSaveGames(resolver, appSavegameFolder, newFiles); - } - } + @RequiresApi(api = Build.VERSION_CODES.P) + private void GoToNextConflictOrFinish(ContentResolver resolver, + DocumentFile appSavegameFolder, + List newFiles, + ArrayList dialogs) { + if (dialogs.stream().count() > 0) { + CustomDialog d = dialogs.remove(0); + CustomDialogFactory.show(d); + } else { + importSaveGames(resolver, appSavegameFolder, newFiles); + } + } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); - if (resultCode != Activity.RESULT_OK) { - return; - } + if (resultCode != Activity.RESULT_OK) { + return; + } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { switch (-requestCode) { @@ -777,86 +763,86 @@ public final class LoadSaveActivity extends AndorsTrailBaseActivity implements O //region show Dialogs - @RequiresApi(api = Build.VERSION_CODES.P) - private void showStartExportInfo(OnClickListener onOk) { - final CustomDialog d = CustomDialogFactory.createDialog(this, - getString(R.string.loadsave_export), - getResources().getDrawable(android.R.drawable.ic_dialog_info), - getString(R.string.loadsave_export_info), - null, - true); - CustomDialogFactory.addButton(d, android.R.string.yes, onOk); - CustomDialogFactory.addDismissButton(d, android.R.string.no); - CustomDialogFactory.show(d); - } + @RequiresApi(api = Build.VERSION_CODES.P) + private void showStartExportInfo(OnClickListener onOk) { + final CustomDialog d = CustomDialogFactory.createDialog(this, + getString(R.string.loadsave_export), + getResources().getDrawable(android.R.drawable.ic_dialog_info), + getString(R.string.loadsave_export_info), + null, + true); + CustomDialogFactory.addButton(d, android.R.string.yes, onOk); + CustomDialogFactory.addDismissButton(d, android.R.string.no); + CustomDialogFactory.show(d); + } - @RequiresApi(api = Build.VERSION_CODES.P) - private void showStartImportSavesInfo(OnClickListener onOk) { - final CustomDialog d = CustomDialogFactory.createDialog(this, - getString(R.string.loadsave_import_save), - getResources().getDrawable(android.R.drawable.ic_dialog_info), - getString(R.string.loadsave_import_save_info), - null, - true); - CustomDialogFactory.addButton(d, android.R.string.yes, onOk); - CustomDialogFactory.addDismissButton(d, android.R.string.no); - CustomDialogFactory.show(d); - } + @RequiresApi(api = Build.VERSION_CODES.P) + private void showStartImportSavesInfo(OnClickListener onOk) { + final CustomDialog d = CustomDialogFactory.createDialog(this, + getString(R.string.loadsave_import_save), + getResources().getDrawable(android.R.drawable.ic_dialog_info), + getString(R.string.loadsave_import_save_info), + null, + true); + CustomDialogFactory.addButton(d, android.R.string.yes, onOk); + CustomDialogFactory.addDismissButton(d, android.R.string.no); + CustomDialogFactory.show(d); + } - @RequiresApi(api = Build.VERSION_CODES.P) - private void showStartImportWorldmapInfo(OnClickListener onOk) { - final CustomDialog d = CustomDialogFactory.createDialog(this, - getString(R.string.loadsave_import_worldmap), - getResources().getDrawable(android.R.drawable.ic_dialog_info), - getString(R.string.loadsave_import_worldmap_info), - null, - true); - CustomDialogFactory.addButton(d, android.R.string.yes, onOk); - CustomDialogFactory.addDismissButton(d, android.R.string.no); - CustomDialogFactory.show(d); - } + @RequiresApi(api = Build.VERSION_CODES.P) + private void showStartImportWorldmapInfo(OnClickListener onOk) { + final CustomDialog d = CustomDialogFactory.createDialog(this, + getString(R.string.loadsave_import_worldmap), + getResources().getDrawable(android.R.drawable.ic_dialog_info), + getString(R.string.loadsave_import_worldmap_info), + null, + true); + CustomDialogFactory.addButton(d, android.R.string.yes, onOk); + CustomDialogFactory.addDismissButton(d, android.R.string.no); + CustomDialogFactory.show(d); + } - private void showErrorImportingWorldmapWrongDirectory() { - final CustomDialog d = CustomDialogFactory.createErrorDialog(this, - getString(R.string.loadsave_import_worldmap_unsuccessfull), - getString(R.string.loadsave_import_worldmap_wrong_file)); - CustomDialogFactory.show(d); - } + private void showErrorImportingWorldmapWrongDirectory() { + final CustomDialog d = CustomDialogFactory.createErrorDialog(this, + getString(R.string.loadsave_import_worldmap_unsuccessfull), + getString(R.string.loadsave_import_worldmap_wrong_file)); + CustomDialogFactory.show(d); + } - private void showErrorExportingSaveGamesUnknown() { - final CustomDialog d = CustomDialogFactory.createErrorDialog(this, - getString(R.string.loadsave_export_unsuccessfull), - getString(R.string.loadsave_export_error_unknown)); - CustomDialogFactory.show(d); - } + private void showErrorExportingSaveGamesUnknown() { + final CustomDialog d = CustomDialogFactory.createErrorDialog(this, + getString(R.string.loadsave_export_unsuccessfull), + getString(R.string.loadsave_export_error_unknown)); + CustomDialogFactory.show(d); + } private void showErrorLoadingEmptySlot() { final CustomDialog d = CustomDialogFactory.createErrorDialog(this, - getString(R.string.startscreen_error_loading_game), - getString(R.string.startscreen_error_loading_empty_slot)); + getString(R.string.startscreen_error_loading_game), + getString(R.string.startscreen_error_loading_empty_slot)); CustomDialogFactory.show(d); } private void showSlotGetsDeletedOnLoadWarning(final int slot) { final CustomDialog d = CustomDialogFactory.createDialog(this, - getString(R.string.startscreen_attention_slot_gets_delete_on_load), - getResources().getDrawable(android.R.drawable.ic_dialog_alert), - getString(R.string.startscreen_attention_message_slot_gets_delete_on_load), - null, - true); + getString(R.string.startscreen_attention_slot_gets_delete_on_load), + getResources().getDrawable(android.R.drawable.ic_dialog_alert), + getString(R.string.startscreen_attention_message_slot_gets_delete_on_load), + null, + true); CustomDialogFactory.addButton(d, android.R.string.ok, v -> completeLoadSaveActivity(slot)); CustomDialogFactory.show(d); } - private void showConfirmOverwriteQuestion(final int slot, String message) { + private void showConfirmOverwriteQuestion(final int slot, String message) { final String title = getString(R.string.loadsave_save_overwrite_confirmation_title) + ' ' + getString(R.string.loadsave_save_overwrite_confirmation_slot, slot); - final CustomDialog d = CustomDialogFactory.createDialog(this, - title, - getResources().getDrawable(android.R.drawable.ic_dialog_alert), - message, - null, - true); + final CustomDialog d = CustomDialogFactory.createDialog(this, + title, + getResources().getDrawable(android.R.drawable.ic_dialog_alert), + message, + null, + true); CustomDialogFactory.addButton(d, android.R.string.yes, v -> completeLoadSaveActivity(slot)); CustomDialogFactory.addDismissButton(d, android.R.string.no); diff --git a/AndorsTrail/app/src/main/java/com/gpl/rpg/AndorsTrail/util/AndroidStorage.java b/AndorsTrail/app/src/main/java/com/gpl/rpg/AndorsTrail/util/AndroidStorage.java index 010f27ae4..6923005a9 100644 --- a/AndorsTrail/app/src/main/java/com/gpl/rpg/AndorsTrail/util/AndroidStorage.java +++ b/AndorsTrail/app/src/main/java/com/gpl/rpg/AndorsTrail/util/AndroidStorage.java @@ -35,8 +35,7 @@ public final class AndroidStorage { public static File getStorageDirectory(Context context, String name) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { return context.getExternalFilesDir(name); - } - else { + } else { File root = Environment.getExternalStorageDirectory(); return new File(root, name); } @@ -44,35 +43,33 @@ public final class AndroidStorage { public static boolean shouldMigrateToInternalStorage(Context context) { boolean ret = false; - File externalSaveGameDirectory = new File(Environment.getExternalStorageDirectory(), Constants.FILENAME_SAVEGAME_DIRECTORY); + File externalSaveGameDirectory = new File(Environment.getExternalStorageDirectory(), + Constants.FILENAME_SAVEGAME_DIRECTORY); File internalSaveGameDirectory = getStorageDirectory(context, Constants.FILENAME_SAVEGAME_DIRECTORY); if (externalSaveGameDirectory.exists() - && externalSaveGameDirectory.isDirectory() - && externalSaveGameDirectory.listFiles().length > 0 - && ( - !internalSaveGameDirectory.exists() - || internalSaveGameDirectory.isDirectory() && internalSaveGameDirectory.listFiles().length < 2) - ) { + && externalSaveGameDirectory.isDirectory() + && externalSaveGameDirectory.listFiles().length > 0 + && (!internalSaveGameDirectory.exists() + || internalSaveGameDirectory.isDirectory() + && internalSaveGameDirectory.listFiles().length < 2)) { ret = true; } return ret; } - public static boolean migrateToInternalStorage(Context context) { - try { - copy(new File(Environment.getExternalStorageDirectory(), - Constants.CHEAT_DETECTION_FOLDER), - getStorageDirectory(context, Constants.CHEAT_DETECTION_FOLDER)); - copy(new File(Environment.getExternalStorageDirectory(), - Constants.FILENAME_SAVEGAME_DIRECTORY), - getStorageDirectory(context, Constants.FILENAME_SAVEGAME_DIRECTORY)); - } catch (IOException e) { - L.log("Error migrating data: " + e); - return false; - } - return true; - } + public static boolean migrateToInternalStorage(Context context) { + try { + copy(new File(Environment.getExternalStorageDirectory(), Constants.CHEAT_DETECTION_FOLDER), + getStorageDirectory(context, Constants.CHEAT_DETECTION_FOLDER)); + copy(new File(Environment.getExternalStorageDirectory(), Constants.FILENAME_SAVEGAME_DIRECTORY), + getStorageDirectory(context, Constants.FILENAME_SAVEGAME_DIRECTORY)); + } catch (IOException e) { + L.log("Error migrating data: " + e); + return false; + } + return true; + } private static void copy(File sourceLocation, File targetLocation) throws IOException { if (!sourceLocation.exists()) { @@ -109,195 +106,188 @@ public final class AndroidStorage { } } - @RequiresApi(api = Build.VERSION_CODES.P) - public static void createZipDocumentFileFromFilesAsync(File[] files, - Context context, - DocumentFile targetDirectory, - String fileName, - String loadingMessage, - Consumer callback) { + @RequiresApi(api = Build.VERSION_CODES.P) + public static void createZipDocumentFileFromFilesAsync(File[] files, + Context context, + DocumentFile targetDirectory, + String fileName, + String loadingMessage, + Consumer callback) { - BackgroundWorker worker = new BackgroundWorker<>(); - CustomDialogFactory.CustomDialog progressDialog = getLoadingDialog(context, - loadingMessage); - progressDialog.setOnCancelListener(dialog -> worker.cancel()); - ContentResolver resolver = context.getContentResolver(); - Handler handler = Handler.createAsync(Looper.getMainLooper()); + BackgroundWorker worker = new BackgroundWorker<>(); + CustomDialogFactory.CustomDialog progressDialog = getLoadingDialog(context, loadingMessage); + progressDialog.setOnCancelListener(dialog -> worker.cancel()); + ContentResolver resolver = context.getContentResolver(); + Handler handler = Handler.createAsync(Looper.getMainLooper()); - worker.setTask(workerCallback -> { - try { - workerCallback.onInitialize(); + worker.setTask(workerCallback -> { + try { + workerCallback.onInitialize(); - //region create zip file - File zip = File.createTempFile("temp_worldmap", ".zip"); - try (OutputStream out = new FileOutputStream(zip)) { - ZipOutputStream zipOut = new ZipOutputStream(out); - for (int i = 0; i < files.length; i++) { - File file = files[i]; - try (FileInputStream fis = new FileInputStream(file)) { - workerCallback.onProgress((float) i / files.length); - zipOut.putNextEntry(new ZipEntry(file.getName())); - copyStream(fis, zipOut); - zipOut.closeEntry(); - } - } - zipOut.close(); - } - //endregion + //region create zip file + File zip = File.createTempFile("temp_worldmap", ".zip"); + try (OutputStream out = new FileOutputStream(zip)) { + ZipOutputStream zipOut = new ZipOutputStream(out); + for (int i = 0; i < files.length; i++) { + File file = files[i]; + try (FileInputStream fis = new FileInputStream(file)) { + workerCallback.onProgress((float) i / files.length); + zipOut.putNextEntry(new ZipEntry(file.getName())); + copyStream(fis, zipOut); + zipOut.closeEntry(); + } + } + zipOut.close(); + } + //endregion - DocumentFile worldmapZip = DocumentFile.fromFile(zip); - DocumentFile worldmapTarget = targetDirectory.createFile("application/zip", - fileName); - if (worldmapTarget != null && worldmapTarget.exists()) { - AndroidStorage.copyDocumentFile(worldmapZip, resolver, worldmapTarget); - workerCallback.onComplete(true); - } - else { - throw new FileNotFoundException("Could not create File"); - } - } catch (NullPointerException e) { - if (worker.isCancelled()) { - workerCallback.onFailure(new CancellationException("Cancelled")); - } - else { - workerCallback.onFailure(e); - } - } catch (Exception e) { - workerCallback.onFailure(e); - } - }); + DocumentFile worldmapZip = DocumentFile.fromFile(zip); + DocumentFile worldmapTarget = targetDirectory.createFile("application/zip", fileName); + if (worldmapTarget != null && worldmapTarget.exists()) { + AndroidStorage.copyDocumentFile(worldmapZip, resolver, worldmapTarget); + workerCallback.onComplete(true); + } else { + throw new FileNotFoundException("Could not create File"); + } + } catch (NullPointerException e) { + if (worker.isCancelled()) { + workerCallback.onFailure(new CancellationException("Cancelled")); + } else { + workerCallback.onFailure(e); + } + } catch (Exception e) { + workerCallback.onFailure(e); + } + }); - worker.setCallback(getDefaultBackgroundWorkerCallback(handler, progressDialog, callback)); - worker.run(); + worker.setCallback(getDefaultBackgroundWorkerCallback(handler, progressDialog, callback)); + worker.run(); - } + } - public static void unzipToDirectory(File zipFile, - File targetDirectory, - boolean overwriteNotSkip) throws IOException { + public static void unzipToDirectory(File zipFile, + File targetDirectory, + boolean overwriteNotSkip) throws IOException { - try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) { - unzipStreamToDirectory(targetDirectory, overwriteNotSkip, zis); - } + try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) { + unzipStreamToDirectory(targetDirectory, overwriteNotSkip, zis); + } - } + } - @RequiresApi(api = Build.VERSION_CODES.P) - public static void unzipDocumentFileToDirectoryAsync(DocumentFile zipFile, - Context context, - File targetDirectory, - boolean overwriteNotSkip, - String loadingMessage, - Consumer callback) { + @RequiresApi(api = Build.VERSION_CODES.P) + public static void unzipDocumentFileToDirectoryAsync(DocumentFile zipFile, + Context context, + File targetDirectory, + boolean overwriteNotSkip, + String loadingMessage, + Consumer callback) { - BackgroundWorker worker = new BackgroundWorker<>(); - CustomDialogFactory.CustomDialog progressDialog = getLoadingDialog(context, - loadingMessage); - progressDialog.setOnCancelListener(dialog -> worker.cancel()); - ContentResolver resolver = context.getContentResolver(); - Handler handler = Handler.createAsync(Looper.getMainLooper()); + BackgroundWorker worker = new BackgroundWorker<>(); + CustomDialogFactory.CustomDialog progressDialog = getLoadingDialog(context, loadingMessage); + progressDialog.setOnCancelListener(dialog -> worker.cancel()); + ContentResolver resolver = context.getContentResolver(); + Handler handler = Handler.createAsync(Looper.getMainLooper()); - worker.setTask(workerCallback -> { - try { - workerCallback.onInitialize(); - workerCallback.onProgress(-1);//set dummy progress since we don't know the - // progress of the unzip - unzipDocumentFileToDirectory(zipFile, resolver, targetDirectory, overwriteNotSkip); - workerCallback.onComplete(true); - } catch (IOException e) { - workerCallback.onFailure(e); - } - }); + worker.setTask(workerCallback -> { + try { + workerCallback.onInitialize(); + workerCallback.onProgress(-1);//set dummy progress since we don't know the + // progress of the unzip + unzipDocumentFileToDirectory(zipFile, resolver, targetDirectory, overwriteNotSkip); + workerCallback.onComplete(true); + } catch (IOException e) { + workerCallback.onFailure(e); + } + }); - worker.setCallback(getDefaultBackgroundWorkerCallback(handler, progressDialog, callback)); - worker.run(); + worker.setCallback(getDefaultBackgroundWorkerCallback(handler, progressDialog, callback)); + worker.run(); - } + } - public static void unzipDocumentFileToDirectory(DocumentFile zipFile, - ContentResolver resolver, - File targetDirectory, - boolean overwriteNotSkip) throws IOException { - try (ZipInputStream zis = new ZipInputStream(resolver.openInputStream(zipFile.getUri()))) { - unzipStreamToDirectory(targetDirectory, overwriteNotSkip, zis); - } - } + public static void unzipDocumentFileToDirectory(DocumentFile zipFile, + ContentResolver resolver, + File targetDirectory, + boolean overwriteNotSkip) throws IOException { + try (ZipInputStream zis = new ZipInputStream(resolver.openInputStream(zipFile.getUri()))) { + unzipStreamToDirectory(targetDirectory, overwriteNotSkip, zis); + } + } - private static void unzipStreamToDirectory(File targetDirectory, - boolean overwriteNotSkip, - ZipInputStream zis) throws IOException { - ZipEntry entry; - while ((entry = zis.getNextEntry()) != null) { - File file = new File(targetDirectory, entry.getName()); + private static void unzipStreamToDirectory(File targetDirectory, + boolean overwriteNotSkip, + ZipInputStream zis) throws IOException { + ZipEntry entry; + while ((entry = zis.getNextEntry()) != null) { + File file = new File(targetDirectory, entry.getName()); - if (entry.isDirectory()) { - file.mkdirs(); - } - else { - file.getParentFile().mkdirs(); - if (file.exists() && !overwriteNotSkip) { - continue; - } + if (entry.isDirectory()) { + file.mkdirs(); + } else { + file.getParentFile().mkdirs(); + if (file.exists() && !overwriteNotSkip) { + continue; + } - try (FileOutputStream fos = new FileOutputStream(file)) { - copyStream(zis, fos); - } - } - } - } + try (FileOutputStream fos = new FileOutputStream(file)) { + copyStream(zis, fos); + } + } + } + } - public static void copyDocumentFileToNewOrExistingFile(DocumentFile sourceFile, - ContentResolver resolver, - DocumentFile targetFolder) throws IOException { - copyDocumentFileToNewOrExistingFile(sourceFile, - resolver, - targetFolder, - Constants.NO_FILE_EXTENSION_MIME_TYPE); - } + public static void copyDocumentFileToNewOrExistingFile(DocumentFile sourceFile, + ContentResolver resolver, + DocumentFile targetFolder) throws IOException { + copyDocumentFileToNewOrExistingFile(sourceFile, + resolver, + targetFolder, + Constants.NO_FILE_EXTENSION_MIME_TYPE); + } - public static void copyDocumentFileToNewOrExistingFile(DocumentFile sourceFile, - ContentResolver resolver, - DocumentFile targetFolder, - String mimeType) throws IOException { - String fileName = sourceFile.getName(); - DocumentFile file = targetFolder.findFile(fileName); - if (file == null) { - file = targetFolder.createFile(mimeType, fileName); - } - if (file == null) { - return; - } + public static void copyDocumentFileToNewOrExistingFile(DocumentFile sourceFile, + ContentResolver resolver, + DocumentFile targetFolder, + String mimeType) throws IOException { + String fileName = sourceFile.getName(); + DocumentFile file = targetFolder.findFile(fileName); + if (file == null) { + file = targetFolder.createFile(mimeType, fileName); + } + if (file == null) { + return; + } AndroidStorage.copyDocumentFile(sourceFile, resolver, file); } - public static void copyDocumentFile(DocumentFile sourceFile, ContentResolver resolver, DocumentFile targetFile) throws IOException { + public static void copyDocumentFile(DocumentFile sourceFile, + ContentResolver resolver, + DocumentFile targetFile) throws IOException { try (OutputStream outputStream = resolver.openOutputStream(targetFile.getUri()); InputStream inputStream = resolver.openInputStream(sourceFile.getUri())) { copyStream(inputStream, outputStream); } } - public static String getUrlForFile(Context context, File worldmap) { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { - String applicationId = context.getPackageName(); - Uri uri = FileProvider.getUriForFile(context, - applicationId + ".fileprovider", - worldmap); - return uri.toString(); - } - else { - return "file://" + worldmap.getAbsolutePath(); - } - } + public static String getUrlForFile(Context context, File worldmap) { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + String applicationId = context.getPackageName(); + Uri uri = FileProvider.getUriForFile(context, applicationId + ".fileprovider", worldmap); + return uri.toString(); + } else { + return "file://" + worldmap.getAbsolutePath(); + } + } - @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) - public static Intent getNewOpenDirectoryIntent() { - return new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); - } + @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) + public static Intent getNewOpenDirectoryIntent() { + return new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE); + } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public static Intent getNewSelectMultipleSavegameFilesIntent() { @@ -308,96 +298,92 @@ public final class AndroidStorage { return intent; } - @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) - public static Intent getNewSelectZipIntent() { - Intent intent = new Intent(Intent.ACTION_GET_CONTENT); - intent.addCategory(Intent.CATEGORY_OPENABLE); - intent.setType("application/zip"); - return intent; - } + @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) + public static Intent getNewSelectZipIntent() { + Intent intent = new Intent(Intent.ACTION_GET_CONTENT); + intent.addCategory(Intent.CATEGORY_OPENABLE); + intent.setType("application/zip"); + return intent; + } - @RequiresApi(api = Build.VERSION_CODES.P) - public static void copyDocumentFilesFromToAsync(DocumentFile[] sources, - Context context, - DocumentFile[] targets, - String loadingMessage, - Consumer callback) { - if (sources.length != targets.length) { - throw new IllegalArgumentException( - "Both arrays, target & source have to have the same size"); - } + @RequiresApi(api = Build.VERSION_CODES.P) + public static void copyDocumentFilesFromToAsync(DocumentFile[] sources, + Context context, + DocumentFile[] targets, + String loadingMessage, + Consumer callback) { + if (sources.length != targets.length) { + throw new IllegalArgumentException("Both arrays, target & source have to have the same size"); + } - BackgroundWorker worker = new BackgroundWorker<>(); + BackgroundWorker worker = new BackgroundWorker<>(); - CustomDialogFactory.CustomDialog progressDialog = getLoadingDialog(context, - loadingMessage); - progressDialog.setOnCancelListener(dialog -> worker.cancel()); + CustomDialogFactory.CustomDialog progressDialog = getLoadingDialog(context, loadingMessage); + progressDialog.setOnCancelListener(dialog -> worker.cancel()); - ContentResolver resolver = context.getContentResolver(); - Handler handler = Handler.createAsync(Looper.getMainLooper()); + ContentResolver resolver = context.getContentResolver(); + Handler handler = Handler.createAsync(Looper.getMainLooper()); - worker.setTask(workerCallback -> { - try { - workerCallback.onInitialize(); - for (int i = 0; i < sources.length; i++) { - if (worker.isCancelled()) { - workerCallback.onFailure(new CancellationException("Cancelled")); - return; - } - DocumentFile source = sources[i]; - DocumentFile target = targets[i]; + worker.setTask(workerCallback -> { + try { + workerCallback.onInitialize(); + for (int i = 0; i < sources.length; i++) { + if (worker.isCancelled()) { + workerCallback.onFailure(new CancellationException("Cancelled")); + return; + } + DocumentFile source = sources[i]; + DocumentFile target = targets[i]; - if(source == null || target == null) - { - continue; - } + if (source == null || target == null) { + continue; + } - copyDocumentFile(source, resolver, target); - float progress = i / (float) sources.length; - workerCallback.onProgress(progress); - } - workerCallback.onComplete(true); - } catch (NullPointerException e) { - if (worker.isCancelled()) { - workerCallback.onFailure(new CancellationException("Cancelled")); - return; - } - } catch (Exception e) { - workerCallback.onFailure(e); - } - }); - worker.setCallback(getDefaultBackgroundWorkerCallback(handler, progressDialog, callback)); - worker.run(); - } + copyDocumentFile(source, resolver, target); + float progress = i / (float) sources.length; + workerCallback.onProgress(progress); + } + workerCallback.onComplete(true); + } catch (NullPointerException e) { + if (worker.isCancelled()) { + workerCallback.onFailure(new CancellationException("Cancelled")); + return; + } + } catch (Exception e) { + workerCallback.onFailure(e); + } + }); + worker.setCallback(getDefaultBackgroundWorkerCallback(handler, progressDialog, callback)); + worker.run(); + } - @RequiresApi(api = Build.VERSION_CODES.P) - public static void copyDocumentFilesToDirAsync(DocumentFile[] files, - Context context, - DocumentFile targetDirectory, - String loadingMessage, - Consumer callback) { - BackgroundWorker worker = new BackgroundWorker<>(); - CustomDialogFactory.CustomDialog progressDialog = getLoadingDialog(context, - loadingMessage); - progressDialog.setOnCancelListener(dialog -> worker.cancel()); - ContentResolver resolver = context.getContentResolver(); - Handler handler = Handler.createAsync(Looper.getMainLooper()); + @RequiresApi(api = Build.VERSION_CODES.P) + public static void copyDocumentFilesToDirAsync(DocumentFile[] files, + Context context, + DocumentFile targetDirectory, + String loadingMessage, + Consumer callback) { + BackgroundWorker worker = new BackgroundWorker<>(); + CustomDialogFactory.CustomDialog progressDialog = getLoadingDialog(context, loadingMessage); + progressDialog.setOnCancelListener(dialog -> worker.cancel()); + ContentResolver resolver = context.getContentResolver(); + Handler handler = Handler.createAsync(Looper.getMainLooper()); - worker.setTask(workerCallback -> { - try { - workerCallback.onInitialize(); - for (int i = 0; i < files.length; i++) { - if (worker.isCancelled()) { - workerCallback.onFailure(new CancellationException("Cancelled")); - return; - } - DocumentFile file = files[i]; - if (file == null) { - continue; - } + worker.setTask(workerCallback -> { + try { + workerCallback.onInitialize(); + for (int i = 0; i < files.length; i++) { + if (worker.isCancelled()) { + workerCallback.onFailure(new CancellationException("Cancelled")); + return; + } + DocumentFile file = files[i]; + if (file == null) { + continue; + } copyDocumentFileToNewOrExistingFile(file, resolver, targetDirectory); - float progress = i /(float) files.length; + float progress = i / (float) files.length; workerCallback.onProgress(progress); } workerCallback.onComplete(true); @@ -414,10 +400,11 @@ public final class AndroidStorage { } private static BackgroundWorkerCallback getDefaultBackgroundWorkerCallback(Handler handler, - CustomDialogFactory.CustomDialog progressDialog, - Consumer callback) { + CustomDialogFactory.CustomDialog progressDialog, + Consumer callback) { return new BackgroundWorkerCallback() { - private int progress = -1; + private int progress = -1; + @Override public void onInitialize() { handler.post(() -> { @@ -425,62 +412,61 @@ public final class AndroidStorage { }); } - @Override - public void onProgress(float progress) { - handler.post(() -> { - int intProgress = (int) (progress * 100); - if (this.progress == intProgress) { - return; - } + @Override + public void onProgress(float progress) { + handler.post(() -> { + int intProgress = (int) (progress * 100); + if (this.progress == intProgress) { + return; + } - this.progress = intProgress; + this.progress = intProgress; - if (progress == -1) { - CustomDialogFactory.setDesc(progressDialog, null); - return; - } + if (progress == -1) { + CustomDialogFactory.setDesc(progressDialog, null); + return; + } - CustomDialogFactory.setDesc(progressDialog, intProgress + "%"); - }); - } + CustomDialogFactory.setDesc(progressDialog, intProgress + "%"); + }); + } - @RequiresApi(api = Build.VERSION_CODES.N) - @Override - public void onFailure(Exception e) { - this.onComplete(false); - } + @RequiresApi(api = Build.VERSION_CODES.N) + @Override + public void onFailure(Exception e) { + this.onComplete(false); + } - @RequiresApi(api = Build.VERSION_CODES.N) - @Override - public void onComplete(Boolean result) { - handler.post(() -> { - progressDialog.dismiss(); - callback.accept(result); - }); - } - }; - } + @RequiresApi(api = Build.VERSION_CODES.N) + @Override + public void onComplete(Boolean result) { + handler.post(() -> { + progressDialog.dismiss(); + callback.accept(result); + }); + } + }; + } - private static CustomDialogFactory.CustomDialog getLoadingDialog(Context context) { - return getLoadingDialog(context, null); - } + private static CustomDialogFactory.CustomDialog getLoadingDialog(Context context) { + return getLoadingDialog(context, null); + } - private static CustomDialogFactory.CustomDialog getLoadingDialog(Context context, - String message) { - if (message == null) { - message = context.getResources().getString(R.string.dialog_loading_message); - } + private static CustomDialogFactory.CustomDialog getLoadingDialog(Context context, String message) { + if (message == null) { + message = context.getResources().getString(R.string.dialog_loading_message); + } - CustomDialogFactory.CustomDialog dialog = CustomDialogFactory.createDialog(context, - message, - context.getResources() - .getDrawable(R.drawable.loading_anim), - null, - null, - true, - false); - CustomDialogFactory.addCancelButton(dialog, android.R.string.no); - return dialog; - } + CustomDialogFactory.CustomDialog dialog = CustomDialogFactory.createDialog(context, + message, + context.getResources() + .getDrawable(R.drawable.loading_anim), + null, + null, + true, + false); + CustomDialogFactory.addCancelButton(dialog, android.R.string.no); + return dialog; + } }