comparison src/com/five_ten_sg/connectbot/HostListActivity.java @ 0:0ce5cc452d02

initial version
author Carl Byington <carl@five-ten-sg.com>
date Thu, 22 May 2014 10:41:19 -0700
parents
children 75d86b7fd3f0
comparison
equal deleted inserted replaced
-1:000000000000 0:0ce5cc452d02
1 /*
2 * ConnectBot: simple, powerful, open-source SSH client for Android
3 * Copyright 2007 Kenny Root, Jeffrey Sharkey
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 package com.five_ten_sg.connectbot;
19
20 import java.util.List;
21
22 import com.five_ten_sg.connectbot.bean.HostBean;
23 import com.five_ten_sg.connectbot.service.TerminalBridge;
24 import com.five_ten_sg.connectbot.service.TerminalManager;
25 import com.five_ten_sg.connectbot.transport.TransportFactory;
26 import com.five_ten_sg.connectbot.util.HostDatabase;
27 import com.five_ten_sg.connectbot.util.PreferenceConstants;
28 import android.app.Activity;
29 import android.app.AlertDialog;
30 import android.app.ListActivity;
31 import android.content.ComponentName;
32 import android.content.Context;
33 import android.content.DialogInterface;
34 import android.content.Intent;
35 import android.content.Intent.ShortcutIconResource;
36 import android.content.ServiceConnection;
37 import android.content.SharedPreferences;
38 import android.content.SharedPreferences.Editor;
39 import android.content.res.ColorStateList;
40 import android.net.Uri;
41 import android.os.Build;
42 import android.os.Bundle;
43 import android.os.Handler;
44 import android.os.IBinder;
45 import android.os.Message;
46 import android.preference.PreferenceManager;
47 import android.util.Log;
48 import android.view.ContextMenu;
49 import android.view.KeyEvent;
50 import android.view.LayoutInflater;
51 import android.view.Menu;
52 import android.view.MenuItem;
53 import android.view.MenuItem.OnMenuItemClickListener;
54 import android.view.View;
55 import android.view.View.OnKeyListener;
56 import android.view.ViewGroup;
57 import android.widget.AdapterView;
58 import android.widget.AdapterView.OnItemClickListener;
59 import android.widget.ArrayAdapter;
60 import android.widget.ImageView;
61 import android.widget.ListView;
62 import android.widget.Spinner;
63 import android.widget.TextView;
64
65 public class HostListActivity extends ListActivity {
66 public final static int REQUEST_EDIT = 1;
67
68 public final static int REQUEST_EULA = 2;
69
70 protected TerminalManager bound = null;
71
72 protected HostDatabase hostdb;
73 private List<HostBean> hosts;
74 protected LayoutInflater inflater = null;
75
76 protected boolean sortedByColor = false;
77
78 private MenuItem sortcolor;
79
80 private MenuItem sortlast;
81
82 private Spinner transportSpinner;
83 private TextView quickconnect;
84
85 private SharedPreferences prefs = null;
86
87 protected boolean makingShortcut = false;
88
89 protected Handler updateHandler = new Handler() {
90 @Override
91 public void handleMessage(Message msg) {
92 HostListActivity.this.updateList();
93 }
94 };
95
96 private ServiceConnection connection = new ServiceConnection() {
97 public void onServiceConnected(ComponentName className, IBinder service) {
98 bound = ((TerminalManager.TerminalBinder) service).getService();
99 // update our listview binder to find the service
100 HostListActivity.this.updateList();
101 }
102 public void onServiceDisconnected(ComponentName className) {
103 bound = null;
104 HostListActivity.this.updateList();
105 }
106 };
107
108 @Override
109 public void onStart() {
110 super.onStart();
111 // start the terminal manager service
112 this.bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
113
114 if (this.hostdb == null)
115 this.hostdb = new HostDatabase(this);
116 }
117
118 @Override
119 public void onStop() {
120 super.onStop();
121 this.unbindService(connection);
122
123 if (this.hostdb != null) {
124 this.hostdb.close();
125 this.hostdb = null;
126 }
127 }
128
129 @Override
130 public void onResume() {
131 super.onResume();
132 }
133
134 @Override
135 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
136 if (requestCode == REQUEST_EULA) {
137 if (resultCode == Activity.RESULT_OK) {
138 // yay they agreed, so store that info
139 Editor edit = prefs.edit();
140 edit.putBoolean(PreferenceConstants.EULA, true);
141 edit.commit();
142 }
143 else {
144 // user didnt agree, so close
145 this.finish();
146 }
147 }
148 else if (requestCode == REQUEST_EDIT) {
149 this.updateList();
150 }
151 }
152
153 @Override
154 public void onCreate(Bundle icicle) {
155 super.onCreate(icicle);
156 setContentView(R.layout.act_hostlist);
157 this.setTitle(String.format("%s: %s",
158 getResources().getText(R.string.app_name),
159 getResources().getText(R.string.title_hosts_list)));
160 this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
161
162 // detect HTC Dream and apply special preferences
163 if (Build.MANUFACTURER.equals("HTC") && Build.DEVICE.equals("dream")) {
164 if (!prefs.contains(PreferenceConstants.SHIFT_FKEYS) &&
165 !prefs.contains(PreferenceConstants.CTRL_FKEYS)) {
166 SharedPreferences.Editor editor = prefs.edit();
167 editor.putBoolean(PreferenceConstants.SHIFT_FKEYS, true);
168 editor.putBoolean(PreferenceConstants.CTRL_FKEYS, true);
169 editor.commit();
170 }
171 }
172
173 // check for eula agreement
174 boolean agreed = prefs.getBoolean(PreferenceConstants.EULA, false);
175
176 if (!agreed) {
177 this.startActivityForResult(new Intent(this, WizardActivity.class), REQUEST_EULA);
178 }
179
180 this.makingShortcut = Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction())
181 || Intent.ACTION_PICK.equals(getIntent().getAction());
182 // connect with hosts database and populate list
183 this.hostdb = new HostDatabase(this);
184 ListView list = this.getListView();
185 this.sortedByColor = prefs.getBoolean(PreferenceConstants.SORT_BY_COLOR, false);
186 //this.list.setSelector(R.drawable.highlight_disabled_pressed);
187 list.setOnItemClickListener(new OnItemClickListener() {
188
189 public synchronized void onItemClick(AdapterView<?> parent, View view, int position, long id) {
190 // launch off to console details
191 HostBean host = (HostBean) parent.getAdapter().getItem(position);
192 Uri uri = host.getUri();
193 Intent contents = new Intent(Intent.ACTION_VIEW, uri);
194 contents.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
195
196 if (makingShortcut) {
197 // create shortcut if requested
198 ShortcutIconResource icon = Intent.ShortcutIconResource.fromContext(HostListActivity.this, R.drawable.icon);
199 Intent intent = new Intent();
200 intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, contents);
201 intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, host.getNickname());
202 intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
203 setResult(RESULT_OK, intent);
204 finish();
205 }
206 else {
207 // otherwise just launch activity to show this host
208 HostListActivity.this.startActivity(contents);
209 }
210 }
211 });
212 this.registerForContextMenu(list);
213 quickconnect = (TextView) this.findViewById(R.id.front_quickconnect);
214 quickconnect.setVisibility(makingShortcut ? View.GONE : View.VISIBLE);
215 quickconnect.setOnKeyListener(new OnKeyListener() {
216 public boolean onKey(View v, int keyCode, KeyEvent event) {
217 if (event.getAction() == KeyEvent.ACTION_UP) return false;
218
219 if (keyCode != KeyEvent.KEYCODE_ENTER) return false;
220
221 return startConsoleActivity();
222 }
223 });
224 transportSpinner = (Spinner)findViewById(R.id.transport_selection);
225 transportSpinner.setVisibility(makingShortcut ? View.GONE : View.VISIBLE);
226 ArrayAdapter<String> transportSelection = new ArrayAdapter<String> (this,
227 android.R.layout.simple_spinner_item, TransportFactory.getTransportNames());
228 transportSelection.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
229 transportSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
230 public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
231 String formatHint = TransportFactory.getFormatHint(
232 (String) transportSpinner.getSelectedItem(),
233 HostListActivity.this);
234 quickconnect.setHint(formatHint);
235 quickconnect.setError(null);
236 quickconnect.requestFocus();
237 }
238 public void onNothingSelected(AdapterView<?> arg0) { }
239 });
240 transportSpinner.setAdapter(transportSelection);
241 this.inflater = LayoutInflater.from(this);
242 }
243
244 @Override
245 public boolean onPrepareOptionsMenu(Menu menu) {
246 super.onPrepareOptionsMenu(menu);
247
248 // don't offer menus when creating shortcut
249 if (makingShortcut) return true;
250
251 sortcolor.setVisible(!sortedByColor);
252 sortlast.setVisible(sortedByColor);
253 return true;
254 }
255
256 @Override
257 public boolean onCreateOptionsMenu(Menu menu) {
258 super.onCreateOptionsMenu(menu);
259
260 // don't offer menus when creating shortcut
261 if (makingShortcut) return true;
262
263 // add host, ssh keys, about
264 sortcolor = menu.add(R.string.list_menu_sortcolor);
265 sortcolor.setIcon(android.R.drawable.ic_menu_share);
266 sortcolor.setOnMenuItemClickListener(new OnMenuItemClickListener() {
267 public boolean onMenuItemClick(MenuItem item) {
268 sortedByColor = true;
269 updateList();
270 return true;
271 }
272 });
273 sortlast = menu.add(R.string.list_menu_sortname);
274 sortlast.setIcon(android.R.drawable.ic_menu_share);
275 sortlast.setOnMenuItemClickListener(new OnMenuItemClickListener() {
276 public boolean onMenuItemClick(MenuItem item) {
277 sortedByColor = false;
278 updateList();
279 return true;
280 }
281 });
282 MenuItem keys = menu.add(R.string.list_menu_pubkeys);
283 keys.setIcon(android.R.drawable.ic_lock_lock);
284 keys.setIntent(new Intent(HostListActivity.this, PubkeyListActivity.class));
285 MenuItem colors = menu.add(R.string.title_colors);
286 colors.setIcon(android.R.drawable.ic_menu_slideshow);
287 colors.setIntent(new Intent(HostListActivity.this, ColorsActivity.class));
288 MenuItem settings = menu.add(R.string.list_menu_settings);
289 settings.setIcon(android.R.drawable.ic_menu_preferences);
290 settings.setIntent(new Intent(HostListActivity.this, SettingsActivity.class));
291 MenuItem help = menu.add(R.string.title_help);
292 help.setIcon(android.R.drawable.ic_menu_help);
293 help.setIntent(new Intent(HostListActivity.this, HelpActivity.class));
294 return true;
295 }
296
297
298 @Override
299 public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
300 // create menu to handle hosts
301 // create menu to handle deleting and sharing lists
302 AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
303 final HostBean host = (HostBean) this.getListView().getItemAtPosition(info.position);
304 menu.setHeaderTitle(host.getNickname());
305 // edit, disconnect, delete
306 MenuItem connect = menu.add(R.string.list_host_disconnect);
307 final TerminalBridge bridge = bound.getConnectedBridge(host);
308 connect.setEnabled((bridge != null));
309 connect.setOnMenuItemClickListener(new OnMenuItemClickListener() {
310 public boolean onMenuItemClick(MenuItem item) {
311 bridge.dispatchDisconnect(true);
312 updateHandler.sendEmptyMessage(-1);
313 return true;
314 }
315 });
316 MenuItem edit = menu.add(R.string.list_host_edit);
317 edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {
318 public boolean onMenuItemClick(MenuItem item) {
319 Intent intent = new Intent(HostListActivity.this, HostEditorActivity.class);
320 intent.putExtra(Intent.EXTRA_TITLE, host.getId());
321 HostListActivity.this.startActivityForResult(intent, REQUEST_EDIT);
322 return true;
323 }
324 });
325 MenuItem portForwards = menu.add(R.string.list_host_portforwards);
326 portForwards.setOnMenuItemClickListener(new OnMenuItemClickListener() {
327 public boolean onMenuItemClick(MenuItem item) {
328 Intent intent = new Intent(HostListActivity.this, PortForwardListActivity.class);
329 intent.putExtra(Intent.EXTRA_TITLE, host.getId());
330 HostListActivity.this.startActivityForResult(intent, REQUEST_EDIT);
331 return true;
332 }
333 });
334
335 if (!TransportFactory.canForwardPorts(host.getProtocol()))
336 portForwards.setEnabled(false);
337
338 MenuItem delete = menu.add(R.string.list_host_delete);
339 delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
340 public boolean onMenuItemClick(MenuItem item) {
341 // prompt user to make sure they really want this
342 new AlertDialog.Builder(HostListActivity.this)
343 .setMessage(getString(R.string.delete_message, host.getNickname()))
344 .setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {
345 public void onClick(DialogInterface dialog, int which) {
346 // make sure we disconnect
347 if (bridge != null)
348 bridge.dispatchDisconnect(true);
349
350 hostdb.deleteHost(host);
351 updateHandler.sendEmptyMessage(-1);
352 }
353 })
354 .setNegativeButton(R.string.delete_neg, null).create().show();
355 return true;
356 }
357 });
358 }
359
360 /**
361 * @param text
362 * @return
363 */
364 private boolean startConsoleActivity() {
365 Uri uri = TransportFactory.getUri((String) transportSpinner
366 .getSelectedItem(), quickconnect.getText().toString());
367
368 if (uri == null) {
369 quickconnect.setError(getString(R.string.list_format_error,
370 TransportFactory.getFormatHint(
371 (String) transportSpinner.getSelectedItem(),
372 HostListActivity.this)));
373 return false;
374 }
375
376 HostBean host = TransportFactory.findHost(hostdb, uri);
377
378 if (host == null) {
379 host = TransportFactory.getTransport(uri.getScheme()).createHost(uri);
380 host.setColor(HostDatabase.COLOR_GRAY);
381 host.setPubkeyId(HostDatabase.PUBKEYID_ANY);
382 hostdb.saveHost(host);
383 }
384
385 Intent intent = new Intent(HostListActivity.this, ConsoleActivity.class);
386 intent.setData(uri);
387 startActivity(intent);
388 return true;
389 }
390
391 protected void updateList() {
392 if (prefs.getBoolean(PreferenceConstants.SORT_BY_COLOR, false) != sortedByColor) {
393 Editor edit = prefs.edit();
394 edit.putBoolean(PreferenceConstants.SORT_BY_COLOR, sortedByColor);
395 edit.commit();
396 }
397
398 if (hostdb == null)
399 hostdb = new HostDatabase(this);
400
401 hosts = hostdb.getHosts(sortedByColor);
402
403 // Don't lose hosts that are connected via shortcuts but not in the database.
404 if (bound != null) {
405 for (TerminalBridge bridge : bound.bridges) {
406 if (!hosts.contains(bridge.host))
407 hosts.add(0, bridge.host);
408 }
409 }
410
411 HostAdapter adapter = new HostAdapter(this, hosts, bound);
412 this.setListAdapter(adapter);
413 }
414
415 class HostAdapter extends ArrayAdapter<HostBean> {
416 private List<HostBean> hosts;
417 private final TerminalManager manager;
418 private final ColorStateList red, green, blue;
419
420 public final static int STATE_UNKNOWN = 1, STATE_CONNECTED = 2, STATE_DISCONNECTED = 3;
421
422 class ViewHolder {
423 public TextView nickname;
424 public TextView caption;
425 public ImageView icon;
426 }
427
428 public HostAdapter(Context context, List<HostBean> hosts, TerminalManager manager) {
429 super(context, R.layout.item_host, hosts);
430 this.hosts = hosts;
431 this.manager = manager;
432 red = context.getResources().getColorStateList(R.color.red);
433 green = context.getResources().getColorStateList(R.color.green);
434 blue = context.getResources().getColorStateList(R.color.blue);
435 }
436
437 /**
438 * Check if we're connected to a terminal with the given host.
439 */
440 private int getConnectedState(HostBean host) {
441 // always disconnected if we dont have backend service
442 if (this.manager == null)
443 return STATE_UNKNOWN;
444
445 if (manager.getConnectedBridge(host) != null)
446 return STATE_CONNECTED;
447
448 if (manager.disconnected.contains(host))
449 return STATE_DISCONNECTED;
450
451 return STATE_UNKNOWN;
452 }
453
454 @Override
455 public View getView(int position, View convertView, ViewGroup parent) {
456 ViewHolder holder;
457
458 if (convertView == null) {
459 convertView = inflater.inflate(R.layout.item_host, null, false);
460 holder = new ViewHolder();
461 holder.nickname = (TextView)convertView.findViewById(android.R.id.text1);
462 holder.caption = (TextView)convertView.findViewById(android.R.id.text2);
463 holder.icon = (ImageView)convertView.findViewById(android.R.id.icon);
464 convertView.setTag(holder);
465 }
466 else
467 holder = (ViewHolder) convertView.getTag();
468
469 HostBean host = hosts.get(position);
470
471 if (host == null) {
472 // Well, something bad happened. We can't continue.
473 Log.e("HostAdapter", "Host bean is null!");
474 holder.nickname.setText("Error during lookup");
475 holder.caption.setText("see 'adb logcat' for more");
476 return convertView;
477 }
478
479 holder.nickname.setText(host.getNickname());
480
481 switch (this.getConnectedState(host)) {
482 case STATE_UNKNOWN:
483 holder.icon.setImageState(new int[] { }, true);
484 break;
485
486 case STATE_CONNECTED:
487 holder.icon.setImageState(new int[] { android.R.attr.state_checked }, true);
488 break;
489
490 case STATE_DISCONNECTED:
491 holder.icon.setImageState(new int[] { android.R.attr.state_expanded }, true);
492 break;
493 }
494
495 ColorStateList chosen = null;
496
497 if (HostDatabase.COLOR_RED.equals(host.getColor()))
498 chosen = this.red;
499 else if (HostDatabase.COLOR_GREEN.equals(host.getColor()))
500 chosen = this.green;
501 else if (HostDatabase.COLOR_BLUE.equals(host.getColor()))
502 chosen = this.blue;
503
504 Context context = convertView.getContext();
505
506 if (chosen != null) {
507 // set color normally if not selected
508 holder.nickname.setTextColor(chosen);
509 holder.caption.setTextColor(chosen);
510 }
511 else {
512 // selected, so revert back to default black text
513 holder.nickname.setTextAppearance(context, android.R.attr.textAppearanceLarge);
514 holder.caption.setTextAppearance(context, android.R.attr.textAppearanceSmall);
515 }
516
517 long now = System.currentTimeMillis() / 1000;
518 String nice = context.getString(R.string.bind_never);
519
520 if (host.getLastConnect() > 0) {
521 int minutes = (int)((now - host.getLastConnect()) / 60);
522
523 if (minutes >= 60) {
524 int hours = (minutes / 60);
525
526 if (hours >= 24) {
527 int days = (hours / 24);
528 nice = context.getString(R.string.bind_days, days);
529 }
530 else
531 nice = context.getString(R.string.bind_hours, hours);
532 }
533 else
534 nice = context.getString(R.string.bind_minutes, minutes);
535 }
536
537 holder.caption.setText(nice);
538 return convertView;
539 }
540 }
541 }