Skip to content

Commit

Permalink
Add launcher shortcuts to folders, by @harshad1 (PR #1549)
Browse files Browse the repository at this point in the history
  • Loading branch information
harshad1 authored Jan 4, 2022
1 parent c43bd37 commit 0c27e81
Show file tree
Hide file tree
Showing 18 changed files with 195 additions and 121 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Selection;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.Menu;
Expand Down Expand Up @@ -668,20 +667,27 @@ public String getFragmentTag() {

// Save the file
// Only supports java.io.File. TODO: Android Content
public boolean saveDocument(boolean forceSaveEmpty) {
// Document is written iff content has changed
// _isTextChanged implies _document != null && _hlEditor != null && _hlEditor.getText() != null
if (_isTextChanged && isAdded()) {
public boolean saveDocument(final boolean forceSaveEmpty) {
if (!isAdded()) {
return false;
}

_appSettings.setLastEditPosition(_document.getFile(), _hlEditor.getSelectionStart());
// Save edit position regardless of _isTextChanged
_appSettings.setLastEditPosition(_document.getFile(), _hlEditor.getSelectionStart());

// Document is written iff content has changed
// _isTextChanged implies _document != null && _hlEditor != null && _hlEditor.getText() != null
if (_isTextChanged) {
if (_document.saveContent(getContext(), _hlEditor.getText().toString(), _shareUtil, forceSaveEmpty)) {
updateLauncherWidgets();
checkTextChangeState();
return true;
} else {
return false; // Failure only if saveContent somehow fails
}
} else {
return true; // Report success if text not changed
}
return false;
}

private boolean isDisplayedAtMainActivity() {
Expand Down
44 changes: 39 additions & 5 deletions app/src/main/java/net/gsantner/markor/activity/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
import net.gsantner.markor.BuildConfig;
import net.gsantner.markor.R;
import net.gsantner.markor.format.TextFormat;
import net.gsantner.markor.model.Document;
import net.gsantner.markor.ui.FilesystemViewerCreator;
import net.gsantner.markor.ui.NewFileDialog;
import net.gsantner.markor.util.ActivityUtils;
Expand Down Expand Up @@ -135,7 +136,42 @@ protected void onCreate(Bundle savedInstanceState) {

(new ActivityUtils(this)).applySpecialLaunchersVisibility(_appSettings.isSpecialFileLaunchersEnabled());

_bottomNav.postDelayed(() -> _bottomNav.setSelectedItemId(_appSettings.getAppStartupTab()), 10);
// Switch to tab if specific folder _not_ requested, and not recreating from saved instance
final int startTab = _appSettings.getAppStartupTab();
if (startTab != R.id.nav_notebook && savedInstanceState == null && getIntentDir(getIntent(), null) == null) {
_bottomNav.postDelayed(() -> _bottomNav.setSelectedItemId(startTab), 10);
}
}

@Override
protected void onNewIntent(final Intent intent) {
final File dir = getIntentDir(intent, null);
final FilesystemViewerFragment frag = (FilesystemViewerFragment) _viewPagerAdapter.getFragmentByTag(FilesystemViewerFragment.FRAGMENT_TAG);
if (frag != null && dir != null) {
frag.getAdapter().setCurrentFolder(dir, false);
_bottomNav.postDelayed(() -> _bottomNav.setSelectedItemId(R.id.nav_notebook), 10);
}
}

private static File getIntentDir(final Intent intent, final File fallback) {
if (intent == null) {
return fallback;
}

// By extra path
if (intent.hasExtra(Document.EXTRA_PATH) && intent.getBooleanExtra(Document.EXTRA_PATH_IS_FOLDER, false)) {
return (File) intent.getSerializableExtra(Document.EXTRA_PATH);
}

// By url in data
try {
final File dir = new File(intent.getData().getPath());
if (dir.exists() && dir.isDirectory()) {
return dir;
}
} catch (NullPointerException ignored) {};

return fallback;
}

private void optShowRate() {
Expand Down Expand Up @@ -185,7 +221,7 @@ protected void onResume() {
IS_DEBUG_ENABLED = BuildConfig.IS_TEST_BUILD;
if (_appSettings.isRecreateMainRequired()) {
// recreate(); // does not remake fragments
Intent intent = getIntent();
final Intent intent = getIntent();
overridePendingTransition(0, 0);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
finish();
Expand Down Expand Up @@ -229,7 +265,6 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
restartMainActivity();
}


try {
FilesystemViewerFragment frag = (FilesystemViewerFragment) _viewPagerAdapter.getFragmentByTag(FilesystemViewerFragment.FRAGMENT_TAG);
frag.getAdapter().reconfigure();
Expand Down Expand Up @@ -389,8 +424,7 @@ public FilesystemViewerData.Options getFilesystemFragmentOptions(FilesystemViewe
@Override
public void onFsViewerConfig(FilesystemViewerData.Options dopt) {
dopt.descModtimeInsteadOfParent = true;
//opt.rootFolder = _appSettings.getNotebookDirectory();
dopt.rootFolder = _appSettings.getFolderToLoadByMenuId(_appSettings.getAppStartupFolderMenuId());
dopt.rootFolder = getIntentDir(getIntent(), _appSettings.getFolderToLoadByMenuId(_appSettings.getAppStartupFolderMenuId()));
dopt.folderFirst = _appSettings.isFilesystemListFolderFirst();
dopt.doSelectMultiple = dopt.doSelectFolder = dopt.doSelectFile = true;
dopt.mountedStorageFolder = _shareUtil.getStorageAccessFolder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -599,13 +599,14 @@ public static void showPriorityDialog(Activity activity, char selectedPriority,

@SuppressLint("StringFormatMatches")
public static void showCopyMoveConflictDialog(final Activity activity, final String fileName, final String destName, final boolean multiple, final Callback.a1<Integer> callback) {
SearchOrCustomTextDialog.DialogOptions dopt = new SearchOrCustomTextDialog.DialogOptions();
final SearchOrCustomTextDialog.DialogOptions dopt = new SearchOrCustomTextDialog.DialogOptions();
baseConf(activity, dopt);
dopt.positionCallback = (result) -> callback.callback(result.get(0));
List<String> data = new ArrayList<>();
final List<String> data = new ArrayList<>();
// Order of options here should be synchronized with WrMarkorSingleton._moveOrCopySelected
data.add(activity.getString(R.string.keep_both));
data.add(activity.getString(R.string.skip));
data.add(activity.getString(R.string.overwrite));
data.add(activity.getString(R.string.skip));
if (multiple) {
data.add(activity.getString(R.string.keep_both_all));
data.add(activity.getString(R.string.overwrite_all));
Expand Down
14 changes: 8 additions & 6 deletions app/src/main/java/net/gsantner/markor/util/ShareUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.webkit.WebView;
import android.widget.Toast;

import net.gsantner.markor.R;
import net.gsantner.markor.activity.MainActivity;
import net.gsantner.markor.activity.openeditor.OpenEditorFromShortcutOrWidgetActivity;
import net.gsantner.markor.model.Document;

Expand All @@ -30,15 +30,17 @@ public ShareUtil(Context context) {
setChooserTitle(_context.getString(R.string.share_to_arrow));
}

public void createLauncherDesktopShortcut(Document document) {
public void createLauncherDesktopShortcut(final Document document) {
// This is only allowed to call when direct file access is possible!!
// So basically only for java.io.File Objects. Virtual files, or content://
// in private/restricted space won't work - because of missing permission grant when re-launching
if (document != null && !TextUtils.isEmpty(document.getTitle())) {
Intent shortcutIntent = new Intent(_context, OpenEditorFromShortcutOrWidgetActivity.class)
.setData(Uri.fromFile(document.getFile()));
super.createLauncherDesktopShortcut(shortcutIntent, R.drawable.ic_launcher, document.getTitle());
Toast.makeText(_context, R.string.tried_to_create_shortcut_for_this_notice, Toast.LENGTH_LONG).show();
final boolean isDir = document.getFile().isDirectory();
final Class<?> klass = isDir ? MainActivity.class : OpenEditorFromShortcutOrWidgetActivity.class;
final Intent intent = new Intent(_context, klass).setData(Uri.fromFile(document.getFile()));
final int iconRes = isDir ? R.mipmap.ic_shortcut_folder : R.mipmap.ic_shortcut_file;
super.createLauncherDesktopShortcut(intent, iconRes, document.getTitle());
// Toast.makeText(_context, R.string.tried_to_create_shortcut_for_this_notice, Toast.LENGTH_LONG).show();
}
}

Expand Down
26 changes: 11 additions & 15 deletions app/src/main/java/net/gsantner/markor/util/ShortcutUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -55,17 +55,17 @@ public static void setShortcuts(@NonNull Context context) {
return;
}

ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
List<ShortcutInfo> newShortcuts = new ArrayList<>();
final ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
final List<ShortcutInfo> newShortcuts = new ArrayList<>();

final AppSettings appSettings = new AppSettings(context);

// Create the to-do shortcut
Intent openTodo = new Intent(context, OpenEditorFromShortcutOrWidgetActivity.class)
final Intent openTodo = new Intent(context, OpenEditorFromShortcutOrWidgetActivity.class)
.setAction(Intent.ACTION_EDIT)
.setData(Uri.fromFile(appSettings.getTodoFile()));

ShortcutInfo shortcutToDo = new ShortcutInfo.Builder(context, ID_TO_DO)
final ShortcutInfo shortcutToDo = new ShortcutInfo.Builder(context, ID_TO_DO)
.setShortLabel(createShortLabel(context.getString(R.string.todo)))
.setLongLabel(createLongLabel(context.getString(R.string.todo)))
.setIcon(Icon.createWithResource(context, R.mipmap.ic_shortcut_todo))
Expand All @@ -74,11 +74,11 @@ public static void setShortcuts(@NonNull Context context) {
newShortcuts.add(shortcutToDo);

// Create the QuickNote shortcut
Intent openQuickNote = new Intent(context, OpenEditorFromShortcutOrWidgetActivity.class)
final Intent openQuickNote = new Intent(context, OpenEditorFromShortcutOrWidgetActivity.class)
.setAction(Intent.ACTION_EDIT)
.setData(Uri.fromFile(appSettings.getQuickNoteFile()));

ShortcutInfo shortcutQuickNote = new ShortcutInfo.Builder(context, ID_QUICK_NOTE)
final ShortcutInfo shortcutQuickNote = new ShortcutInfo.Builder(context, ID_QUICK_NOTE)
.setShortLabel(createShortLabel(context.getString(R.string.quicknote)))
.setLongLabel(createLongLabel(context.getString(R.string.quicknote)))
.setIcon(Icon.createWithResource(context, R.mipmap.ic_shortcut_quicknote))
Expand All @@ -87,17 +87,13 @@ public static void setShortcuts(@NonNull Context context) {
newShortcuts.add(shortcutQuickNote);

// Generate shortcuts for the most recent documents. Maximum of MAX_RECENT_DOCUMENTS.
AppSettings settings = new AppSettings(context);
List<String> recentDocuments = settings.getRecentDocuments();
final AppSettings settings = new AppSettings(context);
final List<String> recentDocuments = settings.getRecentDocuments();

int count = 0;
for (String filePath : recentDocuments) {
if (count > MAX_RECENT_DOCUMENTS) break;
count++;
for (int i = 0; i < MAX_RECENT_DOCUMENTS; i++) {
final File file = new File(recentDocuments.get(i));

File file = new File(filePath);

Intent openFile = new Intent(context, OpenEditorFromShortcutOrWidgetActivity.class)
final Intent openFile = new Intent(context, OpenEditorFromShortcutOrWidgetActivity.class)
.setAction(Intent.ACTION_EDIT)
.setData(Uri.fromFile(file));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@

import net.gsantner.markor.R;
import net.gsantner.markor.format.TextFormat;
import net.gsantner.markor.model.Document;
import net.gsantner.markor.ui.FileInfoDialog;
import net.gsantner.markor.ui.FilesystemViewerCreator;
import net.gsantner.markor.ui.SearchOrCustomTextDialogCreator;
Expand Down Expand Up @@ -238,6 +239,7 @@ private void updateMenuItems() {
// Check if is a favourite
boolean isFavourite = false;
boolean selTextFilesOnly = true;
boolean selDirectoriesOnly = true;
boolean selWritable = (!curFilepath.equals("/storage") && !curFilepath.equals("/storage/emulated"));
if (selMulti1) {
for (File favourite : _dopt.favouriteFiles == null ? new ArrayList<File>() : _dopt.favouriteFiles) {
Expand All @@ -247,9 +249,10 @@ private void updateMenuItems() {
}
}
}
for (File f : _filesystemViewerAdapter.getCurrentSelection()) {
selTextFilesOnly = (selTextFilesOnly && TextFormat.isTextFile(f));
selWritable = (selWritable && f.canWrite());
for (final File f : _filesystemViewerAdapter.getCurrentSelection()) {
selTextFilesOnly &= TextFormat.isTextFile(f);
selWritable &= f.canWrite();
selDirectoriesOnly &= f.isDirectory();
}

if (_fragmentMenu != null && _fragmentMenu.findItem(R.id.action_delete_selected_items) != null) {
Expand All @@ -267,6 +270,7 @@ private void updateMenuItems() {
_fragmentMenu.findItem(R.id.action_favourite).setVisible(selMulti1 && !isFavourite);
_fragmentMenu.findItem(R.id.action_favourite_remove).setVisible(selMulti1 && isFavourite);
_fragmentMenu.findItem(R.id.action_fs_copy_to_clipboard).setVisible(selMulti1 && selTextFilesOnly);
_fragmentMenu.findItem(R.id.action_create_shortcut).setVisible(selMulti1 && (selFilesOnly || selDirectoriesOnly));
}
}

Expand Down Expand Up @@ -368,12 +372,16 @@ public FilesystemViewerAdapter getAdapter() {

@Override
public boolean onOptionsItemSelected(MenuItem item) {
PermissionChecker permc = new PermissionChecker(getActivity());
List<Pair<File, String>> appDataPublicDirs = _contextUtils.getAppDataPublicDirs(false, true, false);
final PermissionChecker permc = new PermissionChecker(getActivity());

File folderToLoad = null;

switch (item.getItemId()) {
case R.id.action_create_shortcut: {
final File file = _filesystemViewerAdapter.getCurrentSelection().iterator().next();
_shareUtil.createLauncherDesktopShortcut(new Document(file));
return true;
}
case R.id.action_sort_by_name: {
item.setChecked(true);
_appSettings.setSortMethod(SORT_BY_NAME);
Expand Down
7 changes: 7 additions & 0 deletions app/src/main/res/menu/filesystem__menu.xml
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@
android:visible="false"
app:showAsAction="never" />

<item
android:id="@+id/action_create_shortcut"
android:icon="@drawable/ic_widgets_black_24dp"
android:title="@string/create_shortcut"
android:visible="false"
app:showAsAction="never" />

<item
android:id="@+id/action_share_files"
android:icon="@drawable/ic_share_black_24dp"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,16 +52,14 @@ public void onDataSetChanged() {
}

private void updateFiles() {
_widgetFilesList = (_dir == null) ? new File[0] : _dir.listFiles(file ->
!file.isDirectory() && TextFormat.isTextFile(file)
);
_widgetFilesList = (_dir == null) ? new File[0] : _dir.listFiles(file -> !file.isDirectory() && TextFormat.isTextFile(file));
if (_dir != null && _dir.equals(FilesystemViewerAdapter.VIRTUAL_STORAGE_RECENTS)) {
_widgetFilesList = FilesystemViewerCreator.strlistToArray(AppSettings.get().getRecentDocuments());
}
if (_dir != null && _dir.equals(FilesystemViewerAdapter.VIRTUAL_STORAGE_POPULAR)) {
_widgetFilesList = FilesystemViewerCreator.strlistToArray(AppSettings.get().getPopularDocuments());
}
ArrayList<File> files = new ArrayList<>(Arrays.asList(_widgetFilesList != null ? _widgetFilesList : new File[0]));
final ArrayList<File> files = new ArrayList<>(Arrays.asList(_widgetFilesList != null ? _widgetFilesList : new File[0]));

//noinspection StatementWithEmptyBody
if (_dir != null && (_dir.equals(FilesystemViewerAdapter.VIRTUAL_STORAGE_RECENTS) || _dir.equals(FilesystemViewerAdapter.VIRTUAL_STORAGE_POPULAR))) {
Expand Down Expand Up @@ -97,9 +95,10 @@ public RemoteViews getViewAt(int position) {
else
rowView.setTextColor(R.id.widget_note_title, _context.getResources().getColor(R.color.light__primary_text));
if (position < _widgetFilesList.length) {
File file = _widgetFilesList[position];
Intent fillInIntent = new Intent().putExtra(Document.EXTRA_PATH, file).putExtra(Document.EXTRA_PATH_IS_FOLDER, file.isDirectory());
rowView.setTextViewText(R.id.widget_note_title, MarkdownTextConverter.MD_EXTENSION_PATTERN.matcher(file.getName()).replaceAll(""));
final File file = _widgetFilesList[position];
final Intent fillInIntent = new Intent().putExtra(Document.EXTRA_PATH, file)
.putExtra(Document.EXTRA_PATH_IS_FOLDER, file.isDirectory());
rowView.setTextViewText(R.id.widget_note_title, file.getName());
rowView.setOnClickFillInIntent(R.id.widget_note_title, fillInIntent);
}
return rowView;
Expand Down
Loading

0 comments on commit 0c27e81

Please sign in to comment.