Fix new file option and clean up unused/unnecessary code

This commit is contained in:
Billy Brawner 2019-05-18 14:16:31 -07:00 committed by William Brawner
parent 83ef306b83
commit f16f25ca65
9 changed files with 43 additions and 107 deletions

View file

@ -14,7 +14,8 @@ public interface MarkdownPresenter {
void loadFromUri(Context context, Uri fileUri); void loadFromUri(Context context, Uri fileUri);
void loadMarkdown(String fileName, InputStream in, OnTempFileLoadedListener listener); void loadMarkdown(String fileName, InputStream in, OnTempFileLoadedListener listener);
void newFile(String path);
void newFile(String newName);
void setEditView(MarkdownEditView editView); void setEditView(MarkdownEditView editView);
void setPreviewView(MarkdownPreviewView previewView); void setPreviewView(MarkdownPreviewView previewView);

View file

@ -9,7 +9,6 @@ import android.provider.OpenableColumns;
import com.commonsware.cwac.anddown.AndDown; import com.commonsware.cwac.anddown.AndDown;
import com.wbrawner.simplemarkdown.model.MarkdownFile; import com.wbrawner.simplemarkdown.model.MarkdownFile;
import com.wbrawner.simplemarkdown.utility.ErrorHandler; import com.wbrawner.simplemarkdown.utility.ErrorHandler;
import com.wbrawner.simplemarkdown.utility.Utils;
import com.wbrawner.simplemarkdown.view.MarkdownEditView; import com.wbrawner.simplemarkdown.view.MarkdownEditView;
import com.wbrawner.simplemarkdown.view.MarkdownPreviewView; import com.wbrawner.simplemarkdown.view.MarkdownPreviewView;
@ -197,7 +196,7 @@ public class MarkdownPresenterImpl implements MarkdownPresenter {
fileName = fileUri.getLastPathSegment(); fileName = fileUri.getLastPathSegment();
} }
if (fileName == null) { if (fileName == null) {
fileName = Utils.getDefaultFileName(context); fileName = "Untitled.md";
} }
loadMarkdown(fileName, in); loadMarkdown(fileName, in);
} catch (Exception e) { } catch (Exception e) {

View file

@ -2,24 +2,12 @@ package com.wbrawner.simplemarkdown.utility;
@SuppressWarnings("WeakerAccess") @SuppressWarnings("WeakerAccess")
public class Constants { public class Constants {
// Request codes // Request codes
public static final int REQUEST_OPEN_FILE = 1; public static final int REQUEST_OPEN_FILE = 1;
public static final int REQUEST_SAVE_FILE = 2; public static final int REQUEST_SAVE_FILE = 2;
public static final int REQUEST_DARK_MODE = 3; public static final int REQUEST_NEW_FILE = 3;
public static final int REQUEST_DARK_MODE = 4;
// Extras
public static final String EXTRA_FILE = "EXTRA_FILE";
public static final String EXTRA_FILE_PATH = "EXTRA_FILE_PATH";
public static final String EXTRA_REQUEST_CODE = "EXTRA_REQUEST_CODE";
public static final String EXTRA_EXPLORER = "EXTRA_EXPLORER";
// Settings keys // Settings keys
public static final String KEY_AUTOSAVE = "autosave"; public static final String KEY_AUTOSAVE = "autosave";
public static final String KEY_DOCS_PATH = "defaultRootDir";
// Settings values
public static final String VALUE_EDIT_VIEW = "0";
public static final String VALUE_FILE_VIEW = "1";
} }

View file

@ -4,7 +4,6 @@ import android.Manifest;
import android.content.Context; import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.os.Environment;
import android.os.Handler; import android.os.Handler;
import android.os.HandlerThread; import android.os.HandlerThread;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
@ -12,66 +11,10 @@ import android.preference.PreferenceManager;
import androidx.core.content.ContextCompat; import androidx.core.content.ContextCompat;
import java.io.Closeable; import java.io.Closeable;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Utils { public class Utils {
public static String getDocsPath(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getString(
Constants.KEY_DOCS_PATH,
Environment.getExternalStorageDirectory() + "/" +
Environment.DIRECTORY_DOCUMENTS + "/"
);
}
public static String getDefaultFileName(Context context) {
File docsDir = new File(Utils.getDocsPath(context));
Pattern defaultFilePattern = Pattern.compile("Untitled(-([0-9]+))*.md");
File[] files = docsDir.listFiles();
String defaultFileName = "Untitled.md";
if (files != null && files.length > 0) {
int count = 0;
for (File file : files) {
if (!file.isFile()) {
continue;
}
Matcher fileMatcher = defaultFilePattern.matcher(file.getName());
if (!fileMatcher.find()) {
continue;
}
if (file.getName().equals("Untitled.md")) {
if (count == 0) {
count = 1;
}
continue;
}
String defaultFileCount = fileMatcher.group(2);
int fileCount = Integer.parseInt(defaultFileCount);
if (fileCount >= count) {
count = fileCount + 1;
}
}
if (count > 0) {
defaultFileName = String.format(
Locale.ENGLISH,
"Untitled-%d.md",
count
);
}
}
return defaultFileName;
}
public static boolean isAutosaveEnabled(Context context) { public static boolean isAutosaveEnabled(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getBoolean( return prefs.getBoolean(

View file

@ -13,13 +13,13 @@ import android.view.MenuItem
import android.view.View import android.view.View
import android.webkit.MimeTypeMap import android.webkit.MimeTypeMap
import android.widget.Toast import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat import androidx.core.app.ActivityCompat
import com.wbrawner.simplemarkdown.MarkdownApplication import com.wbrawner.simplemarkdown.MarkdownApplication
import com.wbrawner.simplemarkdown.R import com.wbrawner.simplemarkdown.R
import com.wbrawner.simplemarkdown.presentation.MarkdownPresenter import com.wbrawner.simplemarkdown.presentation.MarkdownPresenter
import com.wbrawner.simplemarkdown.utility.Constants import com.wbrawner.simplemarkdown.utility.Constants.*
import com.wbrawner.simplemarkdown.utility.Constants.REQUEST_DARK_MODE
import com.wbrawner.simplemarkdown.utility.ErrorHandler import com.wbrawner.simplemarkdown.utility.ErrorHandler
import com.wbrawner.simplemarkdown.utility.Utils import com.wbrawner.simplemarkdown.utility.Utils
import com.wbrawner.simplemarkdown.view.adapter.EditPagerAdapter import com.wbrawner.simplemarkdown.view.adapter.EditPagerAdapter
@ -56,7 +56,6 @@ class MainActivity : AppCompatActivity(), ActivityCompat.OnRequestPermissionsRes
if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) { if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
tabLayout!!.visibility = View.GONE tabLayout!!.visibility = View.GONE
} }
newFileHandler = NewFileHandler()
} }
override fun onUserLeaveHint() { override fun onUserLeaveHint() {
@ -81,7 +80,7 @@ class MainActivity : AppCompatActivity(), ActivityCompat.OnRequestPermissionsRes
override fun onOptionsItemSelected(item: MenuItem): Boolean { override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) { when (item.itemId) {
R.id.action_save -> requestFileOp(Constants.REQUEST_SAVE_FILE) R.id.action_save -> requestFileOp(REQUEST_SAVE_FILE)
R.id.action_share -> { R.id.action_share -> {
val shareIntent = Intent(Intent.ACTION_SEND) val shareIntent = Intent(Intent.ACTION_SEND)
shareIntent.putExtra(Intent.EXTRA_TEXT, presenter.markdown) shareIntent.putExtra(Intent.EXTRA_TEXT, presenter.markdown)
@ -91,8 +90,8 @@ class MainActivity : AppCompatActivity(), ActivityCompat.OnRequestPermissionsRes
getString(R.string.share_file) getString(R.string.share_file)
)) ))
} }
R.id.action_load -> requestFileOp(Constants.REQUEST_OPEN_FILE) R.id.action_load -> requestFileOp(REQUEST_OPEN_FILE)
// R.id.action_new -> presenter.saveMarkdown(newFileHandler, null) R.id.action_new -> promptSaveOrDiscardChanges()
R.id.action_lock_swipe -> { R.id.action_lock_swipe -> {
item.isChecked = !item.isChecked item.isChecked = !item.isChecked
pager!!.setSwipeLocked(item.isChecked) pager!!.setSwipeLocked(item.isChecked)
@ -157,7 +156,7 @@ class MainActivity : AppCompatActivity(), ActivityCompat.OnRequestPermissionsRes
grantResults: IntArray grantResults: IntArray
) { ) {
when (requestCode) { when (requestCode) {
Constants.REQUEST_SAVE_FILE, Constants.REQUEST_OPEN_FILE -> { REQUEST_SAVE_FILE, REQUEST_OPEN_FILE -> {
// If request is cancelled, the result arrays are empty. // If request is cancelled, the result arrays are empty.
if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted, open file save dialog // Permission granted, open file save dialog
@ -180,7 +179,7 @@ class MainActivity : AppCompatActivity(), ActivityCompat.OnRequestPermissionsRes
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
when (requestCode) { when (requestCode) {
Constants.REQUEST_OPEN_FILE -> { REQUEST_OPEN_FILE -> {
if (resultCode != Activity.RESULT_OK || data?.data == null) { if (resultCode != Activity.RESULT_OK || data?.data == null) {
return return
} }
@ -197,7 +196,7 @@ class MainActivity : AppCompatActivity(), ActivityCompat.OnRequestPermissionsRes
presenter.loadMarkdown(fileName, fileInput) presenter.loadMarkdown(fileName, fileInput)
} }
} }
Constants.REQUEST_SAVE_FILE -> { REQUEST_SAVE_FILE -> {
if (resultCode != Activity.RESULT_OK if (resultCode != Activity.RESULT_OK
|| data?.data == null) { || data?.data == null) {
return return
@ -211,7 +210,7 @@ class MainActivity : AppCompatActivity(), ActivityCompat.OnRequestPermissionsRes
} ?: "Untitled.md" } ?: "Untitled.md"
presenter.saveMarkdown( presenter.saveMarkdown(
null, newFileHandler,
fileName, fileName,
contentResolver.openOutputStream(data.data!!) contentResolver.openOutputStream(data.data!!)
) )
@ -221,6 +220,21 @@ class MainActivity : AppCompatActivity(), ActivityCompat.OnRequestPermissionsRes
super.onActivityResult(requestCode, resultCode, data) super.onActivityResult(requestCode, resultCode, data)
} }
private fun promptSaveOrDiscardChanges() {
AlertDialog.Builder(this)
.setTitle(R.string.save_changes)
.setMessage(R.string.prompt_save_changes)
.setNegativeButton(R.string.action_discard) { d, _ ->
presenter.newFile("Untitled.md")
}
.setPositiveButton(R.string.action_save) { d, _ ->
newFileHandler = NewFileHandler()
requestFileOp(REQUEST_SAVE_FILE)
}
.create()
.show()
}
private fun requestFileOp(requestType: Int) { private fun requestFileOp(requestType: Int) {
if (!Utils.canAccessFiles(this@MainActivity)) { if (!Utils.canAccessFiles(this@MainActivity)) {
if (Build.VERSION.SDK_INT < 23) return if (Build.VERSION.SDK_INT < 23) return
@ -233,13 +247,13 @@ class MainActivity : AppCompatActivity(), ActivityCompat.OnRequestPermissionsRes
// If the user is going to save the file, we don't want to auto-save it for them // If the user is going to save the file, we don't want to auto-save it for them
shouldAutoSave = false shouldAutoSave = false
val intent = when (requestType) { val intent = when (requestType) {
Constants.REQUEST_SAVE_FILE -> { REQUEST_SAVE_FILE -> {
Intent(Intent.ACTION_CREATE_DOCUMENT).apply { Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
type = "text/markdown" type = "text/markdown"
putExtra(Intent.EXTRA_TITLE, presenter.fileName) putExtra(Intent.EXTRA_TITLE, presenter.fileName)
} }
} }
Constants.REQUEST_OPEN_FILE -> { REQUEST_OPEN_FILE -> {
Intent(Intent.ACTION_OPEN_DOCUMENT).apply { Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
type = "*/*" type = "*/*"
if (MimeTypeMap.getSingleton().hasMimeType("md")) { if (MimeTypeMap.getSingleton().hasMimeType("md")) {
@ -258,6 +272,7 @@ class MainActivity : AppCompatActivity(), ActivityCompat.OnRequestPermissionsRes
) )
} }
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
title = presenter.fileName title = presenter.fileName
@ -267,8 +282,7 @@ class MainActivity : AppCompatActivity(), ActivityCompat.OnRequestPermissionsRes
private inner class NewFileHandler : MarkdownPresenter.MarkdownSavedListener { private inner class NewFileHandler : MarkdownPresenter.MarkdownSavedListener {
override fun saveComplete(success: Boolean) { override fun saveComplete(success: Boolean) {
if (success) { if (success) {
val newFile = Utils.getDefaultFileName(this@MainActivity) presenter.newFile("Untitled.md")
presenter.newFile(newFile)
} else { } else {
Toast.makeText( Toast.makeText(
this@MainActivity, this@MainActivity,

View file

@ -14,7 +14,6 @@ import com.wbrawner.simplemarkdown.MarkdownApplication;
import com.wbrawner.simplemarkdown.R; import com.wbrawner.simplemarkdown.R;
import com.wbrawner.simplemarkdown.presentation.MarkdownPresenter; import com.wbrawner.simplemarkdown.presentation.MarkdownPresenter;
import com.wbrawner.simplemarkdown.utility.ErrorHandler; import com.wbrawner.simplemarkdown.utility.ErrorHandler;
import com.wbrawner.simplemarkdown.utility.Utils;
import javax.inject.Inject; import javax.inject.Inject;
@ -56,13 +55,11 @@ public class SplashActivity extends AppCompatActivity {
} }
AppCompatDelegate.setDefaultNightMode(darkMode); AppCompatDelegate.setDefaultNightMode(darkMode);
String defaultName = Utils.getDefaultFileName(this);
Intent intent = getIntent(); Intent intent = getIntent();
if (intent != null && intent.getData() != null) { if (intent != null && intent.getData() != null) {
presenter.loadFromUri(getApplicationContext(), intent.getData()); presenter.loadFromUri(getApplicationContext(), intent.getData());
} else { } else {
presenter.setFileName(defaultName); presenter.setFileName("Untitled.md");
} }
Intent startIntent = new Intent(this, MainActivity.class); Intent startIntent = new Intent(this, MainActivity.class);

View file

@ -17,7 +17,6 @@ import com.wbrawner.simplemarkdown.MarkdownApplication
import com.wbrawner.simplemarkdown.R import com.wbrawner.simplemarkdown.R
import com.wbrawner.simplemarkdown.presentation.MarkdownPresenter import com.wbrawner.simplemarkdown.presentation.MarkdownPresenter
import com.wbrawner.simplemarkdown.utility.MarkdownObserver import com.wbrawner.simplemarkdown.utility.MarkdownObserver
import com.wbrawner.simplemarkdown.utility.Utils
import com.wbrawner.simplemarkdown.view.MarkdownEditView import com.wbrawner.simplemarkdown.view.MarkdownEditView
import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers import io.reactivex.schedulers.Schedulers
@ -101,10 +100,8 @@ class EditFragment : Fragment(), MarkdownEditView {
} }
override fun onFileSaved(success: Boolean) { override fun onFileSaved(success: Boolean) {
val location = Utils.getDocsPath(activity) + presenter.fileName val message: String = if (success) {
val message: String getString(R.string.file_saved, presenter.fileName)
message = if (success) {
getString(R.string.file_saved, location)
} else { } else {
getString(R.string.file_save_error) getString(R.string.file_save_error)
} }

View file

@ -44,14 +44,7 @@ class PreviewFragment : Fragment(), MarkdownPreviewView {
} }
override fun updatePreview(html: String) { override fun updatePreview(html: String) {
if (markdownPreview == null) { markdownPreview?.post {
return
}
markdownPreview!!.post {
if (markdownPreview == null) {
return@post
}
val isNightMode = AppCompatDelegate.getDefaultNightMode() == val isNightMode = AppCompatDelegate.getDefaultNightMode() ==
AppCompatDelegate.MODE_NIGHT_YES AppCompatDelegate.MODE_NIGHT_YES
|| context!!.resources.configuration.uiMode and UI_MODE_NIGHT_MASK == UI_MODE_NIGHT_YES || context!!.resources.configuration.uiMode and UI_MODE_NIGHT_MASK == UI_MODE_NIGHT_YES
@ -60,6 +53,7 @@ class PreviewFragment : Fragment(), MarkdownPreviewView {
} else { } else {
R.string.pref_custom_css_default R.string.pref_custom_css_default
} }
@Suppress("ConstantConditionIf")
val css: String? = if (!BuildConfig.ENABLE_CUSTOM_CSS) { val css: String? = if (!BuildConfig.ENABLE_CUSTOM_CSS) {
getString(defaultCssId) getString(defaultCssId)
} else { } else {
@ -71,7 +65,7 @@ class PreviewFragment : Fragment(), MarkdownPreviewView {
val style = String.format(FORMAT_CSS, css) val style = String.format(FORMAT_CSS, css)
markdownPreview!!.loadDataWithBaseURL(null, markdownPreview?.loadDataWithBaseURL(null,
style + html, style + html,
"text/html", "text/html",
"UTF-8", null "UTF-8", null

View file

@ -16,7 +16,7 @@
<string name="no_shareable_apps">Unable to share file - no capable apps installed</string> <string name="no_shareable_apps">Unable to share file - no capable apps installed</string>
<string name="share_file">Share file to…</string> <string name="share_file">Share file to…</string>
<string name="no_permissions">Unable to save file without permissions</string> <string name="no_permissions">Unable to save file without permissions</string>
<string name="file_saved">File saved to %1$s</string> <string name="file_saved">Successfully saved %1$s</string>
<string name="action_load">Load</string> <string name="action_load">Load</string>
<string name="open_file">Select a file to open</string> <string name="open_file">Select a file to open</string>
<string name="no_filebrowser">No file browser apps found</string> <string name="no_filebrowser">No file browser apps found</string>
@ -56,6 +56,9 @@
<string name="pref_key_dark_mode_light" translatable="false">light</string> <string name="pref_key_dark_mode_light" translatable="false">light</string>
<string name="pref_key_dark_mode_dark" translatable="false">dark</string> <string name="pref_key_dark_mode_dark" translatable="false">dark</string>
<string name="pref_key_dark_mode_auto" translatable="false">auto</string> <string name="pref_key_dark_mode_auto" translatable="false">auto</string>
<string name="save_changes">Save Changes</string>
<string name="prompt_save_changes">Would you like to save your changes?</string>
<string name="action_discard">Discard</string>
<string-array name="pref_entries_dark_mode"> <string-array name="pref_entries_dark_mode">
<item>@string/pref_value_light</item> <item>@string/pref_value_light</item>
<item>@string/pref_value_dark</item> <item>@string/pref_value_dark</item>