summaryrefslogtreecommitdiffstats
path: root/sl4a/Common/src/com/googlecode/android_scripting/facade/ui/AlertDialogTask.java
blob: 2a1e48efe52d406a802ad8c8bfb170e3a9f689ce (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
/*
 * Copyright (C) 2016 Google Inc.
 *
 * 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.googlecode.android_scripting.facade.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.text.method.PasswordTransformationMethod;
import android.widget.EditText;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import org.json.JSONArray;
import org.json.JSONException;

/**
 * Wrapper class for alert dialog running in separate thread.
 *
 * @author MeanEYE.rcf (meaneye.rcf@gmail.com)
 */
class AlertDialogTask extends DialogTask {

  private final String mTitle;
  private final String mMessage;

  private final List<String> mItems;
  private final Set<Integer> mSelectedItems;
  private final Map<String, Object> mResultMap;
  private InputType mInputType;
  private int mEditInputType = 0;

  private String mPositiveButtonText;
  private String mNegativeButtonText;
  private String mNeutralButtonText;

  private EditText mEditText;
  private String mDefaultText;

  private enum InputType {
    DEFAULT, MENU, SINGLE_CHOICE, MULTI_CHOICE, PLAIN_TEXT, PASSWORD;
  }

  public AlertDialogTask(String title, String message) {
    mTitle = title;
    mMessage = message;
    mInputType = InputType.DEFAULT;
    mItems = new ArrayList<String>();
    mSelectedItems = new TreeSet<Integer>();
    mResultMap = new HashMap<String, Object>();
  }

  public void setPositiveButtonText(String text) {
    mPositiveButtonText = text;
  }

  public void setNegativeButtonText(String text) {
    mNegativeButtonText = text;
  }

  public void setNeutralButtonText(String text) {
    mNeutralButtonText = text;
  }

  /**
   * Set list items.
   *
   * @param items
   */
  public void setItems(JSONArray items) {
    mItems.clear();
    for (int i = 0; i < items.length(); i++) {
      try {
        mItems.add(items.getString(i));
      } catch (JSONException e) {
        throw new RuntimeException(e);
      }
    }
    mInputType = InputType.MENU;
  }

  /**
   * Set single choice items.
   *
   * @param items
   *          a list of items as {@link String}s to display
   * @param selected
   *          the index of the item that is selected by default
   */
  public void setSingleChoiceItems(JSONArray items, int selected) {
    setItems(items);
    mSelectedItems.clear();
    mSelectedItems.add(selected);
    mInputType = InputType.SINGLE_CHOICE;
  }

  /**
   * Set multi choice items.
   *
   * @param items
   *          a list of items as {@link String}s to display
   * @param selected
   *          a list of indices for items that should be selected by default
   * @throws JSONException
   */
  public void setMultiChoiceItems(JSONArray items, JSONArray selected) throws JSONException {
    setItems(items);
    mSelectedItems.clear();
    if (selected != null) {
      for (int i = 0; i < selected.length(); i++) {
        mSelectedItems.add(selected.getInt(i));
      }
    }
    mInputType = InputType.MULTI_CHOICE;
  }

  /**
   * Returns the list of selected items.
   */
  public Set<Integer> getSelectedItems() {
    return mSelectedItems;
  }

  public void setTextInput(String defaultText) {
    mDefaultText = defaultText;
    mInputType = InputType.PLAIN_TEXT;
    setEditInputType("text");
  }

  public void setEditInputType(String editInputType) {
    String[] list = editInputType.split("\\|");
    Map<String, Integer> types = ViewInflater.getInputTypes();
    mEditInputType = 0;
    for (String flag : list) {
      Integer v = types.get(flag.trim());
      if (v != null) {
        mEditInputType |= v;
      }
    }
    if (mEditInputType == 0) {
      mEditInputType = android.text.InputType.TYPE_CLASS_TEXT;
    }
  }

  public void setPasswordInput() {
    mInputType = InputType.PASSWORD;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    if (mTitle != null) {
      builder.setTitle(mTitle);
    }
    // Can't display both a message and items. We'll elect to show the items instead.
    if (mMessage != null && mItems.isEmpty()) {
      builder.setMessage(mMessage);
    }
    switch (mInputType) {
    // Add single choice menu items to dialog.
    case SINGLE_CHOICE:
      builder.setSingleChoiceItems(getItemsAsCharSequenceArray(), mSelectedItems.iterator().next(),
          new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
              mSelectedItems.clear();
              mSelectedItems.add(item);
            }
          });
      break;
    // Add multiple choice items to the dialog.
    case MULTI_CHOICE:
      boolean[] selectedItems = new boolean[mItems.size()];
      for (int i : mSelectedItems) {
        selectedItems[i] = true;
      }
      builder.setMultiChoiceItems(getItemsAsCharSequenceArray(), selectedItems,
          new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item, boolean isChecked) {
              if (isChecked) {
                mSelectedItems.add(item);
              } else {
                mSelectedItems.remove(item);
              }
            }
          });
      break;
    // Add standard, menu-like, items to dialog.
    case MENU:
      builder.setItems(getItemsAsCharSequenceArray(), new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
          Map<String, Integer> result = new HashMap<String, Integer>();
          result.put("item", item);
          dismissDialog();
          setResult(result);
        }
      });
      break;
    case PLAIN_TEXT:
      mEditText = new EditText(getActivity());
      if (mDefaultText != null) {
        mEditText.setText(mDefaultText);
      }
      mEditText.setInputType(mEditInputType);
      builder.setView(mEditText);
      break;
    case PASSWORD:
      mEditText = new EditText(getActivity());
      mEditText.setInputType(android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD);
      mEditText.setTransformationMethod(new PasswordTransformationMethod());
      builder.setView(mEditText);
      break;
    default:
      // No input type specified.
    }
    configureButtons(builder, getActivity());
    addOnCancelListener(builder, getActivity());
    mDialog = builder.show();
    mShowLatch.countDown();
  }

  private CharSequence[] getItemsAsCharSequenceArray() {
    return mItems.toArray(new CharSequence[mItems.size()]);
  }

  private Builder addOnCancelListener(final AlertDialog.Builder builder, final Activity activity) {
    return builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
      @Override
      public void onCancel(DialogInterface dialog) {
        mResultMap.put("canceled", true);
        setResult();
      }
    });
  }

  private void configureButtons(final AlertDialog.Builder builder, final Activity activity) {
    DialogInterface.OnClickListener buttonListener = new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which) {
        switch (which) {
        case DialogInterface.BUTTON_POSITIVE:
          mResultMap.put("which", "positive");
          break;
        case DialogInterface.BUTTON_NEGATIVE:
          mResultMap.put("which", "negative");
          break;
        case DialogInterface.BUTTON_NEUTRAL:
          mResultMap.put("which", "neutral");

          break;
        }
        setResult();
      }
    };
    if (mNegativeButtonText != null) {
      builder.setNegativeButton(mNegativeButtonText, buttonListener);
    }
    if (mPositiveButtonText != null) {
      builder.setPositiveButton(mPositiveButtonText, buttonListener);
    }
    if (mNeutralButtonText != null) {
      builder.setNeutralButton(mNeutralButtonText, buttonListener);
    }
  }

  private void setResult() {
    dismissDialog();
    if (mInputType == InputType.PLAIN_TEXT || mInputType == InputType.PASSWORD) {
      mResultMap.put("value", mEditText.getText().toString());
    }
    setResult(mResultMap);
  }

}