summaryrefslogtreecommitdiff
path: root/src/us/minak/SettingsActivity.java
blob: b33300261191e042c23fe5080ff1b44bd1f7cbd5 (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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
/*
 * Copyright (C) 2009 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 us.minak;

import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.gesture.Gesture;
import android.gesture.GestureLibrary;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class SettingsActivity extends ListActivity {
	private static final int STATUS_SUCCESS = 0;
	private static final int STATUS_CANCELLED = 1;
	private static final int STATUS_NO_STORAGE = 2;
	private static final int STATUS_NOT_LOADED = 3;

	private static final int MENU_ID_REMOVE = 1;

	private static final int REQUEST_NEW_GESTURE = 1;

	private final Comparator<NamedGesture> mSorter = new Comparator<NamedGesture>() {
		public int compare(NamedGesture object1, NamedGesture object2) {
			return object1.name.compareTo(object2.name);
		}
	};

	private GesturesAdapter mAdapter;
	private GesturesLoadTask mTask;
	private TextView mEmptyMessageView;

	// Hacky constructor to get 'this' out of scope ///////////////////////////

	private SettingsActivity mThis;

	public SettingsActivity() {
		super();
		mThis = this;
	}

	// /////////////////////////////////////////////////////////////////////////

	private void loadGestures() {
		if (mTask != null
				&& mTask.getStatus() != GesturesLoadTask.Status.FINISHED) {
			mTask.cancel(true);
		}
		mTask = (GesturesLoadTask) new GesturesLoadTask().execute();
	}

	public void uploadGestures() {
	    // Create a new HttpClient and Post Header
		   PostTask task = new PostTask();
		   task.setActivity(this);
		   task.execute("https://lukeshu.com/minak-server");
	}

	public void uploadGestures(View view) {
		uploadGestures();
	}

	private void checkForEmpty() {
		if (mAdapter.getCount() == 0) {
			mEmptyMessageView.setText(R.string.gestures_empty);
		}
	}

	// Basic life-cycle ///////////////////////////////////////////////////////
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gestures_list);
		setListAdapter(mAdapter = new GesturesAdapter(this));

		mEmptyMessageView = (TextView) findViewById(android.R.id.empty);
		loadGestures();

		registerForContextMenu(getListView());
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		if (mTask != null
				&& mTask.getStatus() != GesturesLoadTask.Status.FINISHED) {
			mTask.cancel(true);
			mTask = null;
		}
	}

	// The buttons at the bottom //////////////////////////////////////////////

	/** Called by onClick */
	public void reloadGestures(View v) {
		loadGestures();
	}

	/** Called by onClick */
	public void addGesture(View v) {
		Intent intent = new Intent(this, SettingsCreateGestureActivity.class);
		startActivityForResult(intent, REQUEST_NEW_GESTURE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case REQUEST_NEW_GESTURE:
				loadGestures();
				break;
			}
		}
	}

	// Context menu ///////////////////////////////////////////////////////////

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);

		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;

		menu.setHeaderTitle(((TextView) info.targetView).getText());
		menu.add(0, MENU_ID_REMOVE, 0, R.string.gestures_delete);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final AdapterView.AdapterContextMenuInfo menuInfo = (AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo();
		final NamedGesture gesture = (NamedGesture) menuInfo.targetView
				.getTag();

		switch (item.getItemId()) {
		case MENU_ID_REMOVE:
			SettingsUtil.getGestureLibrary(this).removeGesture(gesture.name,
					gesture.gesture);
			SettingsUtil.getGestureLibrary(this).save();

			mAdapter.setNotifyOnChange(false);
			mAdapter.remove(gesture);
			mAdapter.sort(mSorter);
			checkForEmpty();
			mAdapter.notifyDataSetChanged();

			Toast.makeText(this, R.string.gestures_delete_success,
					Toast.LENGTH_SHORT).show();
			return true;
		}

		return super.onContextItemSelected(item);
	}

	// /////////////////////////////////////////////////////////////////////////

	private class GesturesLoadTask extends
			AsyncTask<Void, NamedGesture, Integer> {
		private int mThumbnailSize;
		private int mThumbnailInset;
		private int mPathColor;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			final Resources resources = getResources();
			mPathColor = resources.getColor(R.color.gesture_color);
			mThumbnailInset = (int) resources
					.getDimension(R.dimen.gesture_thumbnail_inset);
			mThumbnailSize = (int) resources
					.getDimension(R.dimen.gesture_thumbnail_size);

			findViewById(R.id.addButton).setEnabled(false);
			findViewById(R.id.reloadButton).setEnabled(false);

			mAdapter.setNotifyOnChange(false);
			mAdapter.clear();
		}

		@Override
		protected Integer doInBackground(Void... params) {
			if (isCancelled())
				return STATUS_CANCELLED;
			if (!Environment.MEDIA_MOUNTED.equals(Environment
					.getExternalStorageState())) {
				return STATUS_NO_STORAGE;
			}

			final GestureLibrary store = SettingsUtil.getGestureLibrary(mThis);

			if (store.load()) {
				for (String name : store.getGestureEntries()) {
					if (isCancelled())
						break;

					for (Gesture gesture : store.getGestures(name)) {
						final Bitmap bitmap = gesture.toBitmap(mThumbnailSize,
								mThumbnailSize, mThumbnailInset, mPathColor);
						final NamedGesture namedGesture = new NamedGesture();
						namedGesture.gesture = gesture;
						namedGesture.name = name;

						mAdapter.addBitmap(namedGesture.gesture.getID(), bitmap);
						publishProgress(namedGesture);
					}
				}

				return STATUS_SUCCESS;
			}

			return STATUS_NOT_LOADED;
		}

		@Override
		protected void onProgressUpdate(NamedGesture... values) {
			super.onProgressUpdate(values);

			final GesturesAdapter adapter = mAdapter;
			adapter.setNotifyOnChange(false);

			for (NamedGesture gesture : values) {
				adapter.add(gesture);
			}

			adapter.sort(mSorter);
			adapter.notifyDataSetChanged();
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);

			if (result == STATUS_NO_STORAGE) {
				getListView().setVisibility(View.GONE);
				mEmptyMessageView.setVisibility(View.VISIBLE);
				mEmptyMessageView.setText(getString(
						R.string.gestures_error_loading, SettingsUtil
								.getGestureFile(mThis).getAbsolutePath()));
			} else {
				findViewById(R.id.addButton).setEnabled(true);
				findViewById(R.id.reloadButton).setEnabled(true);
				checkForEmpty();
			}
		}
	}

	static class NamedGesture {
		String name;
		Gesture gesture;
	}

	private class GesturesAdapter extends ArrayAdapter<NamedGesture> {
		private final LayoutInflater mInflater;
		private final Map<Long, Drawable> mThumbnails = Collections
				.synchronizedMap(new HashMap<Long, Drawable>());

		public GesturesAdapter(Context context) {
			super(context, 0);
			mInflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		void addBitmap(Long id, Bitmap bitmap) {
			mThumbnails.put(id, new BitmapDrawable(getResources(), bitmap));
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.gestures_item, parent,
						false);
			}

			final NamedGesture gesture = getItem(position);
			final TextView label = (TextView) convertView;

			label.setTag(gesture);
			label.setText(gesture.name);
			label.setCompoundDrawablesWithIntrinsicBounds(
					mThumbnails.get(gesture.gesture.getID()), null, null, null);

			return convertView;
		}
	}
	
	class PostTask extends AsyncTask<String, String, String>{

		private SettingsActivity mThis;
		
	    @Override
	    protected String doInBackground(String... uri) {
	    	
	    	Log.w(NOTIFICATION_SERVICE, "Begin request");
	    	
		    HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost("http://lukeshu.com/minak-server");
		    if (!httppost.containsHeader("Host")) {
		    	httppost.addHeader("Host", "lukeshu.com");
		    	Log.w(NOTIFICATION_SERVICE, "added host header");
	    	}else{
		    	Log.w(NOTIFICATION_SERVICE, "did not add host header");
	    	}
		    for (Header header : httppost.getAllHeaders()) {
		    	Log.d("header", header.toString());
		    }
		    
		    HttpResponse response = null;
		    try {
		    	httppost.setEntity(new FileEntity(SettingsUtil.getGestureFile(mThis), "application/octet-stream"));
		    	Log.d("postdata", httppost.getEntity().getContent().toString());
		        response = httpclient.execute(httppost);
		    	Log.w(NOTIFICATION_SERVICE, "Extend");

				Toast toast = Toast.makeText(mThis, response.toString(), Toast.LENGTH_LONG);
				toast.show();

		    } catch (ClientProtocolException e) {
		    	Log.w(NOTIFICATION_SERVICE, "fil");
		        // TODO Auto-generated catch block
		    } catch (IOException e) {
		    	Log.w(NOTIFICATION_SERVICE, e.getMessage());
		    	e.printStackTrace();
		        // TODO Auto-generated catch block
		    }catch (Exception e){
		    	Log.w(NOTIFICATION_SERVICE, e.getMessage());
		    }

		    if (response != null){
		    	return response.toString();
		    } else {
		    	return "";
		    }
	    }
	    
	    @Override
	    protected void onPostExecute(String result) {
	        //Do anything with response..
	    	;
	    }
	    
	    public void setActivity(Activity ack) {
	    	mThis = (SettingsActivity) ack;
	    }
	    
	}
}