OSDN Git Service

Add support for renaming documents
authorAga Wronska <agawronska@google.com>
Thu, 21 Jan 2016 00:32:33 +0000 (16:32 -0800)
committerAga Wronska <agawronska@google.com>
Fri, 22 Jan 2016 21:36:40 +0000 (13:36 -0800)
- Add rename dialog
- Add rename menu option
- Enable rename menu option only when renaming supported
- Rename files and directories
- Present error message if renaming fails

Bug: 20493815
Change-Id: Ic7386d14e3876655fb19245b9a90b4c67a4febb4

packages/DocumentsUI/res/layout/dialog_file_name.xml [moved from packages/DocumentsUI/res/layout/dialog_create_dir.xml with 100% similarity]
packages/DocumentsUI/res/menu/mode_directory.xml
packages/DocumentsUI/res/values/strings.xml
packages/DocumentsUI/src/com/android/documentsui/BaseActivity.java
packages/DocumentsUI/src/com/android/documentsui/CreateDirectoryFragment.java
packages/DocumentsUI/src/com/android/documentsui/dirlist/DirectoryFragment.java
packages/DocumentsUI/src/com/android/documentsui/dirlist/FragmentTuner.java
packages/DocumentsUI/src/com/android/documentsui/dirlist/RenameDocumentFragment.java [new file with mode: 0644]
packages/DocumentsUI/src/com/android/documentsui/model/DocumentInfo.java
packages/DocumentsUI/tests/src/com/android/documentsui/StubProvider.java

index 4ff396f..6f9bfb5 100644 (file)
@@ -48,4 +48,9 @@
         android:title="@string/menu_move"
         android:showAsAction="never"
         android:visible="false" />
+    <item
+        android:id="@+id/menu_rename"
+        android:title="@string/menu_rename"
+        android:showAsAction="never"
+        android:visible="false" />
 </menu>
index 016657e..d9fb057 100644 (file)
@@ -87,7 +87,7 @@
     <!-- Button label that hides the error bar [CHAR LIMIT=24] -->
     <string name="button_dismiss">Dismiss</string>
     <string name="button_retry">Try Again</string>
-    
+
     <!-- Mode that sorts documents by their display name alphabetically [CHAR LIMIT=24] -->
     <string name="sort_name">By name</string>
     <!-- Mode that sorts documents by their last modified time in descending order; most recent first [CHAR LIMIT=24] -->
     </plurals>
     <!-- Toast shown when a user tries to paste files into an unsupported location. -->
     <string name="clipboard_files_cannot_paste">Cannot paste the selected files in this location.</string>
+    <!-- Menu item that renames the selected document [CHAR LIMIT=24] -->
+    <string name="menu_rename">Rename</string>
+    <!-- Toast shown when renaming document failed with an error [CHAR LIMIT=48] -->
+    <string name="rename_error">Failed to rename document</string>
 </resources>
index 0fb8daf..f43b81c 100644 (file)
@@ -437,7 +437,7 @@ public abstract class BaseActivity extends Activity implements SearchManagerList
         DirectoryFragment.get(getFragmentManager()).onUserModeChanged();
     }
 
-    void setPending(boolean pending) {
+    public void setPending(boolean pending) {
         final SaveFragment save = SaveFragment.get(getFragmentManager());
         if (save != null) {
             save.setPending(pending);
index f3c3f2f..df036b9 100644 (file)
@@ -63,7 +63,7 @@ public class CreateDirectoryFragment extends DialogFragment {
         final AlertDialog.Builder builder = new AlertDialog.Builder(context);
         final LayoutInflater dialogInflater = LayoutInflater.from(builder.getContext());
 
-        final View view = dialogInflater.inflate(R.layout.dialog_create_dir, null, false);
+        final View view = dialogInflater.inflate(R.layout.dialog_file_name, null, false);
         final EditText editText = (EditText) view.findViewById(android.R.id.text1);
 
         builder.setTitle(R.string.menu_create_dir);
index 580e2d8..1586ee7 100644 (file)
@@ -91,6 +91,7 @@ import com.android.documentsui.R;
 import com.android.documentsui.RecentLoader;
 import com.android.documentsui.RecentsProvider;
 import com.android.documentsui.RecentsProvider.StateColumns;
+import com.android.documentsui.dirlist.RenameDocumentFragment;
 import com.android.documentsui.RootsCache;
 import com.android.documentsui.Shared;
 import com.android.documentsui.Snackbars;
@@ -651,6 +652,7 @@ public class DirectoryFragment extends Fragment implements DocumentsAdapter.Envi
         private Selection mSelected = new Selection();
         private ActionMode mActionMode;
         private int mNoDeleteCount = 0;
+        private int mNoRenameCount = -1;
         private Menu mMenu;
 
         @Override
@@ -674,6 +676,9 @@ public class DirectoryFragment extends Fragment implements DocumentsAdapter.Envi
             if ((docFlags & Document.FLAG_SUPPORTS_DELETE) == 0) {
                 mNoDeleteCount += selected ? 1 : -1;
             }
+            if ((docFlags & Document.FLAG_SUPPORTS_RENAME) != 0) {
+                mNoRenameCount += selected ? 1 : -1;
+            }
         }
 
         @Override
@@ -712,6 +717,7 @@ public class DirectoryFragment extends Fragment implements DocumentsAdapter.Envi
             mSelectionManager.clearSelection();
             mSelected.clear();
             mNoDeleteCount = 0;
+            mNoRenameCount = -1;
         }
 
         @Override
@@ -729,10 +735,19 @@ public class DirectoryFragment extends Fragment implements DocumentsAdapter.Envi
             return true;
         }
 
+        boolean canRenameSelection() {
+            return mNoRenameCount == 0 && mSelectionManager.getSelection().size() == 1;
+        }
+
+        boolean canDeleteSelection() {
+            return mNoDeleteCount == 0;
+        }
+
         private void updateActionMenu() {
             checkNotNull(mMenu);
+
             // Delegate update logic to our owning action, since specialized logic is desired.
-            mTuner.updateActionMenu(mMenu, mType, mNoDeleteCount == 0);
+            mTuner.updateActionMenu(mMenu, mType, canDeleteSelection(), canRenameSelection());
             Menus.disableHiddenItems(mMenu);
         }
 
@@ -772,6 +787,7 @@ public class DirectoryFragment extends Fragment implements DocumentsAdapter.Envi
                 case R.id.menu_copy_to_clipboard:
                     if (!selection.isEmpty()) {
                         copySelectionToClipboard(selection);
+                        mode.finish();
                     }
                     return true;
 
@@ -779,6 +795,11 @@ public class DirectoryFragment extends Fragment implements DocumentsAdapter.Envi
                     selectAllFiles();
                     return true;
 
+                case R.id.menu_rename:
+                    renameDocuments(selection);
+                    mode.finish();
+                    return true;
+
                 default:
                     if (DEBUG) Log.d(TAG, "Unhandled menu item selected: " + item);
                     return false;
@@ -924,6 +945,19 @@ public class DirectoryFragment extends Fragment implements DocumentsAdapter.Envi
         }.execute(selected);
     }
 
+    private void renameDocuments(Selection selected) {
+        // Batch renaming not supported
+        // Rename option is only available in menu when 1 document selected
+        checkArgument(selected.size() == 1);
+
+        new GetDocumentsTask() {
+            @Override
+            void onDocumentsReady(List<DocumentInfo> docs) {
+                RenameDocumentFragment.show(getFragmentManager(), docs.get(0));
+            }
+        }.execute(selected);
+    }
+
     @Override
     public void initDocumentHolder(DocumentHolder holder) {
         holder.addClickListener(mItemClickListener);
index ef6d2c9..a295ab2 100644 (file)
@@ -58,7 +58,8 @@ public abstract class FragmentTuner {
     }
 
 
-    public abstract void updateActionMenu(Menu menu, int dirType, boolean canDelete);
+    public abstract void updateActionMenu(Menu menu, int dirType, boolean canDelete,
+            boolean canRename);
 
     // Subtly different from isDocumentEnabled. The reason may be illuminated as follows.
     // A folder is enabled such that it may be double clicked, even in settings
@@ -129,7 +130,8 @@ public abstract class FragmentTuner {
         }
 
         @Override
-        public void updateActionMenu(Menu menu, int dirType, boolean canDelete) {
+        public void updateActionMenu(Menu menu, int dirType, boolean canDelete,
+                boolean canRename) {
 
             boolean copyEnabled = dirType != DirectoryFragment.TYPE_RECENT_OPEN;
             boolean moveEnabled =
@@ -141,6 +143,7 @@ public abstract class FragmentTuner {
             final MenuItem delete = menu.findItem(R.id.menu_delete);
             final MenuItem copyTo = menu.findItem(R.id.menu_copy_to);
             final MenuItem moveTo = menu.findItem(R.id.menu_move_to);
+            final MenuItem rename = menu.findItem(R.id.menu_rename);
 
             open.setVisible(true);
             share.setVisible(false);
@@ -149,6 +152,7 @@ public abstract class FragmentTuner {
             copyTo.setEnabled(copyEnabled);
             moveTo.setVisible(moveEnabled);
             moveTo.setEnabled(moveEnabled);
+            rename.setVisible(false);
         }
     }
 
@@ -162,7 +166,8 @@ public abstract class FragmentTuner {
         }
 
         @Override
-        public void updateActionMenu(Menu menu, int dirType, boolean canDelete) {
+        public void updateActionMenu(Menu menu, int dirType, boolean canDelete,
+                boolean canRename) {
             checkArgument(dirType != DirectoryFragment.TYPE_RECENT_OPEN);
 
             boolean moveEnabled =
@@ -174,6 +179,7 @@ public abstract class FragmentTuner {
             final MenuItem delete = menu.findItem(R.id.menu_delete);
             final MenuItem copyTo = menu.findItem(R.id.menu_copy_to);
             final MenuItem moveTo = menu.findItem(R.id.menu_move_to);
+            final MenuItem rename = menu.findItem(R.id.menu_rename);
 
             open.setVisible(false);
             delete.setVisible(canDelete);
@@ -181,6 +187,7 @@ public abstract class FragmentTuner {
             copyTo.setEnabled(true);
             moveTo.setVisible(moveEnabled);
             moveTo.setEnabled(moveEnabled);
+            rename.setVisible(false);
         }
     }
 
@@ -194,12 +201,17 @@ public abstract class FragmentTuner {
         }
 
         @Override
-        public void updateActionMenu(Menu menu, int dirType, boolean canDelete) {
+        public void updateActionMenu(Menu menu, int dirType, boolean canDelete,
+                boolean canRename) {
 
             MenuItem copy = menu.findItem(R.id.menu_copy_to_clipboard);
             MenuItem paste = menu.findItem(R.id.menu_paste_from_clipboard);
             copy.setEnabled(dirType != DirectoryFragment.TYPE_RECENT_OPEN);
 
+            MenuItem rename = menu.findItem(R.id.menu_rename);
+            rename.setVisible(true);
+            rename.setEnabled(canRename);
+
             menu.findItem(R.id.menu_share).setVisible(true);
             menu.findItem(R.id.menu_delete).setVisible(canDelete);
 
diff --git a/packages/DocumentsUI/src/com/android/documentsui/dirlist/RenameDocumentFragment.java b/packages/DocumentsUI/src/com/android/documentsui/dirlist/RenameDocumentFragment.java
new file mode 100644 (file)
index 0000000..71708c1
--- /dev/null
@@ -0,0 +1,158 @@
+/*
+ * Copyright (C) 2016 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.documentsui.dirlist;
+
+import static com.android.documentsui.Shared.TAG;
+import static com.android.internal.util.Preconditions.checkArgument;
+
+import android.app.AlertDialog;
+import android.app.Dialog;
+import android.app.DialogFragment;
+import android.app.FragmentManager;
+import android.content.ContentProviderClient;
+import android.content.ContentResolver;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.DialogInterface.OnClickListener;
+import android.net.Uri;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.provider.DocumentsContract;
+import android.support.annotation.Nullable;
+import android.support.design.widget.Snackbar;
+import android.util.Log;
+import android.view.KeyEvent;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.widget.EditText;
+import android.widget.TextView;
+import android.widget.TextView.OnEditorActionListener;
+
+import com.android.documentsui.BaseActivity;
+import com.android.documentsui.DocumentsApplication;
+import com.android.documentsui.model.DocumentInfo;
+import com.android.documentsui.R;
+import com.android.documentsui.Snackbars;
+/**
+ * Dialog to rename file or directory.
+ */
+class RenameDocumentFragment extends DialogFragment {
+    private static final String TAG_RENAME_DOCUMENT = "rename_document";
+    private DocumentInfo mDocument;
+
+    public static void show(FragmentManager fm, DocumentInfo document) {
+        final RenameDocumentFragment dialog = new RenameDocumentFragment();
+        dialog.mDocument = document;
+        dialog.show(fm, TAG_RENAME_DOCUMENT);
+    }
+
+    @Override
+    public Dialog onCreateDialog(Bundle savedInstanceState) {
+        Context context = getActivity();
+        AlertDialog.Builder builder = new AlertDialog.Builder(context);
+        LayoutInflater dialogInflater = LayoutInflater.from(builder.getContext());
+        View view = dialogInflater.inflate(R.layout.dialog_file_name, null, false);
+
+        final EditText editText = (EditText) view.findViewById(android.R.id.text1);
+        editText.setText(mDocument.displayName);
+
+        builder.setTitle(R.string.menu_rename);
+        builder.setView(view);
+
+        builder.setPositiveButton(
+                android.R.string.ok,
+                new OnClickListener() {
+                    @Override
+                    public void onClick(DialogInterface dialog, int which) {
+                        renameDocuments(editText.getText().toString());
+                    }
+                });
+
+        builder.setNegativeButton(android.R.string.cancel, null);
+
+        final AlertDialog dialog = builder.create();
+
+        editText.setOnEditorActionListener(
+                new OnEditorActionListener() {
+                    @Override
+                    public boolean onEditorAction(
+                            TextView view, int actionId, @Nullable KeyEvent event) {
+                        if (event != null
+                                && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
+                                && event.hasNoModifiers()) {
+                            renameDocuments(editText.getText().toString());
+                            dialog.dismiss();
+                            return true;
+                        }
+                        return false;
+                    }
+                });
+
+        return dialog;
+    }
+
+    private void renameDocuments(String newDisplayName) {
+        BaseActivity activity = (BaseActivity) getActivity();
+
+        new RenameDocumentsTask(activity, newDisplayName).execute(mDocument);
+    }
+
+    private class RenameDocumentsTask extends AsyncTask<DocumentInfo, Void, DocumentInfo> {
+        private final BaseActivity mActivity;
+        private final String mNewDisplayName;
+
+        public RenameDocumentsTask(BaseActivity activity, String newDisplayName) {
+            mActivity = activity;
+            mNewDisplayName = newDisplayName;
+        }
+
+        @Override
+        protected void onPreExecute() {
+            mActivity.setPending(true);
+        }
+
+        @Override
+        protected DocumentInfo doInBackground(DocumentInfo... document) {
+            checkArgument(document.length == 1);
+            final ContentResolver resolver = mActivity.getContentResolver();
+            ContentProviderClient client = null;
+
+            try {
+                client = DocumentsApplication.acquireUnstableProviderOrThrow(
+                        resolver, document[0].derivedUri.getAuthority());
+                Uri newUri = DocumentsContract.renameDocument(
+                        client, document[0].derivedUri, mNewDisplayName);
+                return DocumentInfo.fromUri(resolver, newUri);
+            } catch (Exception e) {
+                Log.w(TAG, "Failed to rename file", e);
+                return null;
+            } finally {
+                ContentProviderClient.releaseQuietly(client);
+            }
+        }
+
+        @Override
+        protected void onPostExecute(DocumentInfo result) {
+            if (result == null) {
+                Snackbars.makeSnackbar(mActivity, R.string.rename_error, Snackbar.LENGTH_SHORT)
+                        .show();
+            }
+
+            mActivity.setPending(false);
+        }
+    }
+}
index 83df18c..4b5499a 100644 (file)
@@ -239,6 +239,10 @@ public class DocumentInfo implements Durable, Parcelable {
         return (flags & Document.FLAG_SUPPORTS_DELETE) != 0;
     }
 
+    public boolean isRenameSupported() {
+        return (flags & Document.FLAG_SUPPORTS_RENAME) != 0;
+    }
+
     public boolean isGridTitlesHidden() {
         return (flags & Document.FLAG_DIR_HIDE_GRID_TITLES) != 0;
     }
index fb6445b..b1ba37e 100644 (file)
@@ -625,7 +625,7 @@ public class StubProvider extends DocumentsProvider {
             this.documentId = getDocumentIdForFile(file);
             this.mimeType = Document.MIME_TYPE_DIR;
             this.streamTypes = new ArrayList<String>();
-            this.flags = Document.FLAG_DIR_SUPPORTS_CREATE;
+            this.flags = Document.FLAG_DIR_SUPPORTS_CREATE | Document.FLAG_SUPPORTS_RENAME;
             this.parentId = null;
             this.rootInfo = rootInfo;
         }