aboutsummaryrefslogtreecommitdiffstats
path: root/app/src/main/java/org/connectbot/HostEditorActivity.java
blob: 902cfeffe2d3dc50355cf2e401c8e608e617a924 (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
397
398
399
400
401
402
403
404
405
406
407
408
409
/*
 * ConnectBot: simple, powerful, open-source SSH client for Android
 * Copyright 2007 Kenny Root, Jeffrey Sharkey
 *
 * 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 org.connectbot;

import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.connectbot.bean.HostBean;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import org.connectbot.util.HostDatabase;
import org.connectbot.util.PubkeyDatabase;

import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.SwitchPreference;
import android.util.Log;

public class HostEditorActivity extends AppCompatPreferenceActivity implements OnSharedPreferenceChangeListener {
	public class CursorPreferenceHack implements SharedPreferences {
		protected final String table;
		protected final long id;

		protected Map<String, String> values = new HashMap<String, String>();
//		protected Map<String, String> pubkeys = new HashMap<String, String>();

		public CursorPreferenceHack(String table, long id) {
			this.table = table;
			this.id = id;

			cacheValues();
		}

		protected final void cacheValues() {
			// fill a cursor and cache the values locally
			// this makes sure we don't have any floating cursor to dispose later

			SQLiteDatabase db = hostdb.getWritableDatabase();
			Cursor cursor = db.query(table, null, "_id = ?",
					new String[] { String.valueOf(id) }, null, null, null);

			if (cursor.moveToFirst()) {
				for (int i = 0; i < cursor.getColumnCount(); i++) {
					String key = cursor.getColumnName(i);
					String value = cursor.getString(i);
					values.put(key, value);
				}
			}
			cursor.close();
		}

		public boolean contains(String key) {
			return values.containsKey(key);
		}

		public class Editor implements SharedPreferences.Editor {

			private ContentValues update = new ContentValues();

			public SharedPreferences.Editor clear() {
				Log.d(this.getClass().toString(), "clear()");
				update = new ContentValues();
				return this;
			}

			public boolean commit() {
				SQLiteDatabase db = hostdb.getWritableDatabase();
				db.beginTransaction();
				try {
					db.update(table, update, "_id = ?", new String[] {String.valueOf(id)});
					db.setTransactionSuccessful();
				} finally {
					db.endTransaction();
				}

				// make sure we refresh the parent cached values
				cacheValues();

				// and update any listeners
				for (OnSharedPreferenceChangeListener listener : listeners) {
					listener.onSharedPreferenceChanged(CursorPreferenceHack.this, null);
				}

				return true;
			}

			// Gingerbread compatibility
			public void apply() {
				commit();
			}

			public android.content.SharedPreferences.Editor putBoolean(String key, boolean value) {
				return this.putString(key, Boolean.toString(value));
			}

			public android.content.SharedPreferences.Editor putFloat(String key, float value) {
				return this.putString(key, Float.toString(value));
			}

			public android.content.SharedPreferences.Editor putInt(String key, int value) {
				return this.putString(key, Integer.toString(value));
			}

			public android.content.SharedPreferences.Editor putLong(String key, long value) {
				return this.putString(key, Long.toString(value));
			}

			public android.content.SharedPreferences.Editor putString(String key, String value) {
				//Log.d(this.getClass().toString(), String.format("Editor.putString(key=%s, value=%s)", key, value));
				update.put(key, value);
				return this;
			}

			public android.content.SharedPreferences.Editor remove(String key) {
				//Log.d(this.getClass().toString(), String.format("Editor.remove(key=%s)", key));
				update.remove(key);
				return this;
			}

			public android.content.SharedPreferences.Editor putStringSet(String key, Set<String> value) {
				throw new UnsupportedOperationException("HostEditor Prefs do not support Set<String>");
			}
		}


		public Editor edit() {
			//Log.d(this.getClass().toString(), "edit()");
			return new Editor();
		}

		public Map<String, ?> getAll() {
			return values;
		}

		public boolean getBoolean(String key, boolean defValue) {
			return Boolean.valueOf(this.getString(key, Boolean.toString(defValue)));
		}

		public float getFloat(String key, float defValue) {
			return Float.valueOf(this.getString(key, Float.toString(defValue)));
		}

		public int getInt(String key, int defValue) {
			return Integer.valueOf(this.getString(key, Integer.toString(defValue)));
		}

		public long getLong(String key, long defValue) {
			return Long.valueOf(this.getString(key, Long.toString(defValue)));
		}

		public String getString(String key, String defValue) {
			//Log.d(this.getClass().toString(), String.format("getString(key=%s, defValue=%s)", key, defValue));

			if (!values.containsKey(key)) return defValue;
			return values.get(key);
		}

		public Set<String> getStringSet(String key, Set<String> defValue) {
			throw new ClassCastException("HostEditor Prefs do not support Set<String>");
		}

		protected List<OnSharedPreferenceChangeListener> listeners = new LinkedList<OnSharedPreferenceChangeListener>();

		public void registerOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
			listeners.add(listener);
		}

		public void unregisterOnSharedPreferenceChangeListener(OnSharedPreferenceChangeListener listener) {
			listeners.remove(listener);
		}

	}

	@Override
	public SharedPreferences getSharedPreferences(String name, int mode) {
		//Log.d(this.getClass().toString(), String.format("getSharedPreferences(name=%s)", name));
		return this.pref;
	}

	protected static final String TAG = "CB.HostEditorActivity";

	protected HostDatabase hostdb = null;
	private PubkeyDatabase pubkeydb = null;

	private CursorPreferenceHack pref;
	private ServiceConnection connection;

	private HostBean host;
	protected TerminalBridge hostBridge;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		long hostId = this.getIntent().getLongExtra(Intent.EXTRA_TITLE, -1);

		// TODO: we could pass through a specific ContentProvider uri here
		//this.getPreferenceManager().setSharedPreferencesName(uri);

		this.hostdb = HostDatabase.get(this);
		this.pubkeydb = PubkeyDatabase.get(this);

		host = hostdb.findHostById(hostId);

		connection = new ServiceConnection() {
			public void onServiceConnected(ComponentName className, IBinder service) {
				TerminalManager bound = ((TerminalManager.TerminalBinder) service).getService();

				hostBridge = bound.getConnectedBridge(host);
			}

			public void onServiceDisconnected(ComponentName name) {
				hostBridge = null;
			}
		};

		this.pref = new CursorPreferenceHack(HostDatabase.TABLE_HOSTS, hostId);
		this.pref.registerOnSharedPreferenceChangeListener(this);

		this.addPreferencesFromResource(R.xml.host_prefs);

		// add all existing pubkeys to our listpreference for user to choose from
		// TODO: may be an issue here when this activity is recycled after adding a new pubkey
		// TODO: should consider moving into onStart, but we dont have a good way of resetting the listpref after filling once
		ListPreference pubkeyPref = (ListPreference) findPreference(HostDatabase.FIELD_HOST_PUBKEYID);

		List<CharSequence> pubkeyNicks = new LinkedList<CharSequence>(Arrays.asList(pubkeyPref.getEntries()));
		pubkeyNicks.addAll(pubkeydb.allValues(PubkeyDatabase.FIELD_PUBKEY_NICKNAME));
		pubkeyPref.setEntries(pubkeyNicks.toArray(new CharSequence[pubkeyNicks.size()]));

		List<CharSequence> pubkeyIds = new LinkedList<CharSequence>(Arrays.asList(pubkeyPref.getEntryValues()));
		pubkeyIds.addAll(pubkeydb.allValues("_id"));
		pubkeyPref.setEntryValues(pubkeyIds.toArray(new CharSequence[pubkeyIds.size()]));

		// Populate the character set encoding list with all available
		final ListPreference charsetPref = (ListPreference) findPreference(HostDatabase.FIELD_HOST_ENCODING);

		if (CharsetHolder.isInitialized()) {
			initCharsetPref(charsetPref);
		} else {
			String[] currentCharsetPref = new String[1];
			currentCharsetPref[0] = charsetPref.getValue();
			charsetPref.setEntryValues(currentCharsetPref);
			charsetPref.setEntries(currentCharsetPref);

			new Thread(new Runnable() {
				public void run() {
					initCharsetPref(charsetPref);
				}
			}).start();
		}

		this.updateSummaries();
	}

	@Override
	public void onStart() {
		super.onStart();

		bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);

		hostdb = HostDatabase.get(this);
		pubkeydb = PubkeyDatabase.get(this);
	}

	@Override
	public void onStop() {
		super.onStop();

		unbindService(connection);

		hostdb = null;
		pubkeydb = null;
	}

	private void updateSummaries() {
		// for all text preferences, set hint as current database value
		for (String key : this.pref.values.keySet()) {
			if (key.equals(HostDatabase.FIELD_HOST_POSTLOGIN)) continue;
			Preference pref = this.findPreference(key);
			if (pref == null) continue;
			if (pref instanceof CheckBoxPreference || pref instanceof SwitchPreference) continue;
			CharSequence value = this.pref.getString(key, "");

			if (key.equals(HostDatabase.FIELD_HOST_PUBKEYID)) {
				try {
					int pubkeyId = Integer.parseInt((String) value);
					if (pubkeyId >= 0)
						pref.setSummary(pubkeydb.getNickname(pubkeyId));
					else if (pubkeyId == HostDatabase.PUBKEYID_ANY)
						pref.setSummary(R.string.list_pubkeyids_any);
					else if (pubkeyId == HostDatabase.PUBKEYID_NEVER)
						pref.setSummary(R.string.list_pubkeyids_none);
					continue;
				} catch (NumberFormatException nfe) {
					// Fall through.
				}
			} else if (pref instanceof ListPreference) {
				ListPreference listPref = (ListPreference) pref;
				int entryIndex = listPref.findIndexOfValue((String) value);
				if (entryIndex >= 0)
					value = listPref.getEntries()[entryIndex];
			}

			pref.setSummary(value);
		}

	}

	private void initCharsetPref(final ListPreference charsetPref) {
		charsetPref.setEntryValues(CharsetHolder.getCharsetIds());
		charsetPref.setEntries(CharsetHolder.getCharsetNames());
	}

	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
		// update values on changed preference
		this.updateSummaries();

		// Our CursorPreferenceHack always send null keys, so try to set charset anyway
		if (hostBridge != null)
			hostBridge.setCharset(sharedPreferences
					.getString(HostDatabase.FIELD_HOST_ENCODING, HostDatabase.ENCODING_DEFAULT));
	}

	public static class CharsetHolder {
		private static boolean initialized = false;

		private static CharSequence[] charsetIds;
		private static CharSequence[] charsetNames;

		public static CharSequence[] getCharsetNames() {
			if (charsetNames == null)
				initialize();

			return charsetNames;
		}

		public static CharSequence[] getCharsetIds() {
			if (charsetIds == null)
				initialize();

			return charsetIds;
		}

		private synchronized static void initialize() {
			if (initialized)
				return;

			List<CharSequence> charsetIdsList = new LinkedList<CharSequence>();
			List<CharSequence> charsetNamesList = new LinkedList<CharSequence>();

			for (Entry<String, Charset> entry : Charset.availableCharsets().entrySet()) {
				Charset c = entry.getValue();
				if (c.canEncode() && c.isRegistered()) {
					String key = entry.getKey();
					if (key.startsWith("cp")) {
						// Custom CP437 charset changes
						charsetIdsList.add("CP437");
						charsetNamesList.add("CP437");
					}
					charsetIdsList.add(entry.getKey());
					charsetNamesList.add(c.displayName());
				}
			}

			charsetIds = charsetIdsList.toArray(new CharSequence[charsetIdsList.size()]);
			charsetNames = charsetNamesList.toArray(new CharSequence[charsetNamesList.size()]);

			initialized = true;
		}

		public static boolean isInitialized() {
			return initialized;
		}
	}
}