/* * 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.lang.ref.WeakReference; import java.util.ArrayList; import java.util.List; import org.connectbot.bean.HostBean; import org.connectbot.bean.SelectionArea; import org.connectbot.service.BridgeDisconnectedListener; import org.connectbot.service.PromptHelper; import org.connectbot.service.TerminalBridge; import org.connectbot.service.TerminalKeyListener; import org.connectbot.service.TerminalManager; import org.connectbot.util.PreferenceConstants; import android.app.AlertDialog; import android.app.Dialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.media.AudioManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.preference.PreferenceManager; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.design.widget.TabLayout; import android.support.v4.view.MenuItemCompat; import android.support.v4.view.MotionEventCompat; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.ClipboardManager; import android.util.Log; import android.view.ContextMenu; import android.view.GestureDetector; import android.view.InputDevice; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnKeyListener; import android.view.View.OnTouchListener; import android.view.ViewConfiguration; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.HorizontalScrollView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import de.mud.terminal.vt320; public class ConsoleActivity extends AppCompatActivity implements BridgeDisconnectedListener { public final static String TAG = "CB.ConsoleActivity"; protected static final int REQUEST_EDIT = 1; private static final int CLICK_TIME = 400; private static final float MAX_CLICK_DISTANCE = 25f; private static final int KEYBOARD_DISPLAY_TIME = 3000; private static final int KEYBOARD_REPEAT_INITIAL = 500; private static final int KEYBOARD_REPEAT = 100; private static final String STATE_SELECTED_URI = "selectedUri"; protected ViewPager pager = null; protected TabLayout tabs = null; protected Toolbar toolbar = null; @Nullable protected TerminalManager bound = null; protected TerminalPagerAdapter adapter = null; protected LayoutInflater inflater = null; private SharedPreferences prefs = null; // determines whether or not menuitem accelerators are bound // otherwise they collide with an external keyboard's CTRL-char private boolean hardKeyboard = false; protected Uri requested; protected ClipboardManager clipboard; private RelativeLayout stringPromptGroup; protected EditText stringPrompt; private TextView stringPromptInstructions; private RelativeLayout booleanPromptGroup; private TextView booleanPrompt; private Button booleanYes, booleanNo; private LinearLayout keyboardGroup; private Runnable keyboardGroupHider; private TextView empty; private Animation fade_out_delayed; private Animation keyboard_fade_in, keyboard_fade_out; private float lastX, lastY; private InputMethodManager inputManager; private MenuItem disconnect, copy, paste, portForward, resize, urlscan; protected TerminalBridge copySource = null; private int lastTouchRow, lastTouchCol; private boolean forcedOrientation; private Handler handler = new Handler(); private ImageView mKeyboardButton; private ActionBar actionBar; private boolean inActionBarMenu = false; private boolean titleBarHide; private ServiceConnection connection = new ServiceConnection() { public void onServiceConnected(ComponentName className, IBinder service) { bound = ((TerminalManager.TerminalBinder) service).getService(); // let manager know about our event handling services bound.disconnectListener = ConsoleActivity.this; bound.setResizeAllowed(true); final String requestedNickname = (requested != null) ? requested.getFragment() : null; int requestedIndex = 0; TerminalBridge requestedBridge = bound.getConnectedBridge(requestedNickname); // If we didn't find the requested connection, try opening it if (requestedNickname != null && requestedBridge == null) { try { Log.d(TAG, String.format("We couldnt find an existing bridge with URI=%s (nickname=%s), so creating one now", requested.toString(), requestedNickname)); requestedBridge = bound.openConnection(requested); } catch (Exception e) { Log.e(TAG, "Problem while trying to create new requested bridge from URI", e); } } // create views for all bridges on this service adapter.notifyDataSetChanged(); requestedIndex = bound.getBridges().indexOf(requestedBridge); setDisplayedTerminal(requestedIndex == -1 ? 0 : requestedIndex); } public void onServiceDisconnected(ComponentName className) { adapter.notifyDataSetChanged(); updateEmptyVisible(); bound = null; } }; protected Handler promptHandler = new Handler() { @Override public void handleMessage(Message msg) { // someone below us requested to display a prompt updatePromptVisible(); } }; public void onDisconnected(TerminalBridge bridge) { synchronized (adapter) { adapter.notifyDataSetChanged(); Log.d(TAG, "Someone sending HANDLE_DISCONNECT to parentHandler"); if (bridge.isAwaitingClose()) { closeBridge(bridge); } } } protected OnClickListener emulatedKeysListener = new OnClickListener() { @Override public void onClick(View v) { onEmulatedKeyClicked(v); } }; protected Handler keyRepeatHandler = new Handler(); /** * Handle repeatable virtual keys and touch events */ public class KeyRepeater implements Runnable, OnTouchListener, OnClickListener { private View mView; private Handler mHandler; private boolean mDown; public KeyRepeater(Handler handler, View view) { mView = view; mHandler = handler; mView.setOnTouchListener(this); mView.setOnClickListener(this); mDown = false; } @Override public void run() { mDown = true; mHandler.removeCallbacks(this); mHandler.postDelayed(this, KEYBOARD_REPEAT); mView.performClick(); } @Override public boolean onTouch(View v, MotionEvent event) { if (BuildConfig.DEBUG) { Log.d(TAG, "KeyRepeater.onTouch(" + v.getId() + ", " + event.getAction() + ", " + event.getActionIndex() + ", " + event.getActionMasked() + ");"); } switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mDown = false; mHandler.postDelayed(this, KEYBOARD_REPEAT_INITIAL); mView.setPressed(true); return (true); case MotionEvent.ACTION_CANCEL: mHandler.removeCallbacks(this); mView.setPressed(false); return (true); case MotionEvent.ACTION_UP: mHandler.removeCallbacks(this); mView.setPressed(false); if (!mDown) { mView.performClick(); } return (true); } return false; } @Override public void onClick(View view) { onEmulatedKeyClicked(view); } } private void onEmulatedKeyClicked(View v) { TerminalView terminal = adapter.getCurrentTerminalView(); if (terminal == null) return; if (BuildConfig.DEBUG) { Log.d(TAG, "onEmulatedKeyClicked(" + v.getId() + ")"); } TerminalKeyListener handler = terminal.bridge.getKeyHandler(); boolean hideKeys = false; switch (v.getId()) { case R.id.button_ctrl: handler.metaPress(TerminalKeyListener.OUR_CTRL_ON, true); hideKeys = true; break; case R.id.button_esc: handler.sendEscape(); hideKeys = true; break; case R.id.button_tab: handler.sendTab(); hideKeys = true; break; case R.id.button_up: handler.sendPressedKey(vt320.KEY_UP); break; case R.id.button_down: handler.sendPressedKey(vt320.KEY_DOWN); break; case R.id.button_left: handler.sendPressedKey(vt320.KEY_LEFT); break; case R.id.button_right: handler.sendPressedKey(vt320.KEY_RIGHT); break; case R.id.button_home: handler.sendPressedKey(vt320.KEY_HOME); break; case R.id.button_end: handler.sendPressedKey(vt320.KEY_END); break; case R.id.button_pgup: handler.sendPressedKey(vt320.KEY_PAGE_UP); break; case R.id.button_pgdn: handler.sendPressedKey(vt320.KEY_PAGE_DOWN); break; case R.id.button_f1: handler.sendPressedKey(vt320.KEY_F1); break; case R.id.button_f2: handler.sendPressedKey(vt320.KEY_F2); break; case R.id.button_f3: handler.sendPressedKey(vt320.KEY_F3); break; case R.id.button_f4: handler.sendPressedKey(vt320.KEY_F4); break; case R.id.button_f5: handler.sendPressedKey(vt320.KEY_F5); break; case R.id.button_f6: handler.sendPressedKey(vt320.KEY_F6); break; case R.id.button_f7: handler.sendPressedKey(vt320.KEY_F7); break; case R.id.button_f8: handler.sendPressedKey(vt320.KEY_F8); break; case R.id.button_f9: handler.sendPressedKey(vt320.KEY_F9); break; case R.id.button_f10: handler.sendPressedKey(vt320.KEY_F10); break; case R.id.button_f11: handler.sendPressedKey(vt320.KEY_F11); break; case R.id.button_f12: handler.sendPressedKey(vt320.KEY_F12); break; } if (hideKeys) hideEmulatedKeys(); else autoHideEmulatedKeys(); terminal.bridge.tryKeyVibrate(); if (titleBarHide) { actionBar.hide(); } } /** * @param bridge */ private void closeBridge(final TerminalBridge bridge) { updateEmptyVisible(); updatePromptVisible(); // If we just closed the last bridge, go back to the previous activity. if (pager.getChildCount() == 0) { finish(); } } protected View findCurrentView(int id) { View view = pager.findViewWithTag(adapter.getBridgeAtPosition(pager.getCurrentItem())); if (view == null) { return null; } return view.findViewById(id); } protected PromptHelper getCurrentPromptHelper() { TerminalView view = adapter.getCurrentTerminalView(); if (view == null) return null; return view.bridge.promptHelper; } protected void hideAllPrompts() { stringPromptGroup.setVisibility(View.GONE); booleanPromptGroup.setVisibility(View.GONE); } private void showEmulatedKeys(boolean showActionBar) { keyboardGroup.startAnimation(keyboard_fade_in); keyboardGroup.setVisibility(View.VISIBLE); if (showActionBar) { actionBar.show(); } autoHideEmulatedKeys(); } private void autoHideEmulatedKeys() { if (keyboardGroupHider != null) handler.removeCallbacks(keyboardGroupHider); keyboardGroupHider = new Runnable() { public void run() { if (keyboardGroup.getVisibility() == View.GONE || inActionBarMenu) return; keyboardGroup.startAnimation(keyboard_fade_out); keyboardGroup.setVisibility(View.GONE); if (titleBarHide) { actionBar.hide(); } keyboardGroupHider = null; } }; handler.postDelayed(keyboardGroupHider, KEYBOARD_DISPLAY_TIME); } private void hideEmulatedKeys() { if (keyboardGroupHider != null) handler.removeCallbacks(keyboardGroupHider); keyboardGroup.setVisibility(View.GONE); if (titleBarHide) { actionBar.hide(); } } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { StrictModeSetup.run(); } hardKeyboard = getResources().getConfiguration().keyboard == Configuration.KEYBOARD_QWERTY; clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); prefs = PreferenceManager.getDefaultSharedPreferences(this); titleBarHide = prefs.getBoolean(PreferenceConstants.TITLEBARHIDE, false); if (titleBarHide) { supportRequestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY); } this.setContentView(R.layout.act_console); // hide status bar if requested by user if (prefs.getBoolean(PreferenceConstants.FULLSCREEN, false)) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } // TODO find proper way to disable volume key beep if it exists. setVolumeControlStream(AudioManager.STREAM_MUSIC); // handle requested console from incoming intent if (icicle == null) { requested = getIntent().getData(); } else { requested = Uri.parse(icicle.getString(STATE_SELECTED_URI)); } inflater = LayoutInflater.from(this); toolbar = (Toolbar) findViewById(R.id.toolbar); pager = (ViewPager) findViewById(R.id.console_flip); registerForContextMenu(pager); pager.addOnPageChangeListener( new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { onTerminalChanged(); } }); adapter = new TerminalPagerAdapter(); pager.setAdapter(adapter); empty = (TextView) findViewById(android.R.id.empty); stringPromptGroup = (RelativeLayout) findViewById(R.id.console_password_group); stringPromptInstructions = (TextView) findViewById(R.id.console_password_instructions); stringPrompt = (EditText) findViewById(R.id.console_password); stringPrompt.setOnKeyListener(new OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_UP) return false; if (keyCode != KeyEvent.KEYCODE_ENTER) return false; // pass collected password down to current terminal String value = stringPrompt.getText().toString(); PromptHelper helper = getCurrentPromptHelper(); if (helper == null) return false; helper.setResponse(value); // finally clear password for next user stringPrompt.setText(""); updatePromptVisible(); return true; } }); booleanPromptGroup = (RelativeLayout) findViewById(R.id.console_boolean_group); booleanPrompt = (TextView) findViewById(R.id.console_prompt); booleanYes = (Button) findViewById(R.id.console_prompt_yes); booleanYes.setOnClickListener(new OnClickListener() { public void onClick(View v) { PromptHelper helper = getCurrentPromptHelper(); if (helper == null) return; helper.setResponse(Boolean.TRUE); updatePromptVisible(); } }); booleanNo = (Button) findViewById(R.id.console_prompt_no); booleanNo.setOnClickListener(new OnClickListener() { public void onClick(View v) { PromptHelper helper = getCurrentPromptHelper(); if (helper == null) return; helper.setResponse(Boolean.FALSE); updatePromptVisible(); } }); fade_out_delayed = AnimationUtils.loadAnimation(this, R.anim.fade_out_delayed); // Preload animation for keyboard button keyboard_fade_in = AnimationUtils.loadAnimation(this, R.anim.keyboard_fade_in); keyboard_fade_out = AnimationUtils.loadAnimation(this, R.anim.keyboard_fade_out); inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); keyboardGroup = (LinearLayout) findViewById(R.id.keyboard_group); mKeyboardButton = (ImageView) findViewById(R.id.button_keyboard); mKeyboardButton.setOnClickListener(new OnClickListener() { public void onClick(View view) { View terminal = adapter.getCurrentTerminalView(); if (terminal == null) return; inputManager.showSoftInput(terminal, InputMethodManager.SHOW_FORCED); hideEmulatedKeys(); } }); findViewById(R.id.button_ctrl).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_esc).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_tab).setOnClickListener(emulatedKeysListener); new KeyRepeater(keyRepeatHandler, findViewById(R.id.button_up)); new KeyRepeater(keyRepeatHandler, findViewById(R.id.button_down)); new KeyRepeater(keyRepeatHandler, findViewById(R.id.button_left)); new KeyRepeater(keyRepeatHandler, findViewById(R.id.button_right)); findViewById(R.id.button_home).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_end).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_pgup).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_pgdn).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f1).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f2).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f3).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f4).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f5).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f6).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f7).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f8).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f9).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f10).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f11).setOnClickListener(emulatedKeysListener); findViewById(R.id.button_f12).setOnClickListener(emulatedKeysListener); actionBar = getSupportActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); if (titleBarHide) { actionBar.hide(); } actionBar.addOnMenuVisibilityListener(new ActionBar.OnMenuVisibilityListener() { public void onMenuVisibilityChanged(boolean isVisible) { inActionBarMenu = isVisible; if (isVisible == false) { hideEmulatedKeys(); } } }); final HorizontalScrollView keyboardScroll = (HorizontalScrollView) findViewById(R.id.keyboard_hscroll); if (!hardKeyboard) { // Show virtual keyboard and scroll back and forth showEmulatedKeys(false); keyboardScroll.postDelayed(new Runnable() { @Override public void run() { final int xscroll = findViewById(R.id.button_f12).getRight(); if (BuildConfig.DEBUG) { Log.d(TAG, "smoothScrollBy(toEnd[" + xscroll + "])"); } keyboardScroll.smoothScrollBy(xscroll, 0); keyboardScroll.postDelayed(new Runnable() { @Override public void run() { if (BuildConfig.DEBUG) { Log.d(TAG, "smoothScrollBy(toStart[" + (-xscroll) + "])"); } keyboardScroll.smoothScrollBy(-xscroll, 0); } }, 500); } }, 500); } // Reset keyboard auto-hide timer when scrolling keyboardScroll.setOnTouchListener( new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_MOVE: autoHideEmulatedKeys(); break; case MotionEvent.ACTION_UP: v.performClick(); return (true); } return (false); } }); tabs = (TabLayout) findViewById(R.id.tabs); if (tabs != null) setupTabLayoutWithViewPager(); // detect fling gestures to switch between terminals final GestureDetector detect = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() { private float totalY = 0; @Override public void onLongPress(MotionEvent e) { super.onLongPress(e); openContextMenu(pager); } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { // if copying, then ignore if (copySource != null && copySource.isSelectingForCopy()) return false; if (e1 == null || e2 == null) return false; // if releasing then reset total scroll if (e2.getAction() == MotionEvent.ACTION_UP) { totalY = 0; } // activate consider if within x tolerance int touchSlop = ViewConfiguration.get(ConsoleActivity.this).getScaledTouchSlop(); if (Math.abs(e1.getX() - e2.getX()) < touchSlop * 4) { View view = adapter.getCurrentTerminalView(); if (view == null) return false; TerminalView terminal = (TerminalView) view; // estimate how many rows we have scrolled through // accumulate distance that doesn't trigger immediate scroll totalY += distanceY; final int moved = (int) (totalY / terminal.bridge.charHeight); // consume as scrollback only if towards right half of screen if (e2.getX() > view.getWidth() / 2) { if (moved != 0) { int base = terminal.bridge.buffer.getWindowBase(); terminal.bridge.buffer.setWindowBase(base + moved); totalY = 0; return true; } } else { // otherwise consume as pgup/pgdown for every 5 lines if (moved > 5) { ((vt320) terminal.bridge.buffer).keyPressed(vt320.KEY_PAGE_DOWN, ' ', 0); terminal.bridge.tryKeyVibrate(); totalY = 0; return true; } else if (moved < -5) { ((vt320) terminal.bridge.buffer).keyPressed(vt320.KEY_PAGE_UP, ' ', 0); terminal.bridge.tryKeyVibrate(); totalY = 0; return true; } } } return false; } }); pager.setLongClickable(true); pager.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { // Handle mouse-specific actions. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH && MotionEventCompat.getSource(event) == InputDevice.SOURCE_MOUSE && event.getAction() == MotionEvent.ACTION_DOWN) { switch (event.getButtonState()) { case MotionEvent.BUTTON_PRIMARY: // Automatically start copy mode if using a mouse. startCopyMode(); break; case MotionEvent.BUTTON_SECONDARY: openContextMenu(pager); return true; case MotionEvent.BUTTON_TERTIARY: // Middle click pastes. pasteIntoTerminal(); return true; } } // when copying, highlight the area if (copySource != null && copySource.isSelectingForCopy()) { int row = (int) Math.floor(event.getY() / copySource.charHeight); int col = (int) Math.floor(event.getX() / copySource.charWidth); SelectionArea area = copySource.getSelectionArea(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // recording starting area if (area.isSelectingOrigin()) { area.setRow(row); area.setColumn(col); lastTouchRow = row; lastTouchCol = col; copySource.redraw(); } return true; case MotionEvent.ACTION_MOVE: /* ignore when user hasn't moved since last time so * we can fine-tune with directional pad */ if (row == lastTouchRow && col == lastTouchCol) return true; // if the user moves, start the selection for other corner area.finishSelectingOrigin(); // update selected area area.setRow(row); area.setColumn(col); lastTouchRow = row; lastTouchCol = col; copySource.redraw(); return true; case MotionEvent.ACTION_UP: /* If they didn't move their finger, maybe they meant to * select the rest of the text with the directional pad. */ if (area.getLeft() == area.getRight() && area.getTop() == area.getBottom()) { return true; } // copy selected area to clipboard String copiedText = area.copyFrom(copySource.buffer); clipboard.setText(copiedText); Toast.makeText(ConsoleActivity.this, getString(R.string.console_copy_done, copiedText.length()), Toast.LENGTH_LONG).show(); // fall through to clear state case MotionEvent.ACTION_CANCEL: // make sure we clear any highlighted area area.reset(); copySource.setSelectingForCopy(false); copySource.redraw(); return true; } } if (event.getAction() == MotionEvent.ACTION_DOWN) { lastX = event.getX(); lastY = event.getY(); } else if (event.getAction() == MotionEvent.ACTION_UP && keyboardGroup.getVisibility() == View.GONE && event.getEventTime() - event.getDownTime() < CLICK_TIME && Math.abs(event.getX() - lastX) < MAX_CLICK_DISTANCE && Math.abs(event.getY() - lastY) < MAX_CLICK_DISTANCE) { showEmulatedKeys(true); } // pass any touch events back to detector return detect.onTouchEvent(event); } }); } /** * Ties the {@link TabLayout} to the {@link ViewPager}. * *
This method will: *