1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.documentsui;
18
19import static com.android.documentsui.base.Shared.TAG;
20
21import android.app.AlertDialog;
22import android.app.Dialog;
23import android.app.DialogFragment;
24import android.app.FragmentManager;
25import android.content.ContentProviderClient;
26import android.content.ContentResolver;
27import android.content.Context;
28import android.content.DialogInterface;
29import android.content.DialogInterface.OnClickListener;
30import android.net.Uri;
31import android.os.AsyncTask;
32import android.os.Bundle;
33import android.provider.DocumentsContract;
34import android.provider.DocumentsContract.Document;
35import android.support.annotation.Nullable;
36import android.support.design.widget.Snackbar;
37import android.util.Log;
38import android.view.KeyEvent;
39import android.view.inputmethod.EditorInfo;
40import android.view.LayoutInflater;
41import android.view.View;
42import android.widget.EditText;
43import android.widget.TextView;
44import android.widget.TextView.OnEditorActionListener;
45
46import com.android.documentsui.base.DocumentInfo;
47import com.android.documentsui.base.Shared;
48import com.android.documentsui.ui.Snackbars;
49
50/**
51 * Dialog to create a new directory.
52 */
53public class CreateDirectoryFragment extends DialogFragment {
54    private static final String TAG_CREATE_DIRECTORY = "create_directory";
55
56    public static void show(FragmentManager fm) {
57        final CreateDirectoryFragment dialog = new CreateDirectoryFragment();
58        dialog.show(fm, TAG_CREATE_DIRECTORY);
59    }
60
61    @Override
62    public Dialog onCreateDialog(Bundle savedInstanceState) {
63        final Context context = getActivity();
64        final ContentResolver resolver = context.getContentResolver();
65
66        final AlertDialog.Builder builder = new AlertDialog.Builder(context);
67        final LayoutInflater dialogInflater = LayoutInflater.from(builder.getContext());
68
69        final View view = dialogInflater.inflate(R.layout.dialog_file_name, null, false);
70        final EditText editText = (EditText) view.findViewById(android.R.id.text1);
71
72        builder.setTitle(R.string.menu_create_dir);
73        builder.setView(view);
74
75        builder.setPositiveButton(
76                android.R.string.ok,
77                new OnClickListener() {
78                    @Override
79                    public void onClick(DialogInterface dialog, int which) {
80                        createDirectory(editText.getText().toString());
81                    }
82                });
83
84        builder.setNegativeButton(android.R.string.cancel, null);
85        final AlertDialog dialog = builder.create();
86
87        // Workaround for the problem - virtual keyboard doesn't show on the phone.
88        Shared.ensureKeyboardPresent(context, dialog);
89
90        editText.setOnEditorActionListener(
91                new OnEditorActionListener() {
92                    @Override
93                    public boolean onEditorAction(
94                            TextView view, int actionId, @Nullable KeyEvent event) {
95                        if ((actionId == EditorInfo.IME_ACTION_DONE) || (event != null
96                                && event.getKeyCode() == KeyEvent.KEYCODE_ENTER
97                                && event.hasNoModifiers())) {
98                            createDirectory(editText.getText().toString());
99                            dialog.dismiss();
100                            return true;
101                        }
102                        return false;
103                    }
104                });
105
106
107        return dialog;
108    }
109
110    private void createDirectory(String name) {
111        final BaseActivity activity = (BaseActivity) getActivity();
112        final DocumentInfo cwd = activity.getCurrentDirectory();
113
114        new CreateDirectoryTask(activity, cwd, name).executeOnExecutor(
115                ProviderExecutor.forAuthority(cwd.authority));
116    }
117
118    private class CreateDirectoryTask extends AsyncTask<Void, Void, DocumentInfo> {
119        private final BaseActivity mActivity;
120        private final DocumentInfo mCwd;
121        private final String mDisplayName;
122
123        public CreateDirectoryTask(
124                BaseActivity activity, DocumentInfo cwd, String displayName) {
125            mActivity = activity;
126            mCwd = cwd;
127            mDisplayName = displayName;
128        }
129
130        @Override
131        protected void onPreExecute() {
132            mActivity.setPending(true);
133        }
134
135        @Override
136        protected DocumentInfo doInBackground(Void... params) {
137            final ContentResolver resolver = mActivity.getContentResolver();
138            ContentProviderClient client = null;
139            try {
140                client = DocumentsApplication.acquireUnstableProviderOrThrow(
141                        resolver, mCwd.derivedUri.getAuthority());
142                final Uri childUri = DocumentsContract.createDocument(
143                        client, mCwd.derivedUri, Document.MIME_TYPE_DIR, mDisplayName);
144                return DocumentInfo.fromUri(resolver, childUri);
145            } catch (Exception e) {
146                Log.w(TAG, "Failed to create directory", e);
147                return null;
148            } finally {
149                ContentProviderClient.releaseQuietly(client);
150            }
151        }
152
153        @Override
154        protected void onPostExecute(DocumentInfo result) {
155            if (result != null) {
156                // Navigate into newly created child
157                mActivity.onDirectoryCreated(result);
158                Metrics.logCreateDirOperation(getContext());
159            } else {
160                Snackbars.makeSnackbar(mActivity, R.string.create_error, Snackbar.LENGTH_SHORT)
161                        .show();
162                Metrics.logCreateDirError(getContext());
163            }
164            mActivity.setPending(false);
165        }
166    }
167}
168