code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
package com.ch_linghu.fanfoudroid.ui.module;
import android.app.Activity;
import android.view.MotionEvent;
import com.ch_linghu.fanfoudroid.BrowseActivity;
import com.ch_linghu.fanfoudroid.MentionActivity;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterActivity;
/**
* MyActivityFlipper 利用左右滑动手势切换Activity
*
* 1. 切换Activity, 继承与 {@link ActivityFlipper} 2. 手势识别, 实现接口
* {@link Widget.OnGestureListener}
*
*/
public class MyActivityFlipper extends ActivityFlipper implements
Widget.OnGestureListener {
public MyActivityFlipper() {
super();
}
public MyActivityFlipper(Activity activity) {
super(activity);
// TODO Auto-generated constructor stub
}
// factory
public static MyActivityFlipper create(Activity activity) {
MyActivityFlipper flipper = new MyActivityFlipper(activity);
flipper.addActivity(BrowseActivity.class);
flipper.addActivity(TwitterActivity.class);
flipper.addActivity(MentionActivity.class);
flipper.setToastResource(new int[] { R.drawable.point_left,
R.drawable.point_center, R.drawable.point_right });
flipper.setInAnimation(R.anim.push_left_in);
flipper.setOutAnimation(R.anim.push_left_out);
flipper.setPreviousInAnimation(R.anim.push_right_in);
flipper.setPreviousOutAnimation(R.anim.push_right_out);
return flipper;
}
@Override
public boolean onFlingDown(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return false; // do nothing
}
@Override
public boolean onFlingUp(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return false; // do nothing
}
@Override
public boolean onFlingLeft(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
autoShowNext();
return true;
}
@Override
public boolean onFlingRight(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
autoShowPrevious();
return true;
}
}
| Java |
/**
*
*/
package com.ch_linghu.fanfoudroid.ui.module;
import java.text.ParseException;
import java.util.Date;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.app.SimpleImageLoader;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class TweetCursorAdapter extends CursorAdapter implements TweetAdapter {
private static final String TAG = "TweetCursorAdapter";
private Context mContext;
public TweetCursorAdapter(Context context, Cursor cursor) {
super(context, cursor);
mContext = context;
if (context != null) {
mInflater = LayoutInflater.from(context);
}
if (cursor != null) {
//TODO: 可使用:
//Tweet tweet = StatusTable.parseCursor(cursor);
mUserTextColumn = cursor
.getColumnIndexOrThrow(StatusTable.USER_SCREEN_NAME);
mTextColumn = cursor.getColumnIndexOrThrow(StatusTable.TEXT);
mProfileImageUrlColumn = cursor
.getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL);
mCreatedAtColumn = cursor
.getColumnIndexOrThrow(StatusTable.CREATED_AT);
mSourceColumn = cursor.getColumnIndexOrThrow(StatusTable.SOURCE);
mInReplyToScreenName = cursor
.getColumnIndexOrThrow(StatusTable.IN_REPLY_TO_SCREEN_NAME);
mFavorited = cursor.getColumnIndexOrThrow(StatusTable.FAVORITED);
mThumbnailPic = cursor.getColumnIndexOrThrow(StatusTable.PIC_THUMB);
mMiddlePic = cursor.getColumnIndexOrThrow(StatusTable.PIC_MID);
mOriginalPic = cursor.getColumnIndexOrThrow(StatusTable.PIC_ORIG);
}
mMetaBuilder = new StringBuilder();
}
private LayoutInflater mInflater;
private int mUserTextColumn;
private int mTextColumn;
private int mProfileImageUrlColumn;
private int mCreatedAtColumn;
private int mSourceColumn;
private int mInReplyToScreenName;
private int mFavorited;
private int mThumbnailPic;
private int mMiddlePic;
private int mOriginalPic;
private StringBuilder mMetaBuilder;
/*
private ProfileImageCacheCallback callback = new ProfileImageCacheCallback(){
@Override
public void refresh(String url, Bitmap bitmap) {
TweetCursorAdapter.this.refresh();
}
};
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(R.layout.tweet, parent, false);
TweetCursorAdapter.ViewHolder holder = new ViewHolder();
holder.tweetUserText = (TextView) view
.findViewById(R.id.tweet_user_text);
holder.tweetText = (TextView) view.findViewById(R.id.tweet_text);
holder.profileImage = (ImageView) view.findViewById(R.id.profile_image);
holder.metaText = (TextView) view.findViewById(R.id.tweet_meta_text);
holder.fav = (ImageView) view.findViewById(R.id.tweet_fav);
holder.has_image = (ImageView) view.findViewById(R.id.tweet_has_image);
view.setTag(holder);
return view;
}
private static class ViewHolder {
public TextView tweetUserText;
public TextView tweetText;
public ImageView profileImage;
public TextView metaText;
public ImageView fav;
public ImageView has_image;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TweetCursorAdapter.ViewHolder holder = (TweetCursorAdapter.ViewHolder) view
.getTag();
SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);;
boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true);
holder.tweetUserText.setText(cursor.getString(mUserTextColumn));
TextHelper.setSimpleTweetText(holder.tweetText, cursor.getString(mTextColumn));
String profileImageUrl = cursor.getString(mProfileImageUrlColumn);
if (useProfileImage && !TextUtils.isEmpty(profileImageUrl)) {
SimpleImageLoader.display(holder.profileImage, profileImageUrl);
} else {
holder.profileImage.setVisibility(View.GONE);
}
if (cursor.getString(mFavorited).equals("true")) {
holder.fav.setVisibility(View.VISIBLE);
} else {
holder.fav.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(cursor.getString(mThumbnailPic))) {
holder.has_image.setVisibility(View.VISIBLE);
} else {
holder.has_image.setVisibility(View.GONE);
}
try {
Date createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor
.getString(mCreatedAtColumn));
holder.metaText.setText(Tweet.buildMetaText(mMetaBuilder,
createdAt, cursor.getString(mSourceColumn), cursor
.getString(mInReplyToScreenName)));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
}
@Override
public void refresh() {
getCursor().requery();
}
} | Java |
package com.ch_linghu.fanfoudroid.ui.module;
public interface Feedback {
public boolean isAvailable();
public void start(CharSequence text);
public void cancel(CharSequence text);
public void success(CharSequence text);
public void failed(CharSequence text);
public void update(Object arg0);
public void setIndeterminate (boolean indeterminate);
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.fanfou.Weibo;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
//TODO:
/*
* 用于用户的Adapter
*/
public class UserArrayAdapter extends BaseAdapter implements TweetAdapter{
private static final String TAG = "UserArrayAdapter";
private static final String USER_ID="userId";
protected ArrayList<User> mUsers;
private Context mContext;
protected LayoutInflater mInflater;
public UserArrayAdapter(Context context) {
mUsers = new ArrayList<User>();
mContext = context;
mInflater = LayoutInflater.from(mContext);
}
@Override
public int getCount() {
return mUsers.size();
}
@Override
public Object getItem(int position) {
return mUsers.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
private static class ViewHolder {
public ImageView profileImage;
public TextView screenName;
public TextView userId;
public TextView lastStatus;
public TextView followBtn;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);
boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true);
if (convertView == null) {
view = mInflater.inflate(R.layout.follower_item, parent, false);
ViewHolder holder = new ViewHolder();
holder.profileImage = (ImageView) view.findViewById(R.id.profile_image);
holder.screenName = (TextView) view.findViewById(R.id.screen_name);
holder.userId = (TextView) view.findViewById(R.id.user_id);
//holder.lastStatus = (TextView) view.findViewById(R.id.last_status);
holder.followBtn = (TextView) view.findViewById(R.id.follow_btn);
view.setTag(holder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
final User user = mUsers.get(position);
String profileImageUrl = user.profileImageUrl;
if (useProfileImage){
if (!TextUtils.isEmpty(profileImageUrl)) {
holder.profileImage.setImageBitmap(TwitterApplication.mImageLoader
.get(profileImageUrl, callback));
}
}else{
holder.profileImage.setVisibility(View.GONE);
}
//holder.profileImage.setImageBitmap(ImageManager.mDefaultBitmap);
holder.screenName.setText(user.screenName);
holder.userId.setText(user.id);
//holder.lastStatus.setText(user.lastStatus);
holder.followBtn.setText(user.isFollowing ? mContext
.getString(R.string.general_del_friend) : mContext
.getString(R.string.general_add_friend));
holder.followBtn.setOnClickListener(user.isFollowing?new OnClickListener(){
@Override
public void onClick(View v) {
//Toast.makeText(mContext, user.name+"following", Toast.LENGTH_SHORT).show();
delFriend(user.id);
}}:new OnClickListener(){
@Override
public void onClick(View v) {
//Toast.makeText(mContext, user.name+"not following", Toast.LENGTH_SHORT).show();
addFriend(user.id);
}});
return view;
}
public void refresh(ArrayList<User> users) {
mUsers = users;
notifyDataSetChanged();
}
@Override
public void refresh() {
notifyDataSetChanged();
}
private ImageLoaderCallback callback = new ImageLoaderCallback(){
@Override
public void refresh(String url, Bitmap bitmap) {
UserArrayAdapter.this.refresh();
}
};
/**
* 取消关注
* @param id
*/
private void delFriend(final String id) {
Builder diaBuilder = new AlertDialog.Builder(mContext)
.setTitle("关注提示").setMessage("确实要取消关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (cancelFollowingTask != null
&& cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
cancelFollowingTask = new CancelFollowingTask();
cancelFollowingTask
.setListener(cancelFollowingTaskLinstener);
TaskParams params = new TaskParams();
params.put(USER_ID, id);
cancelFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
private GenericTask cancelFollowingTask;
/**
* 取消关注
*
* @author Dino
*
*/
private class CancelFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
//TODO:userid
String userId=params[0].getString(USER_ID);
getApi().destroyFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
// followingBtn.setText("添加关注");
// isFollowingText.setText(getResources().getString(
// R.string.profile_notfollowing));
// followingBtn.setOnClickListener(setfollowingListener);
Toast.makeText(mContext, "取消关注成功", Toast.LENGTH_SHORT).show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(mContext, "取消关注失败", Toast.LENGTH_SHORT).show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
private GenericTask setFollowingTask;
/**
* 设置关注
* @param id
*/
private void addFriend(String id){
Builder diaBuilder = new AlertDialog.Builder(mContext)
.setTitle("关注提示").setMessage("确实要添加关注吗?");
diaBuilder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (setFollowingTask != null
&& setFollowingTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
setFollowingTask = new SetFollowingTask();
setFollowingTask
.setListener(setFollowingTaskLinstener);
TaskParams params = new TaskParams();
setFollowingTask.execute(params);
}
}
});
diaBuilder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
Dialog dialog = diaBuilder.create();
dialog.show();
}
/**
* 设置关注
*
* @author Dino
*
*/
private class SetFollowingTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
String userId=params[0].getString(USER_ID);
getApi().createFriendship(userId);
} catch (HttpException e) {
Log.w(TAG, "create friend ship error");
return TaskResult.FAILED;
}
return TaskResult.OK;
}
}
private TaskListener setFollowingTaskLinstener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
// followingBtn.setText("取消关注");
// isFollowingText.setText(getResources().getString(
// R.string.profile_isfollowing));
// followingBtn.setOnClickListener(cancelFollowingListener);
Toast.makeText(mContext, "关注成功", Toast.LENGTH_SHORT).show();
} else if (result == TaskResult.FAILED) {
Toast.makeText(mContext, "关注失败", Toast.LENGTH_SHORT).show();
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return null;
}
};
public Weibo getApi() {
return TwitterApplication.mApi;
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import android.graphics.Color;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.TextView;
public class TweetEdit {
private EditText mEditText;
private TextView mCharsRemainText;
private int originTextColor;
public TweetEdit(EditText editText, TextView charsRemainText) {
mEditText = editText;
mCharsRemainText = charsRemainText;
originTextColor = mCharsRemainText.getTextColors().getDefaultColor();
mEditText.addTextChangedListener(mTextWatcher);
mEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
MAX_TWEET_INPUT_LENGTH) });
}
private static final int MAX_TWEET_LENGTH = 140;
private static final int MAX_TWEET_INPUT_LENGTH = 400;
public void setTextAndFocus(String text, boolean start) {
setText(text);
Editable editable = mEditText.getText();
if (!start){
Selection.setSelection(editable, editable.length());
}else{
Selection.setSelection(editable, 0);
}
mEditText.requestFocus();
}
public void setText(String text) {
mEditText.setText(text);
updateCharsRemain();
}
private TextWatcher mTextWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable e) {
updateCharsRemain();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
};
public void updateCharsRemain() {
int remaining = MAX_TWEET_LENGTH - mEditText.length();
if (remaining < 0 ) {
mCharsRemainText.setTextColor(Color.RED);
} else {
mCharsRemainText.setTextColor(originTextColor);
}
mCharsRemainText.setText(remaining + "");
}
public String getText() {
return mEditText.getText().toString();
}
public void setEnabled(boolean b) {
mEditText.setEnabled(b);
}
public void setOnKeyListener(OnKeyListener listener) {
mEditText.setOnKeyListener(listener);
}
public void addTextChangedListener(TextWatcher watcher){
mEditText.addTextChangedListener(watcher);
}
public void requestFocus() {
mEditText.requestFocus();
}
public EditText getEditText() {
return mEditText;
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import java.util.ArrayList;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class TweetArrayAdapter extends BaseAdapter implements TweetAdapter {
private static final String TAG = "TweetArrayAdapter";
protected ArrayList<Tweet> mTweets;
private Context mContext;
protected LayoutInflater mInflater;
protected StringBuilder mMetaBuilder;
private ImageLoaderCallback callback = new ImageLoaderCallback(){
@Override
public void refresh(String url, Bitmap bitmap) {
TweetArrayAdapter.this.refresh();
}
};
public TweetArrayAdapter(Context context) {
mTweets = new ArrayList<Tweet>();
mContext = context;
mInflater = LayoutInflater.from(mContext);
mMetaBuilder = new StringBuilder();
}
@Override
public int getCount() {
return mTweets.size();
}
@Override
public Object getItem(int position) {
return mTweets.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
private static class ViewHolder {
public TextView tweetUserText;
public TextView tweetText;
public ImageView profileImage;
public TextView metaText;
public ImageView fav;
public ImageView has_image;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);
boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true);
if (convertView == null) {
view = mInflater.inflate(R.layout.tweet, parent, false);
ViewHolder holder = new ViewHolder();
holder.tweetUserText = (TextView) view
.findViewById(R.id.tweet_user_text);
holder.tweetText = (TextView) view.findViewById(R.id.tweet_text);
holder.profileImage = (ImageView) view
.findViewById(R.id.profile_image);
holder.metaText = (TextView) view
.findViewById(R.id.tweet_meta_text);
holder.fav = (ImageView) view.findViewById(R.id.tweet_fav);
holder.has_image = (ImageView) view.findViewById(R.id.tweet_has_image);
view.setTag(holder);
} else {
view = convertView;
}
ViewHolder holder = (ViewHolder) view.getTag();
Tweet tweet = mTweets.get(position);
holder.tweetUserText.setText(tweet.screenName);
TextHelper.setSimpleTweetText(holder.tweetText, tweet.text);
// holder.tweetText.setText(tweet.text, BufferType.SPANNABLE);
String profileImageUrl = tweet.profileImageUrl;
if (useProfileImage){
if (!TextUtils.isEmpty(profileImageUrl)) {
holder.profileImage.setImageBitmap(TwitterApplication.mImageLoader
.get(profileImageUrl, callback));
}
}else{
holder.profileImage.setVisibility(View.GONE);
}
holder.metaText.setText(Tweet.buildMetaText(mMetaBuilder,
tweet.createdAt, tweet.source, tweet.inReplyToScreenName));
if (tweet.favorited.equals("true")) {
holder.fav.setVisibility(View.VISIBLE);
} else {
holder.fav.setVisibility(View.GONE);
}
if (!TextUtils.isEmpty(tweet.thumbnail_pic)) {
holder.has_image.setVisibility(View.VISIBLE);
} else {
holder.has_image.setVisibility(View.GONE);
}
return view;
}
public void refresh(ArrayList<Tweet> tweets) {
mTweets = tweets;
notifyDataSetChanged();
}
@Override
public void refresh() {
notifyDataSetChanged();
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.AbsListView;
import android.widget.ListView;
public class MyListView extends ListView implements ListView.OnScrollListener {
private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE;
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
setOnScrollListener(this);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean result = super.onInterceptTouchEvent(event);
if (mScrollState == OnScrollListener.SCROLL_STATE_FLING) {
return true;
}
return result;
}
private OnNeedMoreListener mOnNeedMoreListener;
public static interface OnNeedMoreListener {
public void needMore();
}
public void setOnNeedMoreListener(OnNeedMoreListener onNeedMoreListener) {
mOnNeedMoreListener = onNeedMoreListener;
}
private int mFirstVisibleItem;
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mOnNeedMoreListener == null) {
return;
}
if (firstVisibleItem != mFirstVisibleItem) {
if (firstVisibleItem + visibleItemCount >= totalItemCount) {
mOnNeedMoreListener.needMore();
}
} else {
mFirstVisibleItem = firstVisibleItem;
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
mScrollState = scrollState;
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
public interface IFlipper {
void showNext();
void showPrevious();
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.text.TextPaint;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.SearchActivity;
import com.ch_linghu.fanfoudroid.TwitterActivity;
import com.ch_linghu.fanfoudroid.WriteActivity;
import com.ch_linghu.fanfoudroid.ui.base.Refreshable;
public class NavBar implements Widget {
private static final String TAG = "NavBar";
public static final int HEADER_STYLE_HOME = 1;
public static final int HEADER_STYLE_WRITE = 2;
public static final int HEADER_STYLE_BACK = 3;
public static final int HEADER_STYLE_SEARCH = 4;
private ImageView mRefreshButton;
private ImageButton mSearchButton;
private ImageButton mWriteButton;
private TextView mTitleButton;
private Button mBackButton;
private ImageButton mHomeButton;
private MenuDialog mDialog;
private EditText mSearchEdit;
/** @deprecated 已废弃 */
protected AnimationDrawable mRefreshAnimation;
private ProgressBar mProgressBar = null; // 进度条(横)
private ProgressBar mLoadingProgress = null; // 旋转图标
public NavBar(int style, Context context) {
initHeader(style, (Activity) context);
}
private void initHeader(int style, final Activity activity) {
switch (style) {
case HEADER_STYLE_HOME:
addTitleButtonTo(activity);
addWriteButtonTo(activity);
addSearchButtonTo(activity);
addRefreshButtonTo(activity);
break;
case HEADER_STYLE_BACK:
addBackButtonTo(activity);
addWriteButtonTo(activity);
addSearchButtonTo(activity);
addRefreshButtonTo(activity);
break;
case HEADER_STYLE_WRITE:
addBackButtonTo(activity);
break;
case HEADER_STYLE_SEARCH:
addBackButtonTo(activity);
addSearchBoxTo(activity);
addSearchButtonTo(activity);
break;
}
}
/**
* 搜索硬按键行为
* @deprecated 这个不晓得还有没有用, 已经是已经被新的搜索替代的吧 ?
*/
public boolean onSearchRequested() {
/*
Intent intent = new Intent();
intent.setClass(this, SearchActivity.class);
startActivity(intent);
*/
return true;
}
/**
* 添加[LOGO/标题]按钮
* @param acticity
*/
private void addTitleButtonTo(final Activity acticity) {
mTitleButton = (TextView) acticity.findViewById(R.id.title);
mTitleButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int top = mTitleButton.getTop();
int height = mTitleButton.getHeight();
int x = top + height;
if (null == mDialog) {
Log.d(TAG, "Create menu dialog.");
mDialog = new MenuDialog(acticity);
mDialog.bindEvent(acticity);
mDialog.setPosition(-1, x);
}
// toggle dialog
if (mDialog.isShowing()) {
mDialog.dismiss(); // 没机会触发
} else {
mDialog.show();
}
}
});
}
/**
* 设置标题
* @param title
*/
public void setHeaderTitle(String title) {
if (null != mTitleButton) {
mTitleButton.setText(title);
TextPaint tp = mTitleButton.getPaint();
tp.setFakeBoldText(true); // 中文粗体
}
}
/**
* 设置标题
* @param resource R.string.xxx
*/
public void setHeaderTitle(int resource) {
if (null != mTitleButton) {
mTitleButton.setBackgroundResource(resource);
}
}
/**
* 添加[刷新]按钮
* @param activity
*/
private void addRefreshButtonTo(final Activity activity) {
mRefreshButton = (ImageView) activity.findViewById(R.id.top_refresh);
// FIXME: DELETE ME 暂时取消旋转效果, 测试ProgressBar
// refreshButton.setBackgroundResource(R.drawable.top_refresh);
// mRefreshAnimation = (AnimationDrawable)
// refreshButton.getBackground();
mProgressBar = (ProgressBar) activity.findViewById(R.id.progress_bar);
mLoadingProgress = (ProgressBar) activity
.findViewById(R.id.top_refresh_progressBar);
mRefreshButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (activity instanceof Refreshable) {
((Refreshable) activity).doRetrieve();
} else {
Log.e(TAG, "The current view "
+ activity.getClass().getName()
+ " cann't be retrieved");
}
}
});
}
/**
* Start/Stop Top Refresh Button's Animation
*
* @param animate
* start or stop
* @deprecated use feedback
*/
public void setRefreshAnimation(boolean animate) {
if (mRefreshAnimation != null) {
if (animate) {
mRefreshAnimation.start();
} else {
mRefreshAnimation.setVisible(true, true); // restart
mRefreshAnimation.start(); // goTo frame 0
mRefreshAnimation.stop();
}
} else {
Log.w(TAG, "mRefreshAnimation is null");
}
}
/**
* 添加[搜索]按钮
* @param activity
*/
private void addSearchButtonTo(final Activity activity) {
mSearchButton = (ImageButton) activity.findViewById(R.id.search);
mSearchButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
startSearch(activity);
}
});
}
// 这个方法会在SearchActivity里重写
protected boolean startSearch(final Activity activity) {
Intent intent = new Intent();
intent.setClass(activity, SearchActivity.class);
activity.startActivity(intent);
return true;
}
/**
* 添加[搜索框]
* @param activity
*/
private void addSearchBoxTo(final Activity activity) {
mSearchEdit = (EditText) activity.findViewById(R.id.search_edit);
}
/**
* 添加[撰写]按钮
* @param activity
*/
private void addWriteButtonTo(final Activity activity) {
mWriteButton = (ImageButton) activity.findViewById(R.id.writeMessage);
mWriteButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// forward to write activity
Intent intent = new Intent();
intent.setClass(v.getContext(), WriteActivity.class);
v.getContext().startActivity(intent);
}
});
}
/**
* 添加[回首页]按钮
* @param activity
*/
@SuppressWarnings("unused")
private void addHomeButton(final Activity activity) {
mHomeButton = (ImageButton) activity.findViewById(R.id.home);
mHomeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// 动画
Animation anim = AnimationUtils.loadAnimation(v.getContext(),
R.anim.scale_lite);
v.startAnimation(anim);
// forward to TwitterActivity
Intent intent = new Intent();
intent.setClass(v.getContext(), TwitterActivity.class);
v.getContext().startActivity(intent);
}
});
}
/**
* 添加[返回]按钮
* @param activity
*/
private void addBackButtonTo(final Activity activity) {
mBackButton = (Button) activity.findViewById(R.id.top_back);
// 中文粗体
// TextPaint tp = backButton.getPaint();
// tp.setFakeBoldText(true);
mBackButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Go back to previous activity
activity.finish();
}
});
}
public void destroy() {
// dismiss dialog before destroy
// to avoid android.view.WindowLeaked Exception
if (mDialog != null) {
mDialog.dismiss();
mDialog = null;
}
mRefreshButton = null;
mSearchButton = null;
mWriteButton = null;
mTitleButton = null;
mBackButton = null;
mHomeButton = null;
mSearchButton = null;
mSearchEdit = null;
mProgressBar = null;
mLoadingProgress = null;
}
public ImageView getRefreshButton() {
return mRefreshButton;
}
public ImageButton getSearchButton() {
return mSearchButton;
}
public ImageButton getWriteButton() {
return mWriteButton;
}
public TextView getTitleButton() {
return mTitleButton;
}
public Button getBackButton() {
return mBackButton;
}
public ImageButton getHomeButton() {
return mHomeButton;
}
public MenuDialog getDialog() {
return mDialog;
}
public EditText getSearchEdit() {
return mSearchEdit;
}
/** @deprecated 已废弃 */
public AnimationDrawable getRefreshAnimation() {
return mRefreshAnimation;
}
public ProgressBar getProgressBar() {
return mProgressBar;
}
public ProgressBar getLoadingProgress() {
return mLoadingProgress;
}
@Override
public Context getContext() {
if (null != mDialog) {
return mDialog.getContext();
}
if (null != mTitleButton) {
return mTitleButton.getContext();
}
return null;
}
}
| Java |
package com.ch_linghu.fanfoudroid.ui.module;
import android.widget.ListAdapter;
public interface TweetAdapter extends ListAdapter{
void refresh();
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.text.MessageFormat;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.UserArrayBaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter;
public class FollowersActivity extends UserArrayBaseActivity {
private ListView mUserList;
private UserArrayAdapter mAdapter;
private static final String TAG = "FollowersActivity";
private String userId;
private String userName;
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FOLLOWERS";
private static final String USER_ID = "userId";
private static final String USER_NAME = "userName";
private int currentPage=1;
private int followersCount=0;
private static final double PRE_PAGE_COUNT=100.0;//官方分页为每页100
private int pageCount=0;
private String[] ids;
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
this.userId = extras.getString(USER_ID);
this.userName = extras.getString(USER_NAME);
} else {
// 获取登录用户id
userId=TwitterApplication.getMyselfId();
userName=TwitterApplication.getMyselfName();
}
if (super._onCreate(savedInstanceState)) {
String myself = TwitterApplication.getMyselfId();
if(getUserId()==myself){
mNavbar.setHeaderTitle(MessageFormat.format(
getString(R.string.profile_followers_count_title), "我"));
} else {
mNavbar.setHeaderTitle(MessageFormat.format(
getString(R.string.profile_followers_count_title), userName));
}
return true;
}else{
return false;
}
}
public static Intent createIntent(String userId, String userName) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(USER_ID, userId);
intent.putExtra(USER_NAME, userName);
return intent;
}
@Override
public Paging getNextPage() {
currentPage+=1;
return new Paging(currentPage);
}
@Override
protected String getUserId() {
return this.userId;
}
@Override
public Paging getCurrentPage() {
return new Paging(this.currentPage);
}
@Override
protected List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers(
String userId, Paging page) throws HttpException {
return getApi().getFollowersList(userId, page);
}
}
| Java |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity;
public class MentionActivity extends TwitterCursorBaseActivity {
private static final String TAG = "MentionActivity";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.REPLIES";
static final int DIALOG_WRITE_ID = 0;
public static Intent createIntent(Context context) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
return intent;
}
public static Intent createNewTaskIntent(Context context) {
Intent intent = createIntent(context);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)){
mNavbar.setHeaderTitle("@提到我的");
return true;
}else{
return false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
protected Cursor fetchMessages() {
return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_MENTION);
}
@Override
protected void markAllRead() {
getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_MENTION);
}
@Override
protected String getActivityTitle() {
return getResources().getString(R.string.page_title_mentions);
}
// for Retrievable interface
@Override
public String fetchMaxId() {
return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_MENTION);
}
@Override
public List<Status> getMessageSinceId(String maxId) throws HttpException {
if (maxId != null){
return getApi().getMentions(new Paging(maxId));
}else{
return getApi().getMentions();
}
}
@Override
public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) {
return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_MENTION, isUnread);
}
@Override
public String fetchMinId() {
return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_MENTION);
}
@Override
public List<Status> getMoreMessageFromId(String minId)
throws HttpException {
Paging paging = new Paging(1, 20);
paging.setMaxId(minId);
return getApi().getMentions(paging);
}
@Override
public int getDatabaseType() {
return StatusTable.TYPE_MENTION;
}
@Override
public String getUserId() {
return TwitterApplication.getMyselfId();
}
} | Java |
package com.ch_linghu.fanfoudroid.http;
/**
* HTTP StatusCode is not 200
*/
public class HttpException extends Exception {
private int statusCode = -1;
public HttpException(String msg) {
super(msg);
}
public HttpException(Exception cause) {
super(cause);
}
public HttpException(String msg, int statusCode) {
super(msg);
this.statusCode = statusCode;
}
public HttpException(String msg, Exception cause) {
super(msg, cause);
}
public HttpException(String msg, Exception cause, int statusCode) {
super(msg, cause);
this.statusCode = statusCode;
}
public int getStatusCode() {
return this.statusCode;
}
}
| Java |
package com.ch_linghu.fanfoudroid.http;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.SSLHandshakeException;
import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.HttpVersion;
import org.apache.http.NoHttpResponseException;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.fanfou.Configuration;
import com.ch_linghu.fanfoudroid.fanfou.RefuseError;
import com.ch_linghu.fanfoudroid.util.DebugTimer;
/**
* Wrap of org.apache.http.impl.client.DefaultHttpClient
*
* @author lds
*
*/
public class HttpClient {
private static final String TAG = "HttpClient";
private final static boolean DEBUG = Configuration.getDebug();
/** OK: Success! */
public static final int OK = 200;
/** Not Modified: There was no new data to return. */
public static final int NOT_MODIFIED = 304;
/** Bad Request: The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting. */
public static final int BAD_REQUEST = 400;
/** Not Authorized: Authentication credentials were missing or incorrect. */
public static final int NOT_AUTHORIZED = 401;
/** Forbidden: The request is understood, but it has been refused. An accompanying error message will explain why. */
public static final int FORBIDDEN = 403;
/** Not Found: The URI requested is invalid or the resource requested, such as a user, does not exists. */
public static final int NOT_FOUND = 404;
/** Not Acceptable: Returned by the Search API when an invalid format is specified in the request. */
public static final int NOT_ACCEPTABLE = 406;
/** Internal Server Error: Something is broken. Please post to the group so the Weibo team can investigate. */
public static final int INTERNAL_SERVER_ERROR = 500;
/** Bad Gateway: Weibo is down or being upgraded. */
public static final int BAD_GATEWAY = 502;
/** Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited. */
public static final int SERVICE_UNAVAILABLE = 503;
private static final int CONNECTION_TIMEOUT_MS = 30 * 1000;
private static final int SOCKET_TIMEOUT_MS = 30 * 1000;
public static final int RETRIEVE_LIMIT = 20;
public static final int RETRIED_TIME = 3;
private static final String SERVER_HOST = "api.fanfou.com";
private DefaultHttpClient mClient;
private AuthScope mAuthScope;
private BasicHttpContext localcontext;
private String mUserId;
private String mPassword;
private static boolean isAuthenticationEnabled = false;
public HttpClient() {
prepareHttpClient();
}
/**
* @param user_id auth user
* @param password auth password
*/
public HttpClient(String user_id, String password) {
prepareHttpClient();
setCredentials(user_id, password);
}
/**
* Empty the credentials
*/
public void reset() {
setCredentials("", "");
}
/**
* @return authed user id
*/
public String getUserId() {
return mUserId;
}
/**
* @return authed user password
*/
public String getPassword() {
return mPassword;
}
/**
* @param hostname the hostname (IP or DNS name)
* @param port the port number. -1 indicates the scheme default port.
* @param scheme the name of the scheme. null indicates the default scheme
*/
public void setProxy(String host, int port, String scheme) {
HttpHost proxy = new HttpHost(host, port, scheme);
mClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
public void removeProxy() {
mClient.getParams().removeParameter(ConnRoutePNames.DEFAULT_PROXY);
}
private void enableDebug() {
Log.d(TAG, "enable apache.http debug");
java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.FINEST);
java.util.logging.Logger.getLogger("org.apache.http.wire").setLevel(java.util.logging.Level.FINER);
java.util.logging.Logger.getLogger("org.apache.http.headers").setLevel(java.util.logging.Level.OFF);
/*
System.setProperty("log.tag.org.apache.http", "VERBOSE");
System.setProperty("log.tag.org.apache.http.wire", "VERBOSE");
System.setProperty("log.tag.org.apache.http.headers", "VERBOSE");
在这里使用System.setProperty设置不会生效, 原因不明, 必须在终端上输入以下命令方能开启http调试信息:
> adb shell setprop log.tag.org.apache.http VERBOSE
> adb shell setprop log.tag.org.apache.http.wire VERBOSE
> adb shell setprop log.tag.org.apache.http.headers VERBOSE
*/
}
/**
* Setup DefaultHttpClient
*
* Use ThreadSafeClientConnManager.
*
*/
private void prepareHttpClient() {
if (DEBUG) {
enableDebug();
}
// Create and initialize HTTP parameters
HttpParams params = new BasicHttpParams();
ConnManagerParams.setMaxTotalConnections(params, 10);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
// Create and initialize scheme registry
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory
.getSocketFactory(), 80));
schemeRegistry.register(new Scheme("https", SSLSocketFactory
.getSocketFactory(), 443));
// Create an HttpClient with the ThreadSafeClientConnManager.
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params,
schemeRegistry);
mClient = new DefaultHttpClient(cm, params);
// Setup BasicAuth
BasicScheme basicScheme = new BasicScheme();
mAuthScope = new AuthScope(SERVER_HOST, AuthScope.ANY_PORT);
// mClient.setAuthSchemes(authRegistry);
mClient.setCredentialsProvider(new BasicCredentialsProvider());
// Generate BASIC scheme object and stick it to the local
// execution context
localcontext = new BasicHttpContext();
localcontext.setAttribute("preemptive-auth", basicScheme);
// first request interceptor
mClient.addRequestInterceptor(preemptiveAuth, 0);
// Support GZIP
mClient.addResponseInterceptor(gzipResponseIntercepter);
// TODO: need to release this connection in httpRequest()
// cm.releaseConnection(conn, validDuration, timeUnit);
//httpclient.getConnectionManager().shutdown();
}
/**
* HttpRequestInterceptor for DefaultHttpClient
*/
private static HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
@Override
public void process(final HttpRequest request, final HttpContext context) {
AuthState authState = (AuthState) context
.getAttribute(ClientContext.TARGET_AUTH_STATE);
CredentialsProvider credsProvider = (CredentialsProvider) context
.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost) context
.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (authState.getAuthScheme() == null) {
AuthScope authScope = new AuthScope(targetHost.getHostName(),
targetHost.getPort());
Credentials creds = credsProvider.getCredentials(authScope);
if (creds != null) {
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
};
private static HttpResponseInterceptor gzipResponseIntercepter =
new HttpResponseInterceptor() {
@Override
public void process(HttpResponse response, HttpContext context)
throws org.apache.http.HttpException, IOException {
HttpEntity entity = response.getEntity();
Header ceheader = entity.getContentEncoding();
if (ceheader != null) {
HeaderElement[] codecs = ceheader.getElements();
for (int i = 0; i < codecs.length; i++) {
if (codecs[i].getName().equalsIgnoreCase("gzip")) {
response.setEntity(
new GzipDecompressingEntity(response.getEntity()));
return;
}
}
}
}
};
static class GzipDecompressingEntity extends HttpEntityWrapper {
public GzipDecompressingEntity(final HttpEntity entity) {
super(entity);
}
@Override
public InputStream getContent()
throws IOException, IllegalStateException {
// the wrapped entity's getContent() decides about repeatability
InputStream wrappedin = wrappedEntity.getContent();
return new GZIPInputStream(wrappedin);
}
@Override
public long getContentLength() {
// length of ungzipped content is not known
return -1;
}
}
/**
* Setup Credentials for HTTP Basic Auth
*
* @param username
* @param password
*/
public void setCredentials(String username, String password) {
mUserId = username;
mPassword = password;
mClient.getCredentialsProvider().setCredentials(mAuthScope,
new UsernamePasswordCredentials(username, password));
isAuthenticationEnabled = true;
}
public Response post(String url, ArrayList<BasicNameValuePair> postParams,
boolean authenticated) throws HttpException {
if (null == postParams) {
postParams = new ArrayList<BasicNameValuePair>();
}
return httpRequest(url, postParams, authenticated, HttpPost.METHOD_NAME);
}
public Response post(String url, ArrayList<BasicNameValuePair> params)
throws HttpException {
return httpRequest(url, params, false, HttpPost.METHOD_NAME);
}
public Response post(String url, boolean authenticated)
throws HttpException {
return httpRequest(url, null, authenticated, HttpPost.METHOD_NAME);
}
public Response post(String url) throws HttpException {
return httpRequest(url, null, false, HttpPost.METHOD_NAME);
}
public Response post(String url, File file) throws HttpException {
return httpRequest(url, null, file, false, HttpPost.METHOD_NAME);
}
/**
* POST一个文件
*
* @param url
* @param file
* @param authenticate
* @return
* @throws HttpException
*/
public Response post(String url, File file, boolean authenticate)
throws HttpException {
return httpRequest(url, null, file, authenticate, HttpPost.METHOD_NAME);
}
public Response get(String url, ArrayList<BasicNameValuePair> params,
boolean authenticated) throws HttpException {
return httpRequest(url, params, authenticated, HttpGet.METHOD_NAME);
}
public Response get(String url, ArrayList<BasicNameValuePair> params)
throws HttpException {
return httpRequest(url, params, false, HttpGet.METHOD_NAME);
}
public Response get(String url) throws HttpException {
return httpRequest(url, null, false, HttpGet.METHOD_NAME);
}
public Response get(String url, boolean authenticated)
throws HttpException {
return httpRequest(url, null, authenticated, HttpGet.METHOD_NAME);
}
public Response httpRequest(String url,
ArrayList<BasicNameValuePair> postParams, boolean authenticated,
String httpMethod) throws HttpException {
return httpRequest(url, postParams, null, authenticated, httpMethod);
}
/**
* Execute the DefaultHttpClient
*
* @param url
* target
* @param postParams
* @param file
* can be NULL
* @param authenticated
* need or not
* @param httpMethod
* HttpPost.METHOD_NAME
* HttpGet.METHOD_NAME
* HttpDelete.METHOD_NAME
* @return Response from server
* @throws HttpException 此异常包装了一系列底层异常 <br /><br />
* 1. 底层异常, 可使用getCause()查看: <br />
* <li>URISyntaxException, 由`new URI` 引发的.</li>
* <li>IOException, 由`createMultipartEntity` 或 `UrlEncodedFormEntity` 引发的.</li>
* <li>IOException和ClientProtocolException, 由`HttpClient.execute` 引发的.</li><br />
*
* 2. 当响应码不为200时报出的各种子类异常:
* <li>HttpRequestException, 通常发生在请求的错误,如请求错误了 网址导致404等, 抛出此异常,
* 首先检查request log, 确认不是人为错误导致请求失败</li>
* <li>HttpAuthException, 通常发生在Auth失败, 检查用于验证登录的用户名/密码/KEY等</li>
* <li>HttpRefusedException, 通常发生在服务器接受到请求, 但拒绝请求, 可是多种原因, 具体原因
* 服务器会返回拒绝理由, 调用HttpRefusedException#getError#getMessage查看</li>
* <li>HttpServerException, 通常发生在服务器发生错误时, 检查服务器端是否在正常提供服务</li>
* <li>HttpException, 其他未知错误.</li>
*/
public Response httpRequest(String url, ArrayList<BasicNameValuePair> postParams,
File file, boolean authenticated, String httpMethod) throws HttpException {
Log.d(TAG, "Sending " + httpMethod + " request to " + url);
if (TwitterApplication.DEBUG){
DebugTimer.betweenStart("HTTP");
}
URI uri = createURI(url);
HttpResponse response = null;
Response res = null;
HttpUriRequest method = null;
// Create POST, GET or DELETE METHOD
method = createMethod(httpMethod, uri, file, postParams);
// Setup ConnectionParams, Request Headers
SetupHTTPConnectionParams(method);
// Execute Request
try {
response = mClient.execute(method, localcontext);
res = new Response(response);
} catch (ClientProtocolException e) {
Log.e(TAG, e.getMessage(), e);
throw new HttpException(e.getMessage(), e);
} catch (IOException ioe) {
throw new HttpException(ioe.getMessage(), ioe);
}
if (response != null) {
int statusCode = response.getStatusLine().getStatusCode();
// It will throw a weiboException while status code is not 200
HandleResponseStatusCode(statusCode, res);
} else {
Log.e(TAG, "response is null");
}
if (TwitterApplication.DEBUG){
DebugTimer.betweenEnd("HTTP");
}
return res;
}
/**
* CreateURI from URL string
*
* @param url
* @return request URI
* @throws HttpException
* Cause by URISyntaxException
*/
private URI createURI(String url) throws HttpException {
URI uri;
try {
uri = new URI(url);
} catch (URISyntaxException e) {
Log.e(TAG, e.getMessage(), e);
throw new HttpException("Invalid URL.");
}
return uri;
}
/**
* 创建可带一个File的MultipartEntity
*
* @param filename
* 文件名
* @param file
* 文件
* @param postParams
* 其他POST参数
* @return 带文件和其他参数的Entity
* @throws UnsupportedEncodingException
*/
private MultipartEntity createMultipartEntity(String filename, File file,
ArrayList<BasicNameValuePair> postParams)
throws UnsupportedEncodingException {
MultipartEntity entity = new MultipartEntity();
// Don't try this. Server does not appear to support chunking.
// entity.addPart("media", new InputStreamBody(imageStream, "media"));
entity.addPart(filename, new FileBody(file));
for (BasicNameValuePair param : postParams) {
entity.addPart(param.getName(), new StringBody(param.getValue()));
}
return entity;
}
/**
* Setup HTTPConncetionParams
*
* @param method
*/
private void SetupHTTPConnectionParams(HttpUriRequest method) {
HttpConnectionParams.setConnectionTimeout(method.getParams(),
CONNECTION_TIMEOUT_MS);
HttpConnectionParams
.setSoTimeout(method.getParams(), SOCKET_TIMEOUT_MS);
mClient.setHttpRequestRetryHandler(requestRetryHandler);
method.addHeader("Accept-Encoding", "gzip, deflate");
method.addHeader("Accept-Charset", "UTF-8,*;q=0.5");
}
/**
* Create request method, such as POST, GET, DELETE
*
* @param httpMethod
* "GET","POST","DELETE"
* @param uri
* 请求的URI
* @param file
* 可为null
* @param postParams
* POST参数
* @return httpMethod Request implementations for the various HTTP methods
* like GET and POST.
* @throws HttpException
* createMultipartEntity 或 UrlEncodedFormEntity引发的IOException
*/
private HttpUriRequest createMethod(String httpMethod, URI uri, File file,
ArrayList<BasicNameValuePair> postParams) throws HttpException {
HttpUriRequest method;
if (httpMethod.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
// POST METHOD
HttpPost post = new HttpPost(uri);
// See this: http://groups.google.com/group/twitter-development-talk/browse_thread/thread/e178b1d3d63d8e3b
post.getParams().setBooleanParameter("http.protocol.expect-continue", false);
try {
HttpEntity entity = null;
if (null != file) {
entity = createMultipartEntity("photo", file, postParams);
post.setEntity(entity);
} else if (null != postParams) {
entity = new UrlEncodedFormEntity(postParams, HTTP.UTF_8);
}
post.setEntity(entity);
} catch (IOException ioe) {
throw new HttpException(ioe.getMessage(), ioe);
}
method = post;
} else if (httpMethod.equalsIgnoreCase(HttpDelete.METHOD_NAME)) {
method = new HttpDelete(uri);
} else {
method = new HttpGet(uri);
}
return method;
}
/**
* 解析HTTP错误码
*
* @param statusCode
* @return
*/
private static String getCause(int statusCode) {
String cause = null;
switch (statusCode) {
case NOT_MODIFIED:
break;
case BAD_REQUEST:
cause = "The request was invalid. An accompanying error message will explain why. This is the status code will be returned during rate limiting.";
break;
case NOT_AUTHORIZED:
cause = "Authentication credentials were missing or incorrect.";
break;
case FORBIDDEN:
cause = "The request is understood, but it has been refused. An accompanying error message will explain why.";
break;
case NOT_FOUND:
cause = "The URI requested is invalid or the resource requested, such as a user, does not exists.";
break;
case NOT_ACCEPTABLE:
cause = "Returned by the Search API when an invalid format is specified in the request.";
break;
case INTERNAL_SERVER_ERROR:
cause = "Something is broken. Please post to the group so the Weibo team can investigate.";
break;
case BAD_GATEWAY:
cause = "Weibo is down or being upgraded.";
break;
case SERVICE_UNAVAILABLE:
cause = "Service Unavailable: The Weibo servers are up, but overloaded with requests. Try again later. The search and trend methods use this to indicate when you are being rate limited.";
break;
default:
cause = "";
}
return statusCode + ":" + cause;
}
public boolean isAuthenticationEnabled() {
return isAuthenticationEnabled;
}
public static void log(String msg) {
if (DEBUG) {
Log.d(TAG, msg);
}
}
/**
* Handle Status code
*
* @param statusCode
* 响应的状态码
* @param res
* 服务器响应
* @throws HttpException
* 当响应码不为200时都会报出此异常:<br />
* <li>HttpRequestException, 通常发生在请求的错误,如请求错误了 网址导致404等, 抛出此异常,
* 首先检查request log, 确认不是人为错误导致请求失败</li>
* <li>HttpAuthException, 通常发生在Auth失败, 检查用于验证登录的用户名/密码/KEY等</li>
* <li>HttpRefusedException, 通常发生在服务器接受到请求, 但拒绝请求, 可是多种原因, 具体原因
* 服务器会返回拒绝理由, 调用HttpRefusedException#getError#getMessage查看</li>
* <li>HttpServerException, 通常发生在服务器发生错误时, 检查服务器端是否在正常提供服务</li>
* <li>HttpException, 其他未知错误.</li>
*/
private void HandleResponseStatusCode(int statusCode, Response res)
throws HttpException {
String msg = getCause(statusCode) + "\n";
RefuseError error = null;
switch (statusCode) {
// It's OK, do nothing
case OK:
break;
// Mine mistake, Check the Log
case NOT_MODIFIED:
case BAD_REQUEST:
case NOT_FOUND:
case NOT_ACCEPTABLE:
throw new HttpException(msg + res.asString(), statusCode);
// UserName/Password incorrect
case NOT_AUTHORIZED:
throw new HttpAuthException(msg + res.asString(), statusCode);
// Server will return a error message, use
// HttpRefusedException#getError() to see.
case FORBIDDEN:
throw new HttpRefusedException(msg, statusCode);
// Something wrong with server
case INTERNAL_SERVER_ERROR:
case BAD_GATEWAY:
case SERVICE_UNAVAILABLE:
throw new HttpServerException(msg, statusCode);
// Others
default:
throw new HttpException(msg + res.asString(), statusCode);
}
}
public static String encode(String value) throws HttpException {
try {
return URLEncoder.encode(value, HTTP.UTF_8);
} catch (UnsupportedEncodingException e_e) {
throw new HttpException(e_e.getMessage(), e_e);
}
}
public static String encodeParameters(ArrayList<BasicNameValuePair> params)
throws HttpException {
StringBuffer buf = new StringBuffer();
for (int j = 0; j < params.size(); j++) {
if (j != 0) {
buf.append("&");
}
try {
buf.append(URLEncoder.encode(params.get(j).getName(), "UTF-8"))
.append("=")
.append(URLEncoder.encode(params.get(j).getValue(),
"UTF-8"));
} catch (java.io.UnsupportedEncodingException neverHappen) {
throw new HttpException(neverHappen.getMessage(), neverHappen);
}
}
return buf.toString();
}
/**
* 异常自动恢复处理, 使用HttpRequestRetryHandler接口实现请求的异常恢复
*/
private static HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() {
// 自定义的恢复策略
public boolean retryRequest(IOException exception, int executionCount,
HttpContext context) {
// 设置恢复策略,在发生异常时候将自动重试N次
if (executionCount >= RETRIED_TIME) {
// Do not retry if over max retry count
return false;
}
if (exception instanceof NoHttpResponseException) {
// Retry if the server dropped connection on us
return true;
}
if (exception instanceof SSLHandshakeException) {
// Do not retry on SSL handshake exception
return false;
}
HttpRequest request = (HttpRequest) context
.getAttribute(ExecutionContext.HTTP_REQUEST);
boolean idempotent = (request instanceof HttpEntityEnclosingRequest);
if (!idempotent) {
// Retry if the request is considered idempotent
return true;
}
return false;
}
};
}
| Java |
package com.ch_linghu.fanfoudroid.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.CharArrayBuffer;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import android.util.Log;
import com.ch_linghu.fanfoudroid.util.DebugTimer;
public class Response {
private final HttpResponse mResponse;
private boolean mStreamConsumed = false;
public Response(HttpResponse res) {
mResponse = res;
}
/**
* Convert Response to inputStream
*
* @return InputStream or null
* @throws ResponseException
*/
public InputStream asStream() throws ResponseException {
try {
final HttpEntity entity = mResponse.getEntity();
if (entity != null) {
return entity.getContent();
}
} catch (IllegalStateException e) {
throw new ResponseException(e.getMessage(), e);
} catch (IOException e) {
throw new ResponseException(e.getMessage(), e);
}
return null;
}
/**
* @deprecated use entity.getContent();
* @param entity
* @return
* @throws ResponseException
*/
private InputStream asStream(HttpEntity entity) throws ResponseException {
if (null == entity) {
return null;
}
InputStream is = null;
try {
is = entity.getContent();
} catch (IllegalStateException e) {
throw new ResponseException(e.getMessage(), e);
} catch (IOException e) {
throw new ResponseException(e.getMessage(), e);
}
//mResponse = null;
return is;
}
/**
* Convert Response to Context String
*
* @return response context string or null
* @throws ResponseException
*/
public String asString() throws ResponseException {
try {
return entityToString(mResponse.getEntity());
} catch (IOException e) {
throw new ResponseException(e.getMessage(), e);
}
}
/**
* EntityUtils.toString(entity, "UTF-8");
*
* @param entity
* @return
* @throws IOException
* @throws ResponseException
*/
private String entityToString(final HttpEntity entity) throws IOException, ResponseException {
DebugTimer.betweenStart("AS STRING");
if (null == entity) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
//InputStream instream = asStream(entity);
if (instream == null) {
return "";
}
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
int i = (int) entity.getContentLength();
if (i < 0) {
i = 4096;
}
Log.i("LDS", i + " content length");
Reader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
CharArrayBuffer buffer = new CharArrayBuffer(i);
try {
char[] tmp = new char[1024];
int l;
while ((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
} finally {
reader.close();
}
DebugTimer.betweenEnd("AS STRING");
return buffer.toString();
}
/**
* @deprecated use entityToString()
* @param in
* @return
* @throws ResponseException
*/
private String inputStreamToString(final InputStream in) throws IOException {
if (null == in) {
return null;
}
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuffer buf = new StringBuffer();
try {
char[] buffer = new char[1024];
while ((reader.read(buffer)) != -1) {
buf.append(buffer);
}
return buf.toString();
} finally {
if (reader != null) {
reader.close();
setStreamConsumed(true);
}
}
}
public JSONObject asJSONObject() throws ResponseException {
try {
return new JSONObject(asString());
} catch (JSONException jsone) {
throw new ResponseException(jsone.getMessage() + ":"
+ asString(), jsone);
}
}
public JSONArray asJSONArray() throws ResponseException {
try {
return new JSONArray(asString());
} catch (Exception jsone) {
throw new ResponseException(jsone.getMessage(), jsone);
}
}
private void setStreamConsumed(boolean mStreamConsumed) {
this.mStreamConsumed = mStreamConsumed;
}
public boolean isStreamConsumed() {
return mStreamConsumed;
}
/**
* @deprecated
* @return
*/
public Document asDocument() {
// TODO Auto-generated method stub
return null;
}
private static Pattern escaped = Pattern.compile("&#([0-9]{3,5});");
/**
* Unescape UTF-8 escaped characters to string.
* @author pengjianq...@gmail.com
*
* @param original The string to be unescaped.
* @return The unescaped string
*/
public static String unescape(String original) {
Matcher mm = escaped.matcher(original);
StringBuffer unescaped = new StringBuffer();
while (mm.find()) {
mm.appendReplacement(unescaped, Character.toString(
(char) Integer.parseInt(mm.group(1), 10)));
}
mm.appendTail(unescaped);
return unescaped.toString();
}
}
| Java |
package com.ch_linghu.fanfoudroid.http;
import java.util.HashMap;
import java.util.Map;
public class HTMLEntity {
public static String escape(String original) {
StringBuffer buf = new StringBuffer(original);
escape(buf);
return buf.toString();
}
public static void escape(StringBuffer original) {
int index = 0;
String escaped;
while (index < original.length()) {
escaped = entityEscapeMap.get(original.substring(index, index + 1));
if (null != escaped) {
original.replace(index, index + 1, escaped);
index += escaped.length();
} else {
index++;
}
}
}
public static String unescape(String original) {
StringBuffer buf = new StringBuffer(original);
unescape(buf);
return buf.toString();
}
public static void unescape(StringBuffer original) {
int index = 0;
int semicolonIndex = 0;
String escaped;
String entity;
while (index < original.length()) {
index = original.indexOf("&", index);
if (-1 == index) {
break;
}
semicolonIndex = original.indexOf(";", index);
if (-1 != semicolonIndex && 10 > (semicolonIndex - index)) {
escaped = original.substring(index, semicolonIndex + 1);
entity = escapeEntityMap.get(escaped);
if (null != entity) {
original.replace(index, semicolonIndex + 1, entity);
}
index++;
} else {
break;
}
}
}
private static Map<String, String> entityEscapeMap = new HashMap<String, String>();
private static Map<String, String> escapeEntityMap = new HashMap<String, String>();
static {
String[][] entities =
{{" ", " "/* no-break space = non-breaking space */, "\u00A0"}
, {"¡", "¡"/* inverted exclamation mark */, "\u00A1"}
, {"¢", "¢"/* cent sign */, "\u00A2"}
, {"£", "£"/* pound sign */, "\u00A3"}
, {"¤", "¤"/* currency sign */, "\u00A4"}
, {"¥", "¥"/* yen sign = yuan sign */, "\u00A5"}
, {"¦", "¦"/* broken bar = broken vertical bar */, "\u00A6"}
, {"§", "§"/* section sign */, "\u00A7"}
, {"¨", "¨"/* diaeresis = spacing diaeresis */, "\u00A8"}
, {"©", "©"/* copyright sign */, "\u00A9"}
, {"ª", "ª"/* feminine ordinal indicator */, "\u00AA"}
, {"«", "«"/* left-pointing double angle quotation mark = left pointing guillemet */, "\u00AB"}
, {"¬", "¬"/* not sign = discretionary hyphen */, "\u00AC"}
, {"­", "­"/* soft hyphen = discretionary hyphen */, "\u00AD"}
, {"®", "®"/* registered sign = registered trade mark sign */, "\u00AE"}
, {"¯", "¯"/* macron = spacing macron = overline = APL overbar */, "\u00AF"}
, {"°", "°"/* degree sign */, "\u00B0"}
, {"±", "±"/* plus-minus sign = plus-or-minus sign */, "\u00B1"}
, {"²", "²"/* superscript two = superscript digit two = squared */, "\u00B2"}
, {"³", "³"/* superscript three = superscript digit three = cubed */, "\u00B3"}
, {"´", "´"/* acute accent = spacing acute */, "\u00B4"}
, {"µ", "µ"/* micro sign */, "\u00B5"}
, {"¶", "¶"/* pilcrow sign = paragraph sign */, "\u00B6"}
, {"·", "·"/* middle dot = Georgian comma = Greek middle dot */, "\u00B7"}
, {"¸", "¸"/* cedilla = spacing cedilla */, "\u00B8"}
, {"¹", "¹"/* superscript one = superscript digit one */, "\u00B9"}
, {"º", "º"/* masculine ordinal indicator */, "\u00BA"}
, {"»", "»"/* right-pointing double angle quotation mark = right pointing guillemet */, "\u00BB"}
, {"¼", "¼"/* vulgar fraction one quarter = fraction one quarter */, "\u00BC"}
, {"½", "½"/* vulgar fraction one half = fraction one half */, "\u00BD"}
, {"¾", "¾"/* vulgar fraction three quarters = fraction three quarters */, "\u00BE"}
, {"¿", "¿"/* inverted question mark = turned question mark */, "\u00BF"}
, {"À", "À"/* latin capital letter A with grave = latin capital letter A grave */, "\u00C0"}
, {"Á", "Á"/* latin capital letter A with acute */, "\u00C1"}
, {"Â", "Â"/* latin capital letter A with circumflex */, "\u00C2"}
, {"Ã", "Ã"/* latin capital letter A with tilde */, "\u00C3"}
, {"Ä", "Ä"/* latin capital letter A with diaeresis */, "\u00C4"}
, {"Å", "Å"/* latin capital letter A with ring above = latin capital letter A ring */, "\u00C5"}
, {"Æ", "Æ"/* latin capital letter AE = latin capital ligature AE */, "\u00C6"}
, {"Ç", "Ç"/* latin capital letter C with cedilla */, "\u00C7"}
, {"È", "È"/* latin capital letter E with grave */, "\u00C8"}
, {"É", "É"/* latin capital letter E with acute */, "\u00C9"}
, {"Ê", "Ê"/* latin capital letter E with circumflex */, "\u00CA"}
, {"Ë", "Ë"/* latin capital letter E with diaeresis */, "\u00CB"}
, {"Ì", "Ì"/* latin capital letter I with grave */, "\u00CC"}
, {"Í", "Í"/* latin capital letter I with acute */, "\u00CD"}
, {"Î", "Î"/* latin capital letter I with circumflex */, "\u00CE"}
, {"Ï", "Ï"/* latin capital letter I with diaeresis */, "\u00CF"}
, {"Ð", "Ð"/* latin capital letter ETH */, "\u00D0"}
, {"Ñ", "Ñ"/* latin capital letter N with tilde */, "\u00D1"}
, {"Ò", "Ò"/* latin capital letter O with grave */, "\u00D2"}
, {"Ó", "Ó"/* latin capital letter O with acute */, "\u00D3"}
, {"Ô", "Ô"/* latin capital letter O with circumflex */, "\u00D4"}
, {"Õ", "Õ"/* latin capital letter O with tilde */, "\u00D5"}
, {"Ö", "Ö"/* latin capital letter O with diaeresis */, "\u00D6"}
, {"×", "×"/* multiplication sign */, "\u00D7"}
, {"Ø", "Ø"/* latin capital letter O with stroke = latin capital letter O slash */, "\u00D8"}
, {"Ù", "Ù"/* latin capital letter U with grave */, "\u00D9"}
, {"Ú", "Ú"/* latin capital letter U with acute */, "\u00DA"}
, {"Û", "Û"/* latin capital letter U with circumflex */, "\u00DB"}
, {"Ü", "Ü"/* latin capital letter U with diaeresis */, "\u00DC"}
, {"Ý", "Ý"/* latin capital letter Y with acute */, "\u00DD"}
, {"Þ", "Þ"/* latin capital letter THORN */, "\u00DE"}
, {"ß", "ß"/* latin small letter sharp s = ess-zed */, "\u00DF"}
, {"à", "à"/* latin small letter a with grave = latin small letter a grave */, "\u00E0"}
, {"á", "á"/* latin small letter a with acute */, "\u00E1"}
, {"â", "â"/* latin small letter a with circumflex */, "\u00E2"}
, {"ã", "ã"/* latin small letter a with tilde */, "\u00E3"}
, {"ä", "ä"/* latin small letter a with diaeresis */, "\u00E4"}
, {"å", "å"/* latin small letter a with ring above = latin small letter a ring */, "\u00E5"}
, {"æ", "æ"/* latin small letter ae = latin small ligature ae */, "\u00E6"}
, {"ç", "ç"/* latin small letter c with cedilla */, "\u00E7"}
, {"è", "è"/* latin small letter e with grave */, "\u00E8"}
, {"é", "é"/* latin small letter e with acute */, "\u00E9"}
, {"ê", "ê"/* latin small letter e with circumflex */, "\u00EA"}
, {"ë", "ë"/* latin small letter e with diaeresis */, "\u00EB"}
, {"ì", "ì"/* latin small letter i with grave */, "\u00EC"}
, {"í", "í"/* latin small letter i with acute */, "\u00ED"}
, {"î", "î"/* latin small letter i with circumflex */, "\u00EE"}
, {"ï", "ï"/* latin small letter i with diaeresis */, "\u00EF"}
, {"ð", "ð"/* latin small letter eth */, "\u00F0"}
, {"ñ", "ñ"/* latin small letter n with tilde */, "\u00F1"}
, {"ò", "ò"/* latin small letter o with grave */, "\u00F2"}
, {"ó", "ó"/* latin small letter o with acute */, "\u00F3"}
, {"ô", "ô"/* latin small letter o with circumflex */, "\u00F4"}
, {"õ", "õ"/* latin small letter o with tilde */, "\u00F5"}
, {"ö", "ö"/* latin small letter o with diaeresis */, "\u00F6"}
, {"÷", "÷"/* division sign */, "\u00F7"}
, {"ø", "ø"/* latin small letter o with stroke = latin small letter o slash */, "\u00F8"}
, {"ù", "ù"/* latin small letter u with grave */, "\u00F9"}
, {"ú", "ú"/* latin small letter u with acute */, "\u00FA"}
, {"û", "û"/* latin small letter u with circumflex */, "\u00FB"}
, {"ü", "ü"/* latin small letter u with diaeresis */, "\u00FC"}
, {"ý", "ý"/* latin small letter y with acute */, "\u00FD"}
, {"þ", "þ"/* latin small letter thorn with */, "\u00FE"}
, {"ÿ", "ÿ"/* latin small letter y with diaeresis */, "\u00FF"}
, {"ƒ", "ƒ"/* latin small f with hook = function = florin */, "\u0192"}
/* Greek */
, {"Α", "Α"/* greek capital letter alpha */, "\u0391"}
, {"Β", "Β"/* greek capital letter beta */, "\u0392"}
, {"Γ", "Γ"/* greek capital letter gamma */, "\u0393"}
, {"Δ", "Δ"/* greek capital letter delta */, "\u0394"}
, {"Ε", "Ε"/* greek capital letter epsilon */, "\u0395"}
, {"Ζ", "Ζ"/* greek capital letter zeta */, "\u0396"}
, {"Η", "Η"/* greek capital letter eta */, "\u0397"}
, {"Θ", "Θ"/* greek capital letter theta */, "\u0398"}
, {"Ι", "Ι"/* greek capital letter iota */, "\u0399"}
, {"Κ", "Κ"/* greek capital letter kappa */, "\u039A"}
, {"Λ", "Λ"/* greek capital letter lambda */, "\u039B"}
, {"Μ", "Μ"/* greek capital letter mu */, "\u039C"}
, {"Ν", "Ν"/* greek capital letter nu */, "\u039D"}
, {"Ξ", "Ξ"/* greek capital letter xi */, "\u039E"}
, {"Ο", "Ο"/* greek capital letter omicron */, "\u039F"}
, {"Π", "Π"/* greek capital letter pi */, "\u03A0"}
, {"Ρ", "Ρ"/* greek capital letter rho */, "\u03A1"}
/* there is no Sigmaf and no \u03A2 */
, {"Σ", "Σ"/* greek capital letter sigma */, "\u03A3"}
, {"Τ", "Τ"/* greek capital letter tau */, "\u03A4"}
, {"Υ", "Υ"/* greek capital letter upsilon */, "\u03A5"}
, {"Φ", "Φ"/* greek capital letter phi */, "\u03A6"}
, {"Χ", "Χ"/* greek capital letter chi */, "\u03A7"}
, {"Ψ", "Ψ"/* greek capital letter psi */, "\u03A8"}
, {"Ω", "Ω"/* greek capital letter omega */, "\u03A9"}
, {"α", "α"/* greek small letter alpha */, "\u03B1"}
, {"β", "β"/* greek small letter beta */, "\u03B2"}
, {"γ", "γ"/* greek small letter gamma */, "\u03B3"}
, {"δ", "δ"/* greek small letter delta */, "\u03B4"}
, {"ε", "ε"/* greek small letter epsilon */, "\u03B5"}
, {"ζ", "ζ"/* greek small letter zeta */, "\u03B6"}
, {"η", "η"/* greek small letter eta */, "\u03B7"}
, {"θ", "θ"/* greek small letter theta */, "\u03B8"}
, {"ι", "ι"/* greek small letter iota */, "\u03B9"}
, {"κ", "κ"/* greek small letter kappa */, "\u03BA"}
, {"λ", "λ"/* greek small letter lambda */, "\u03BB"}
, {"μ", "μ"/* greek small letter mu */, "\u03BC"}
, {"ν", "ν"/* greek small letter nu */, "\u03BD"}
, {"ξ", "ξ"/* greek small letter xi */, "\u03BE"}
, {"ο", "ο"/* greek small letter omicron */, "\u03BF"}
, {"π", "π"/* greek small letter pi */, "\u03C0"}
, {"ρ", "ρ"/* greek small letter rho */, "\u03C1"}
, {"ς", "ς"/* greek small letter final sigma */, "\u03C2"}
, {"σ", "σ"/* greek small letter sigma */, "\u03C3"}
, {"τ", "τ"/* greek small letter tau */, "\u03C4"}
, {"υ", "υ"/* greek small letter upsilon */, "\u03C5"}
, {"φ", "φ"/* greek small letter phi */, "\u03C6"}
, {"χ", "χ"/* greek small letter chi */, "\u03C7"}
, {"ψ", "ψ"/* greek small letter psi */, "\u03C8"}
, {"ω", "ω"/* greek small letter omega */, "\u03C9"}
, {"ϑ", "ϑ"/* greek small letter theta symbol */, "\u03D1"}
, {"ϒ", "ϒ"/* greek upsilon with hook symbol */, "\u03D2"}
, {"ϖ", "ϖ"/* greek pi symbol */, "\u03D6"}
/* General Punctuation */
, {"•", "•"/* bullet = black small circle */, "\u2022"}
/* bullet is NOT the same as bullet operator ,"\u2219*/
, {"…", "…"/* horizontal ellipsis = three dot leader */, "\u2026"}
, {"′", "′"/* prime = minutes = feet */, "\u2032"}
, {"″", "″"/* double prime = seconds = inches */, "\u2033"}
, {"‾", "‾"/* overline = spacing overscore */, "\u203E"}
, {"⁄", "⁄"/* fraction slash */, "\u2044"}
/* Letterlike Symbols */
, {"℘", "℘"/* script capital P = power set = Weierstrass p */, "\u2118"}
, {"ℑ", "ℑ"/* blackletter capital I = imaginary part */, "\u2111"}
, {"ℜ", "ℜ"/* blackletter capital R = real part symbol */, "\u211C"}
, {"™", "™"/* trade mark sign */, "\u2122"}
, {"ℵ", "ℵ"/* alef symbol = first transfinite cardinal */, "\u2135"}
/* alef symbol is NOT the same as hebrew letter alef ,"\u05D0"}*/
/* Arrows */
, {"←", "←"/* leftwards arrow */, "\u2190"}
, {"↑", "↑"/* upwards arrow */, "\u2191"}
, {"→", "→"/* rightwards arrow */, "\u2192"}
, {"↓", "↓"/* downwards arrow */, "\u2193"}
, {"↔", "↔"/* left right arrow */, "\u2194"}
, {"↵", "↵"/* downwards arrow with corner leftwards = carriage return */, "\u21B5"}
, {"⇐", "⇐"/* leftwards double arrow */, "\u21D0"}
/* Unicode does not say that lArr is the same as the 'is implied by' arrow but also does not have any other character for that function. So ? lArr can be used for 'is implied by' as ISOtech suggests */
, {"⇑", "⇑"/* upwards double arrow */, "\u21D1"}
, {"⇒", "⇒"/* rightwards double arrow */, "\u21D2"}
/* Unicode does not say this is the 'implies' character but does not have another character with this function so ? rArr can be used for 'implies' as ISOtech suggests */
, {"⇓", "⇓"/* downwards double arrow */, "\u21D3"}
, {"⇔", "⇔"/* left right double arrow */, "\u21D4"}
/* Mathematical Operators */
, {"∀", "∀"/* for all */, "\u2200"}
, {"∂", "∂"/* partial differential */, "\u2202"}
, {"∃", "∃"/* there exists */, "\u2203"}
, {"∅", "∅"/* empty set = null set = diameter */, "\u2205"}
, {"∇", "∇"/* nabla = backward difference */, "\u2207"}
, {"∈", "∈"/* element of */, "\u2208"}
, {"∉", "∉"/* not an element of */, "\u2209"}
, {"∋", "∋"/* contains as member */, "\u220B"}
/* should there be a more memorable name than 'ni'? */
, {"∏", "∏"/* n-ary product = product sign */, "\u220F"}
/* prod is NOT the same character as ,"\u03A0"}*/
, {"∑", "∑"/* n-ary sumation */, "\u2211"}
/* sum is NOT the same character as ,"\u03A3"}*/
, {"−", "−"/* minus sign */, "\u2212"}
, {"∗", "∗"/* asterisk operator */, "\u2217"}
, {"√", "√"/* square root = radical sign */, "\u221A"}
, {"∝", "∝"/* proportional to */, "\u221D"}
, {"∞", "∞"/* infinity */, "\u221E"}
, {"∠", "∠"/* angle */, "\u2220"}
, {"∧", "∧"/* logical and = wedge */, "\u2227"}
, {"∨", "∨"/* logical or = vee */, "\u2228"}
, {"∩", "∩"/* intersection = cap */, "\u2229"}
, {"∪", "∪"/* union = cup */, "\u222A"}
, {"∫", "∫"/* integral */, "\u222B"}
, {"∴", "∴"/* therefore */, "\u2234"}
, {"∼", "∼"/* tilde operator = varies with = similar to */, "\u223C"}
/* tilde operator is NOT the same character as the tilde ,"\u007E"}*/
, {"≅", "≅"/* approximately equal to */, "\u2245"}
, {"≈", "≈"/* almost equal to = asymptotic to */, "\u2248"}
, {"≠", "≠"/* not equal to */, "\u2260"}
, {"≡", "≡"/* identical to */, "\u2261"}
, {"≤", "≤"/* less-than or equal to */, "\u2264"}
, {"≥", "≥"/* greater-than or equal to */, "\u2265"}
, {"⊂", "⊂"/* subset of */, "\u2282"}
, {"⊃", "⊃"/* superset of */, "\u2283"}
/* note that nsup 'not a superset of ,"\u2283"}*/
, {"⊆", "⊆"/* subset of or equal to */, "\u2286"}
, {"⊇", "⊇"/* superset of or equal to */, "\u2287"}
, {"⊕", "⊕"/* circled plus = direct sum */, "\u2295"}
, {"⊗", "⊗"/* circled times = vector product */, "\u2297"}
, {"⊥", "⊥"/* up tack = orthogonal to = perpendicular */, "\u22A5"}
, {"⋅", "⋅"/* dot operator */, "\u22C5"}
/* dot operator is NOT the same character as ,"\u00B7"}
/* Miscellaneous Technical */
, {"⌈", "⌈"/* left ceiling = apl upstile */, "\u2308"}
, {"⌉", "⌉"/* right ceiling */, "\u2309"}
, {"⌊", "⌊"/* left floor = apl downstile */, "\u230A"}
, {"⌋", "⌋"/* right floor */, "\u230B"}
, {"⟨", "〈"/* left-pointing angle bracket = bra */, "\u2329"}
/* lang is NOT the same character as ,"\u003C"}*/
, {"⟩", "〉"/* right-pointing angle bracket = ket */, "\u232A"}
/* rang is NOT the same character as ,"\u003E"}*/
/* Geometric Shapes */
, {"◊", "◊"/* lozenge */, "\u25CA"}
/* Miscellaneous Symbols */
, {"♠", "♠"/* black spade suit */, "\u2660"}
/* black here seems to mean filled as opposed to hollow */
, {"♣", "♣"/* black club suit = shamrock */, "\u2663"}
, {"♥", "♥"/* black heart suit = valentine */, "\u2665"}
, {"♦", "♦"/* black diamond suit */, "\u2666"}
, {""", """ /* quotation mark = APL quote */, "\""}
, {"&", "&" /* ampersand */, "\u0026"}
, {"<", "<" /* less-than sign */, "\u003C"}
, {">", ">" /* greater-than sign */, "\u003E"}
/* Latin Extended-A */
, {"Œ", "Œ" /* latin capital ligature OE */, "\u0152"}
, {"œ", "œ" /* latin small ligature oe */, "\u0153"}
/* ligature is a misnomer this is a separate character in some languages */
, {"Š", "Š" /* latin capital letter S with caron */, "\u0160"}
, {"š", "š" /* latin small letter s with caron */, "\u0161"}
, {"Ÿ", "Ÿ" /* latin capital letter Y with diaeresis */, "\u0178"}
/* Spacing Modifier Letters */
, {"ˆ", "ˆ" /* modifier letter circumflex accent */, "\u02C6"}
, {"˜", "˜" /* small tilde */, "\u02DC"}
/* General Punctuation */
, {" ", " "/* en space */, "\u2002"}
, {" ", " "/* em space */, "\u2003"}
, {" ", " "/* thin space */, "\u2009"}
, {"‌", "‌"/* zero width non-joiner */, "\u200C"}
, {"‍", "‍"/* zero width joiner */, "\u200D"}
, {"‎", "‎"/* left-to-right mark */, "\u200E"}
, {"‏", "‏"/* right-to-left mark */, "\u200F"}
, {"–", "–"/* en dash */, "\u2013"}
, {"—", "—"/* em dash */, "\u2014"}
, {"‘", "‘"/* left single quotation mark */, "\u2018"}
, {"’", "’"/* right single quotation mark */, "\u2019"}
, {"‚", "‚"/* single low-9 quotation mark */, "\u201A"}
, {"“", "“"/* left double quotation mark */, "\u201C"}
, {"”", "”"/* right double quotation mark */, "\u201D"}
, {"„", "„"/* double low-9 quotation mark */, "\u201E"}
, {"†", "†"/* dagger */, "\u2020"}
, {"‡", "‡"/* double dagger */, "\u2021"}
, {"‰", "‰"/* per mille sign */, "\u2030"}
, {"‹", "‹"/* single left-pointing angle quotation mark */, "\u2039"}
/* lsaquo is proposed but not yet ISO standardized */
, {"›", "›"/* single right-pointing angle quotation mark */, "\u203A"}
/* rsaquo is proposed but not yet ISO standardized */
, {"€", "€" /* euro sign */, "\u20AC"}};
for (String[] entity : entities) {
entityEscapeMap.put(entity[2], entity[0]);
escapeEntityMap.put(entity[0], entity[2]);
escapeEntityMap.put(entity[1], entity[2]);
}
}
}
| Java |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.http.HttpAuthException;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskFeedback;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
//登录页面需要个性化的菜单绑定, 不直接继承 BaseActivity
public class LoginActivity extends Activity {
private static final String TAG = "LoginActivity";
private static final String SIS_RUNNING_KEY = "running";
private String mUsername;
private String mPassword;
// Views.
private EditText mUsernameEdit;
private EditText mPasswordEdit;
private TextView mProgressText;
private Button mSigninButton;
private ProgressDialog dialog;
// Preferences.
private SharedPreferences mPreferences;
// Tasks.
private GenericTask mLoginTask;
private User user;
private TaskListener mLoginTaskListener = new TaskAdapter(){
@Override
public void onPreExecute(GenericTask task) {
onLoginBegin();
}
@Override
public void onProgressUpdate(GenericTask task, Object param) {
updateProgress((String)param);
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
onLoginSuccess();
} else {
onLoginFailure(((LoginTask)task).getMsg());
}
}
@Override
public String getName() {
// TODO Auto-generated method stub
return "Login";
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
// No Title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
requestWindowFeature(Window.FEATURE_PROGRESS);
mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
setContentView(R.layout.login);
// TextView中嵌入HTML链接
TextView registerLink = (TextView) findViewById(R.id.register_link);
registerLink.setMovementMethod(LinkMovementMethod.getInstance());
mUsernameEdit = (EditText) findViewById(R.id.username_edit);
mPasswordEdit = (EditText) findViewById(R.id.password_edit);
// mUsernameEdit.setOnKeyListener(enterKeyHandler);
mPasswordEdit.setOnKeyListener(enterKeyHandler);
mProgressText = (TextView) findViewById(R.id.progress_text);
mProgressText.setFreezesText(true);
mSigninButton = (Button) findViewById(R.id.signin_button);
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(SIS_RUNNING_KEY)) {
if (savedInstanceState.getBoolean(SIS_RUNNING_KEY)) {
Log.d(TAG, "Was previously logging in. Restart action.");
doLogin();
}
}
}
mSigninButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doLogin();
}
});
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestory");
if (mLoginTask != null && mLoginTask.getStatus() == GenericTask.Status.RUNNING) {
mLoginTask.cancel(true);
}
// dismiss dialog before destroy
// to avoid android.view.WindowLeaked Exception
TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE,
LoginActivity.this).cancel();
super.onDestroy();
}
@Override
protected void onStop() {
Log.d(TAG, "onStop");
// TODO Auto-generated method stub
super.onStop();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mLoginTask != null
&& mLoginTask.getStatus() == GenericTask.Status.RUNNING) {
// If the task was running, want to start it anew when the
// Activity restarts.
// This addresses the case where you user changes orientation
// in the middle of execution.
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
// UI helpers.
private void updateProgress(String progress) {
mProgressText.setText(progress);
}
private void enableLogin() {
mUsernameEdit.setEnabled(true);
mPasswordEdit.setEnabled(true);
mSigninButton.setEnabled(true);
}
private void disableLogin() {
mUsernameEdit.setEnabled(false);
mPasswordEdit.setEnabled(false);
mSigninButton.setEnabled(false);
}
// Login task.
private void doLogin() {
mUsername = mUsernameEdit.getText().toString();
mPassword = mPasswordEdit.getText().toString();
if (mLoginTask != null && mLoginTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
if (!TextUtils.isEmpty(mUsername) & !TextUtils.isEmpty(mPassword) ) {
mLoginTask = new LoginTask();
mLoginTask.setListener(mLoginTaskListener);
TaskParams params = new TaskParams();
params.put("username", mUsername);
params.put("password", mPassword);
mLoginTask.execute(params);
} else {
updateProgress(getString(R.string.login_status_null_username_or_password));
}
}
}
private void onLoginBegin() {
disableLogin();
TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE,
LoginActivity.this).start(
getString(R.string.login_status_logging_in));
}
private void onLoginSuccess() {
TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE,
LoginActivity.this).success("");
updateProgress("");
mUsernameEdit.setText("");
mPasswordEdit.setText("");
Log.d(TAG, "Storing credentials.");
TwitterApplication.mApi.setCredentials(mUsername, mPassword);
Intent intent = getIntent().getParcelableExtra(Intent.EXTRA_INTENT);
String action = intent.getAction();
if (intent.getAction() == null || !Intent.ACTION_SEND.equals(action)) {
// We only want to reuse the intent if it was photo send.
// Or else default to the main activity.
intent = new Intent(this, TwitterActivity.class);
}
//发送消息给widget
Intent reflogin = new Intent(this.getBaseContext(), FanfouWidget.class);
reflogin.setAction("android.appwidget.action.APPWIDGET_UPDATE");
PendingIntent l = PendingIntent.getBroadcast(this.getBaseContext(), 0, reflogin,
PendingIntent.FLAG_UPDATE_CURRENT);
try {
l.send();
} catch (CanceledException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
startActivity(intent);
finish();
}
private void onLoginFailure(String reason) {
TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE,
LoginActivity.this).failed(reason);
enableLogin();
}
private class LoginTask extends GenericTask {
private String msg = getString(R.string.login_status_failure);
public String getMsg(){
return msg;
}
@Override
protected TaskResult _doInBackground(TaskParams...params) {
TaskParams param = params[0];
publishProgress(getString(R.string.login_status_logging_in) + "...");
try {
String username = param.getString("username");
String password = param.getString("password");
user= TwitterApplication.mApi.login(username, password);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
//TODO:确切的应该从HttpException中返回的消息中获取错误信息
//Throwable cause = e.getCause(); // Maybe null
// if (cause instanceof HttpAuthException) {
if (e instanceof HttpAuthException) {
// Invalid userName/password
msg = getString(R.string.login_status_invalid_username_or_password);
} else {
msg = getString(R.string.login_status_network_or_connection_error);
}
publishProgress(msg);
return TaskResult.FAILED;
}
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString(Preferences.USERNAME_KEY, mUsername);
editor.putString(Preferences.PASSWORD_KEY,
encryptPassword(mPassword));
// add 存储当前用户的id
editor.putString(Preferences.CURRENT_USER_ID, user.getId());
editor.commit();
return TaskResult.OK;
}
}
private View.OnKeyListener enterKeyHandler = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER
|| keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
if (event.getAction() == KeyEvent.ACTION_UP) {
doLogin();
}
return true;
}
return false;
}
};
public static String encryptPassword(String password) {
//return Base64.encodeToString(password.getBytes(), Base64.DEFAULT);
return password;
}
public static String decryptPassword(String password) {
//return new String(Base64.decode(password, Base64.DEFAULT));
return password;
}
} | Java |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity;
//TODO: 数据来源换成 getFavorites()
public class FavoritesActivity extends TwitterCursorBaseActivity {
private static final String TAG = "FavoritesActivity";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FAVORITES";
private static final String USER_ID = "userid";
private static final String USER_NAME = "userName";
private static final int DIALOG_WRITE_ID = 0;
private String userId = null;
private String userName = null;
public static Intent createIntent(String userId, String userName) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(USER_ID, userId);
intent.putExtra(USER_NAME, userName);
return intent;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)){
mNavbar.setHeaderTitle(getActivityTitle());
return true;
}else{
return false;
}
}
public static Intent createNewTaskIntent(String userId, String userName) {
Intent intent = createIntent(userId, userName);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
// Menu.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
protected Cursor fetchMessages() {
// TODO Auto-generated method stub
return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_FAVORITE);
}
@Override
protected String getActivityTitle() {
// TODO Auto-generated method stub
String template = getString(R.string.page_title_favorites);
String who;
if (getUserId().equals(TwitterApplication.getMyselfId())){
who = "我";
}else{
who = getUserName();
}
return MessageFormat.format(template, who);
}
@Override
protected void markAllRead() {
// TODO Auto-generated method stub
getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_FAVORITE);
}
// hasRetrieveListTask interface
@Override
public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) {
return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_FAVORITE, isUnread);
}
@Override
public String fetchMaxId() {
return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_FAVORITE);
}
@Override
public List<Status> getMessageSinceId(String maxId) throws HttpException {
if (maxId != null){
return getApi().getFavorites(getUserId(), new Paging(maxId));
}else{
return getApi().getFavorites(getUserId());
}
}
@Override
public String fetchMinId() {
return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_FAVORITE);
}
@Override
public List<Status> getMoreMessageFromId(String minId)
throws HttpException {
Paging paging = new Paging(1, 20);
paging.setMaxId(minId);
return getApi().getFavorites(getUserId(), paging);
}
@Override
public int getDatabaseType() {
return StatusTable.TYPE_FAVORITE;
}
@Override
public String getUserId() {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null){
userId = extras.getString(USER_ID);
} else {
userId = TwitterApplication.getMyselfId();
}
return userId;
}
public String getUserName(){
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null){
userName = extras.getString(USER_NAME);
} else {
userName = TwitterApplication.getMyselfName();
}
return userName;
}
} | Java |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.HttpRefusedException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.Refreshable;
import com.ch_linghu.fanfoudroid.ui.base.TwitterListBaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.MyListView;
import com.ch_linghu.fanfoudroid.ui.module.TweetArrayAdapter;
public class UserTimelineActivity extends TwitterListBaseActivity implements
MyListView.OnNeedMoreListener, Refreshable {
private static final String TAG = UserTimelineActivity.class
.getSimpleName();
private Feedback mFeedback;
private static final String EXTRA_USERID = "userID";
private static final String EXTRA_NAME_SHOW = "showName";
private static final String SIS_RUNNING_KEY = "running";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.USERTIMELINE";
public static Intent createIntent(String userID, String showName) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.putExtra(EXTRA_USERID, userID);
intent.putExtra(EXTRA_NAME_SHOW, showName);
return intent;
}
// State.
private User mUser;
private String mUserID;
private String mShowName;
private ArrayList<Tweet> mTweets;
private int mNextPage = 1;
// Views.
private TextView headerView;
private TextView footerView;
private MyListView mTweetList;
// 记录服务器拒绝访问的信息
private String msg;
private static final int LOADINGFLAG = 1;
private static final int SUCCESSFLAG = 2;
private static final int NETWORKERRORFLAG = 3;
private static final int AUTHERRORFLAG = 4;
private TweetArrayAdapter mAdapter;
// Tasks.
private GenericTask mRetrieveTask;
private GenericTask mLoadMoreTask;
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
onRetrieveBegin();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
mFeedback.failed("登录失败, 请重新登录.");
updateHeader(AUTHERRORFLAG);
return;
} else if (result == TaskResult.OK) {
updateHeader(SUCCESSFLAG);
updateFooter(SUCCESSFLAG);
draw();
goTop();
} else if (result == TaskResult.IO_ERROR) {
mFeedback.failed("更新失败.");
updateHeader(NETWORKERRORFLAG);
}
mFeedback.success("");
}
@Override
public String getName() {
return "UserTimelineRetrieve";
}
};
private TaskListener mLoadMoreTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
onLoadMoreBegin();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
mFeedback.success("");
updateFooter(SUCCESSFLAG);
draw();
}
}
@Override
public String getName() {
return "UserTimelineLoadMoreTask";
}
};
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "_onCreate()...");
if (super._onCreate(savedInstanceState)) {
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
Intent intent = getIntent();
// get user id
mUserID = intent.getStringExtra(EXTRA_USERID);
// show username in title
mShowName = intent.getStringExtra(EXTRA_NAME_SHOW);
// Set header title
mNavbar.setHeaderTitle("@" + mShowName);
boolean wasRunning = isTrue(savedInstanceState, SIS_RUNNING_KEY);
// 此处要求mTweets不为空,最好确保profile页面消息为0时不能进入这个页面
if (!mTweets.isEmpty() && !wasRunning) {
updateHeader(SUCCESSFLAG);
draw();
} else {
doRetrieve();
}
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
mRetrieveTask.cancel(true);
}
if (mLoadMoreTask != null
&& mLoadMoreTask.getStatus() == GenericTask.Status.RUNNING) {
mLoadMoreTask.cancel(true);
}
super.onDestroy();
}
@Override
protected void draw() {
mAdapter.refresh(mTweets);
}
public void goTop() {
Log.d(TAG, "goTop.");
mTweetList.setSelection(1);
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new UserTimelineRetrieveTask();
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute();
}
}
private void doLoadMore() {
Log.d(TAG, "Attempting load more.");
if (mLoadMoreTask != null
&& mLoadMoreTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mLoadMoreTask = new UserTimelineLoadMoreTask();
mLoadMoreTask.setListener(mLoadMoreTaskListener);
mLoadMoreTask.execute();
}
}
private void onRetrieveBegin() {
mFeedback.start("");
// 更新查询状态显示
updateHeader(LOADINGFLAG);
updateFooter(LOADINGFLAG);
}
private void onLoadMoreBegin() {
mFeedback.start("");
}
private class UserTimelineRetrieveTask extends GenericTask {
ArrayList<Tweet> mTweets = new ArrayList<Tweet>();
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
statusList = getApi().getUserTimeline(mUserID,
new Paging(mNextPage));
mUser = getApi().showUser(mUserID);
mFeedback.update(60);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
Throwable cause = e.getCause();
if (cause instanceof HttpRefusedException) {
// AUTH ERROR
msg = ((HttpRefusedException) cause).getError()
.getMessage();
return TaskResult.AUTH_ERROR;
} else {
return TaskResult.IO_ERROR;
}
}
mFeedback.update(100 - (int)Math.floor(statusList.size()*2)); // 60~100
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet;
tweet = Tweet.create(status);
mTweets.add(tweet);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
addTweets(mTweets);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
return TaskResult.OK;
}
}
private class UserTimelineLoadMoreTask extends GenericTask {
ArrayList<Tweet> mTweets = new ArrayList<Tweet>();
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList;
try {
statusList = getApi().getUserTimeline(mUserID,
new Paging(mNextPage));
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
Throwable cause = e.getCause();
if (cause instanceof HttpRefusedException) {
// AUTH ERROR
msg = ((HttpRefusedException) cause).getError()
.getMessage();
return TaskResult.AUTH_ERROR;
} else {
return TaskResult.IO_ERROR;
}
}
for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Tweet tweet;
tweet = Tweet.create(status);
mTweets.add(tweet);
}
if (isCancelled()) {
return TaskResult.CANCELLED;
}
addTweets(mTweets);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
return TaskResult.OK;
}
}
@Override
public void needMore() {
if (!isLastPage()) {
doLoadMore();
}
}
public boolean isLastPage() {
return mNextPage == -1;
}
private synchronized void addTweets(ArrayList<Tweet> tweets) {
// do more时没有更多时
if (tweets.size() == 0) {
mNextPage = -1;
return;
}
mTweets.addAll(tweets);
++mNextPage;
}
@Override
protected String getActivityTitle() {
return "@" + mShowName;
}
@Override
protected Tweet getContextItemTweet(int position) {
if (position >= 1 && position <= mAdapter.getCount()) {
return (Tweet) mAdapter.getItem(position - 1);
} else {
return null;
}
}
@Override
protected int getLayoutId() {
return R.layout.user_timeline;
}
@Override
protected com.ch_linghu.fanfoudroid.ui.module.TweetAdapter getTweetAdapter() {
return mAdapter;
}
@Override
protected ListView getTweetList() {
return mTweetList;
}
@Override
protected void setupState() {
mTweets = new ArrayList<Tweet>();
mAdapter = new TweetArrayAdapter(this);
mTweetList = (MyListView) findViewById(R.id.tweet_list);
// Add Header to ListView
headerView = (TextView) TextView.inflate(this,
R.layout.user_timeline_header, null);
mTweetList.addHeaderView(headerView);
// Add Footer to ListView
footerView = (TextView) TextView.inflate(this,
R.layout.user_timeline_footer, null);
mTweetList.addFooterView(footerView);
mTweetList.setAdapter(mAdapter);
mTweetList.setOnNeedMoreListener(this);
}
@Override
protected void updateTweet(Tweet tweet) {
// 该方法作用?
}
@Override
protected boolean useBasicMenu() {
return true;
}
private void updateHeader(int flag) {
if (flag == LOADINGFLAG) {
// 重新刷新页面时从第一页开始获取数据 --- phoenix
mNextPage = 1;
mTweets.clear();
mAdapter.refresh(mTweets);
headerView.setText(getResources()
.getString(R.string.search_loading));
}
if (flag == SUCCESSFLAG) {
headerView.setText(getResources().getString(
R.string.user_query_status_success));
}
if (flag == NETWORKERRORFLAG) {
headerView.setText(getResources().getString(
R.string.login_status_network_or_connection_error));
}
if (flag == AUTHERRORFLAG) {
headerView.setText(msg);
}
}
private void updateFooter(int flag) {
if (flag == LOADINGFLAG) {
footerView.setText("该用户总共?条消息");
}
if (flag == SUCCESSFLAG) {
footerView.setText("该用户总共" + mUser.getStatusesCount() + "条消息,当前显示"
+ mTweets.size() + "条。");
}
}
} | Java |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.database.Cursor;
import android.os.Bundle;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity;
/**
* 随便看看
*
* @author jmx
*
*/
public class BrowseActivity extends TwitterCursorBaseActivity {
private static final String TAG = "BrowseActivity";
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)) {
mNavbar.setHeaderTitle(getActivityTitle());
getTweetList().removeFooterView(mListFooter); // 随便看看没有获取更多功能
return true;
} else {
return false;
}
}
@Override
protected String getActivityTitle() {
return getResources().getString(R.string.page_title_browse);
}
@Override
public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) {
return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_BROWSE,
isUnread);
}
@Override
public String fetchMaxId() {
return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_BROWSE);
}
@Override
protected Cursor fetchMessages() {
return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_BROWSE);
}
@Override
public List<Status> getMessageSinceId(String maxId) throws HttpException {
return getApi().getPublicTimeline();
}
@Override
protected void markAllRead() {
getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_BROWSE);
}
@Override
public String fetchMinId() {
// 随便看看没有获取更多的功能
return null;
}
@Override
public List<Status> getMoreMessageFromId(String minId) throws HttpException {
// 随便看看没有获取更多的功能
return null;
}
@Override
public int getDatabaseType() {
return StatusTable.TYPE_BROWSE;
}
@Override
public String getUserId() {
return TwitterApplication.getMyselfId();
}
}
| Java |
package com.ch_linghu.fanfoudroid.task;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.ui.base.WithHeaderActivity;
public abstract class TaskFeedback {
private static TaskFeedback _instance = null;
public static final int DIALOG_MODE = 0x01;
public static final int REFRESH_MODE = 0x02;
public static final int PROGRESS_MODE = 0x03;
public static TaskFeedback getInstance(int type, Context context) {
switch (type) {
case DIALOG_MODE:
_instance = DialogFeedback.getInstance();
break;
case REFRESH_MODE:
_instance = RefreshAnimationFeedback.getInstance();
break;
case PROGRESS_MODE:
_instance = ProgressBarFeedback.getInstance();
}
_instance.setContext(context);
return _instance;
}
protected Context _context;
protected void setContext(Context context) {
_context = context;
}
public Context getContent() {
return _context;
}
// default do nothing
public void start(String prompt) {};
public void cancel() {};
public void success(String prompt) {};
public void success() { success(""); };
public void failed(String prompt) {};
public void showProgress(int progress) {};
}
/**
*
*/
class DialogFeedback extends TaskFeedback {
private static DialogFeedback _instance = null;
public static DialogFeedback getInstance() {
if (_instance == null) {
_instance = new DialogFeedback();
}
return _instance;
}
private ProgressDialog _dialog = null;
@Override
public void cancel() {
if (_dialog != null) {
_dialog.dismiss();
}
}
@Override
public void failed(String prompt) {
if (_dialog != null) {
_dialog.dismiss();
}
Toast toast = Toast.makeText(_context, prompt, Toast.LENGTH_LONG);
toast.show();
}
@Override
public void start(String prompt) {
_dialog = ProgressDialog.show(_context, "", prompt, true);
_dialog.setCancelable(true);
}
@Override
public void success(String prompt) {
if (_dialog != null) {
_dialog.dismiss();
}
}
}
/**
*
*/
class RefreshAnimationFeedback extends TaskFeedback {
private static RefreshAnimationFeedback _instance = null;
public static RefreshAnimationFeedback getInstance() {
if (_instance == null) {
_instance = new RefreshAnimationFeedback();
}
return _instance;
}
private WithHeaderActivity _activity;
@Override
protected void setContext(Context context) {
super.setContext(context);
_activity = (WithHeaderActivity) context;
}
@Override
public void cancel() {
_activity.setRefreshAnimation(false);
}
@Override
public void failed(String prompt) {
_activity.setRefreshAnimation(false);
Toast toast = Toast.makeText(_context, prompt, Toast.LENGTH_LONG);
toast.show();
}
@Override
public void start(String prompt) {
_activity.setRefreshAnimation(true);
}
@Override
public void success(String prompt) {
_activity.setRefreshAnimation(false);
}
}
/**
*
*/
class ProgressBarFeedback extends TaskFeedback {
private static ProgressBarFeedback _instance = null;
public static ProgressBarFeedback getInstance() {
if (_instance == null) {
_instance = new ProgressBarFeedback();
}
return _instance;
}
private WithHeaderActivity _activity;
@Override
protected void setContext(Context context) {
super.setContext(context);
_activity = (WithHeaderActivity) context;
}
@Override
public void cancel() {
_activity.setGlobalProgress(0);
}
@Override
public void failed(String prompt) {
cancel();
Toast toast = Toast.makeText(_context, prompt, Toast.LENGTH_LONG);
toast.show();
}
@Override
public void start(String prompt) {
_activity.setGlobalProgress(10);
}
@Override
public void success(String prompt) {
Log.d("LDS", "ON SUCCESS");
_activity.setGlobalProgress(0);
}
@Override
public void showProgress(int progress) {
_activity.setGlobalProgress(progress);
}
// mProgress.setIndeterminate(true);
}
| Java |
package com.ch_linghu.fanfoudroid.task;
import java.util.HashMap;
import org.json.JSONException;
import com.ch_linghu.fanfoudroid.http.HttpException;
/**
* 暂未使用,待观察是否今后需要此类
* @author lds
*
*/
public class TaskParams {
private HashMap<String, Object> params = null;
public TaskParams() {
params = new HashMap<String, Object>();
}
public TaskParams(String key, Object value) {
this();
put(key, value);
}
public void put(String key, Object value) {
params.put(key, value);
}
public Object get(String key) {
return params.get(key);
}
/**
* Get the boolean value associated with a key.
*
* @param key A key string.
* @return The truth.
* @throws HttpException
* if the value is not a Boolean or the String "true" or "false".
*/
public boolean getBoolean(String key) throws HttpException {
Object object = get(key);
if (object.equals(Boolean.FALSE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("false"))) {
return false;
} else if (object.equals(Boolean.TRUE) ||
(object instanceof String &&
((String)object).equalsIgnoreCase("true"))) {
return true;
}
throw new HttpException(key + " is not a Boolean.");
}
/**
* Get the double value associated with a key.
* @param key A key string.
* @return The numeric value.
* @throws HttpException if the key is not found or
* if the value is not a Number object and cannot be converted to a number.
*/
public double getDouble(String key) throws HttpException {
Object object = get(key);
try {
return object instanceof Number ?
((Number)object).doubleValue() :
Double.parseDouble((String)object);
} catch (Exception e) {
throw new HttpException(key + " is not a number.");
}
}
/**
* Get the int value associated with a key.
*
* @param key A key string.
* @return The integer value.
* @throws HttpException if the key is not found or if the value cannot
* be converted to an integer.
*/
public int getInt(String key) throws HttpException {
Object object = get(key);
try {
return object instanceof Number ?
((Number)object).intValue() :
Integer.parseInt((String)object);
} catch (Exception e) {
throw new HttpException(key + " is not an int.");
}
}
/**
* Get the string associated with a key.
*
* @param key A key string.
* @return A string which is the value.
* @throws JSONException if the key is not found.
*/
public String getString(String key) throws HttpException {
Object object = get(key);
return object == null ? null : object.toString();
}
/**
* Determine if the JSONObject contains a specific key.
* @param key A key string.
* @return true if the key exists in the JSONObject.
*/
public boolean has(String key) {
return this.params.containsKey(key);
}
}
| Java |
package com.ch_linghu.fanfoudroid.task;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
public class TweetCommonTask {
public static class DeleteTask extends GenericTask{
public static final String TAG="DeleteTask";
private BaseActivity activity;
public DeleteTask(BaseActivity activity){
this.activity = activity;
}
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
try {
String id = param.getString("id");
com.ch_linghu.fanfoudroid.fanfou.Status status = null;
status = activity.getApi().destroyStatus(id);
// 对所有相关表的对应消息都进行删除(如果存在的话)
activity.getDb().deleteTweet(status.getId(), "", -1);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
public static class FavoriteTask extends GenericTask{
private static final String TAG = "FavoriteTask";
private BaseActivity activity;
public static final String TYPE_ADD = "add";
public static final String TYPE_DEL = "del";
private String type;
public String getType(){
return type;
}
public FavoriteTask(BaseActivity activity){
this.activity = activity;
}
@Override
protected TaskResult _doInBackground(TaskParams...params){
TaskParams param = params[0];
try {
String action = param.getString("action");
String id = param.getString("id");
com.ch_linghu.fanfoudroid.fanfou.Status status = null;
if (action.equals(TYPE_ADD)) {
status = activity.getApi().createFavorite(id);
activity.getDb().setFavorited(id, "true");
type = TYPE_ADD;
} else {
status = activity.getApi().destroyFavorite(id);
activity.getDb().setFavorited(id, "false");
type = TYPE_DEL;
}
Tweet tweet = Tweet.create(status);
// if (!Utils.isEmpty(tweet.profileImageUrl)) {
// // Fetch image to cache.
// try {
// activity.getImageManager().put(tweet.profileImageUrl);
// } catch (IOException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
if(action.equals(TYPE_DEL)){
activity.getDb().deleteTweet(tweet.id, TwitterApplication.getMyselfId(), StatusTable.TYPE_FAVORITE);
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
// public static class UserTask extends GenericTask{
//
// @Override
// protected TaskResult _doInBackground(TaskParams... params) {
// // TODO Auto-generated method stub
// return null;
// }
//
// }
}
| Java |
package com.ch_linghu.fanfoudroid.task;
public interface TaskListener {
String getName();
void onPreExecute(GenericTask task);
void onPostExecute(GenericTask task, TaskResult result);
void onProgressUpdate(GenericTask task, Object param);
void onCancelled(GenericTask task);
}
| Java |
package com.ch_linghu.fanfoudroid.task;
import java.util.Observable;
import java.util.Observer;
import android.util.Log;
public class TaskManager extends Observable {
private static final String TAG = "TaskManager";
public static final Integer CANCEL_ALL = 1;
public void cancelAll() {
Log.d(TAG, "All task Cancelled.");
setChanged();
notifyObservers(CANCEL_ALL);
}
public void addTask(Observer task) {
super.addObserver(task);
}
} | Java |
package com.ch_linghu.fanfoudroid.task;
import java.util.Observable;
import java.util.Observer;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
public abstract class GenericTask extends
AsyncTask<TaskParams, Object, TaskResult> implements Observer {
private static final String TAG = "TaskManager";
private TaskListener mListener = null;
private Feedback mFeedback = null;
private boolean isCancelable = true;
abstract protected TaskResult _doInBackground(TaskParams... params);
public void setListener(TaskListener taskListener) {
mListener = taskListener;
}
public TaskListener getListener() {
return mListener;
}
public void doPublishProgress(Object... values) {
super.publishProgress(values);
}
@Override
protected void onCancelled() {
super.onCancelled();
if (mListener != null) {
mListener.onCancelled(this);
}
Log.d(TAG, mListener.getName() + " has been Cancelled.");
Toast.makeText(TwitterApplication.mContext, mListener.getName()
+ " has been cancelled", Toast.LENGTH_SHORT);
}
@Override
protected void onPostExecute(TaskResult result) {
super.onPostExecute(result);
if (mListener != null) {
mListener.onPostExecute(this, result);
}
if (mFeedback != null) {
mFeedback.success("");
}
/*
Toast.makeText(TwitterApplication.mContext, mListener.getName()
+ " completed", Toast.LENGTH_SHORT);
*/
}
@Override
protected void onPreExecute() {
super.onPreExecute();
if (mListener != null) {
mListener.onPreExecute(this);
}
if (mFeedback != null) {
mFeedback.start("");
}
}
@Override
protected void onProgressUpdate(Object... values) {
super.onProgressUpdate(values);
if (mListener != null) {
if (values != null && values.length > 0) {
mListener.onProgressUpdate(this, values[0]);
}
}
if (mFeedback != null) {
mFeedback.update(values[0]);
}
}
@Override
protected TaskResult doInBackground(TaskParams... params) {
TaskResult result = _doInBackground(params);
if (mFeedback != null) {
mFeedback.update(99);
}
return result;
}
public void update(Observable o, Object arg) {
if (TaskManager.CANCEL_ALL == (Integer) arg && isCancelable) {
if (getStatus() == GenericTask.Status.RUNNING) {
cancel(true);
}
}
}
public void setCancelable(boolean flag) {
isCancelable = flag;
}
public void setFeedback(Feedback feedback) {
mFeedback = feedback;
}
}
| Java |
package com.ch_linghu.fanfoudroid.task;
public abstract class TaskAdapter implements TaskListener {
public abstract String getName();
public void onPreExecute(GenericTask task) {};
public void onPostExecute(GenericTask task, TaskResult result) {};
public void onProgressUpdate(GenericTask task, Object param) {};
public void onCancelled(GenericTask task) {};
}
| Java |
package com.ch_linghu.fanfoudroid.task;
public enum TaskResult {
OK,
FAILED,
CANCELLED,
NOT_FOLLOWED_ERROR,
IO_ERROR,
AUTH_ERROR
} | Java |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.util.Log;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.http.HttpClient;
import com.ch_linghu.fanfoudroid.ui.module.MyTextView;
public class PreferencesActivity extends PreferenceActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//禁止横屏
if (TwitterApplication.mPref.getBoolean(
Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
// TODO: is this a hack?
setResult(RESULT_OK);
addPreferencesFromResource(R.xml.preferences);
}
@Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
Preference preference) {
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if ( key.equalsIgnoreCase(Preferences.NETWORK_TYPE) ) {
HttpClient httpClient = TwitterApplication.mApi.getHttpClient();
String type = sharedPreferences.getString(Preferences.NETWORK_TYPE, "");
if (type.equalsIgnoreCase(getString(R.string.pref_network_type_cmwap))) {
Log.d("LDS", "Set proxy for cmwap mode.");
httpClient.setProxy("10.0.0.172", 80, "http");
} else {
Log.d("LDS", "No proxy.");
httpClient.removeProxy();
}
} else if ( key.equalsIgnoreCase(Preferences.UI_FONT_SIZE)) {
MyTextView.setFontSizeChanged(true);
}
}
}
| Java |
package com.ch_linghu.fanfoudroid.db;
/**
* All information of status table
*
*/
public final class StatusTablesInfo {
} | Java |
package com.ch_linghu.fanfoudroid.db;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import com.ch_linghu.fanfoudroid.data.User;
public final class UserInfoTable implements BaseColumns {
public static final String TAG = "UserInfoTable";
public static final String TABLE_NAME = "userinfo";
public static final String FIELD_USER_NAME = "name";
public static final String FIELD_USER_SCREEN_NAME = "screen_name";
public static final String FIELD_LOCALTION = "location";
public static final String FIELD_DESCRIPTION = "description";
public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url";
public static final String FIELD_URL = "url";
public static final String FIELD_PROTECTED = "protected";
public static final String FIELD_FOLLOWERS_COUNT = "followers_count";
public static final String FIELD_FRIENDS_COUNT = "friends_count";
public static final String FIELD_FAVORITES_COUNT = "favourites_count";
public static final String FIELD_STATUSES_COUNT = "statuses_count";
public static final String FIELD_LAST_STATUS = "last_status";
public static final String FIELD_CREATED_AT = "created_at";
public static final String FIELD_FOLLOWING = "following";
public static final String FIELD_FOLLOWER_IDS="follower_ids";
public static final String[] TABLE_COLUMNS = new String[] { _ID,
FIELD_USER_NAME, FIELD_USER_SCREEN_NAME,
FIELD_LOCALTION, FIELD_DESCRIPTION,
FIELD_PROFILE_IMAGE_URL, FIELD_URL, FIELD_PROTECTED,
FIELD_FOLLOWERS_COUNT, FIELD_FRIENDS_COUNT,
FIELD_FAVORITES_COUNT, FIELD_STATUSES_COUNT,
FIELD_LAST_STATUS, FIELD_CREATED_AT, FIELD_FOLLOWING};
public static final String CREATE_TABLE = "create table "
+ TABLE_NAME + " ("
+ _ID + " text primary key on conflict replace, "
+ FIELD_USER_NAME + " text not null, "
+ FIELD_USER_SCREEN_NAME + " text, "
+ FIELD_LOCALTION + " text, "
+ FIELD_DESCRIPTION + " text, "
+ FIELD_PROFILE_IMAGE_URL + " text, "
+ FIELD_URL + " text, "
+ FIELD_PROTECTED + " boolean, "
+ FIELD_FOLLOWERS_COUNT + " integer, "
+ FIELD_FRIENDS_COUNT + " integer, "
+ FIELD_FAVORITES_COUNT + " integer, "
+ FIELD_STATUSES_COUNT + " integer, "
+ FIELD_LAST_STATUS + " text, "
+ FIELD_CREATED_AT + " date, "
+ FIELD_FOLLOWING + " boolean "
//+FIELD_FOLLOWER_IDS+" text"
+ ")";
/**
* TODO: 将游标解析为一条用户信息
*
* @param cursor 该方法不会关闭游标
* @return 成功返回User类型的单条数据, 失败返回null
*/
public static User parseCursor(Cursor cursor) {
if (null == cursor || 0 == cursor.getCount()) {
Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty.");
return null;
}
User user = new User();
user.id = cursor.getString(cursor.getColumnIndex(_ID));
user.name = cursor.getString(cursor.getColumnIndex(FIELD_USER_NAME));
user.screenName = cursor.getString(cursor.getColumnIndex(FIELD_USER_SCREEN_NAME));
user.location = cursor.getString(cursor.getColumnIndex(FIELD_LOCALTION));
user.description = cursor.getString(cursor.getColumnIndex(FIELD_DESCRIPTION));
user.profileImageUrl = cursor.getString(cursor.getColumnIndex(FIELD_PROFILE_IMAGE_URL));
user.url = cursor.getString(cursor.getColumnIndex(FIELD_URL));
user.isProtected = (0 == cursor.getInt(cursor.getColumnIndex(FIELD_PROTECTED))) ? false : true;
user.followersCount = cursor.getInt(cursor.getColumnIndex(FIELD_FOLLOWERS_COUNT));
user.lastStatus = cursor.getString(cursor.getColumnIndex(FIELD_LAST_STATUS));
user.friendsCount = cursor.getInt(cursor.getColumnIndex(FIELD_FRIENDS_COUNT));
user.favoritesCount = cursor.getInt(cursor.getColumnIndex(FIELD_FAVORITES_COUNT));
user.statusesCount = cursor.getInt(cursor.getColumnIndex(FIELD_STATUSES_COUNT));
user.isFollowing = (0 == cursor.getInt(cursor.getColumnIndex(FIELD_FOLLOWING))) ? false : true;
//TODO:报空指针异常,待查
// try {
// user.createdAt = StatusDatabase.DB_DATE_FORMATTER.parse(cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT)));
// } catch (ParseException e) {
// Log.w(TAG, "Invalid created at data.");
// }
return user;
}
} | Java |
package com.ch_linghu.fanfoudroid.db;
import java.text.ParseException;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import com.ch_linghu.fanfoudroid.data.Dm;
/**
* Table - Direct Messages
*
*/
public final class MessageTable implements BaseColumns {
public static final String TAG = "MessageTable";
public static final int TYPE_GET = 0;
public static final int TYPE_SENT = 1;
public static final String TABLE_NAME = "message";
public static final int MAX_ROW_NUM = 20;
public static final String FIELD_USER_ID = "uid";
public static final String FIELD_USER_SCREEN_NAME = "screen_name";
public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url";
public static final String FIELD_CREATED_AT = "created_at";
public static final String FIELD_TEXT = "text";
public static final String FIELD_IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id";
public static final String FIELD_IN_REPLY_TO_USER_ID = "in_reply_to_user_id";
public static final String FIELD_IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name";
public static final String FIELD_IS_UNREAD = "is_unread";
public static final String FIELD_IS_SENT = "is_send";
public static final String[] TABLE_COLUMNS = new String[] { _ID,
FIELD_USER_SCREEN_NAME, FIELD_TEXT, FIELD_PROFILE_IMAGE_URL,
FIELD_IS_UNREAD, FIELD_IS_SENT, FIELD_CREATED_AT, FIELD_USER_ID };
public static final String CREATE_TABLE = "CREATE TABLE "
+ TABLE_NAME + " ("
+ _ID + " text primary key on conflict replace, "
+ FIELD_USER_SCREEN_NAME + " text not null, "
+ FIELD_TEXT + " text not null, "
+ FIELD_PROFILE_IMAGE_URL + " text not null, "
+ FIELD_IS_UNREAD + " boolean not null, "
+ FIELD_IS_SENT + " boolean not null, "
+ FIELD_CREATED_AT + " date not null, "
+ FIELD_USER_ID + " text)";
/**
* TODO: 将游标解析为一条私信
*
* @param cursor 该方法不会关闭游标
* @return 成功返回Dm类型的单条数据, 失败返回null
*/
public static Dm parseCursor(Cursor cursor) {
if (null == cursor || 0 == cursor.getCount()) {
Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty.");
return null;
}
Dm dm = new Dm();
dm.id = cursor.getString(cursor.getColumnIndex(MessageTable._ID));
dm.screenName = cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_USER_SCREEN_NAME));
dm.text = cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_TEXT));
dm.profileImageUrl = cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_PROFILE_IMAGE_URL));
dm.isSent = (0 == cursor.getInt(cursor.getColumnIndex(MessageTable.FIELD_IS_SENT))) ? false : true ;
try {
dm.createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT)));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
dm.userId = cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_USER_ID));
return dm;
}
} | Java |
package com.ch_linghu.fanfoudroid.db;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
/**
* Table - Statuses
* <br /> <br />
* 为节省流量,故此表不保证本地数据库中所有消息具有前后连贯性, 而只确保最新的MAX_ROW_NUM条<br />
* 数据的连贯性, 超出部分则视为垃圾数据, 不再允许读取, 也不保证其是前后连续的.<br />
* <br />
* 因为用户可能中途长时间停止使用本客户端,而换其他客户端(如网页), <br />
* 如果保证本地所有数据的连贯性, 那么就必须自动去下载所有本地缺失的中间数据,<br />
* 而这些数据极有可能是用户通过其他客户端阅读过的无用信息, 浪费了用户流量.<br />
* <br />
* 即认为相对于旧信息而言, 新信息对于用户更为价值, 所以只会新信息进行维护, <br />
* 而旧信息一律视为无用的, 如用户需要查看超过MAX_ROW_NUM的旧数据, 可主动点击, <br />
* 从而请求服务器. 本地只缓存最有价值的MAX条最新信息.<br />
* <br />
* 本地数据库中前MAX_ROW_NUM条的数据模拟一个定长列队, 即在尾部插入N条消息, 就会使得头部<br />
* 的N条消息被标记为垃圾数据(但并不立即收回),只有在认为数据库数据过多时,<br />
* 可手动调用 <code>StatusDatabase.gc(int type)</code> 方法进行垃圾清理.<br />
*
*
*/
public final class StatusTable implements BaseColumns {
public static final String TAG = "StatusTable";
// Status Types
public static final int TYPE_HOME = 1; //首页(我和我的好友)
public static final int TYPE_MENTION = 2; //提到我的
public static final int TYPE_USER = 3; //指定USER的
public static final int TYPE_FAVORITE = 4; //收藏
public static final int TYPE_BROWSE = 5; //随便看看
public static final String TABLE_NAME = "status";
public static final int MAX_ROW_NUM = 20; //单类型数据安全区域
public static final String OWNER_ID = "owner"; //用于标识数据的所有者。以便于处理其他用户的信息(如其他用户的收藏)
public static final String USER_ID = "uid";
public static final String USER_SCREEN_NAME = "screen_name";
public static final String PROFILE_IMAGE_URL = "profile_image_url";
public static final String CREATED_AT = "created_at";
public static final String TEXT = "text";
public static final String SOURCE = "source";
public static final String TRUNCATED = "truncated";
public static final String IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id";
public static final String IN_REPLY_TO_USER_ID = "in_reply_to_user_id";
public static final String IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name";
public static final String FAVORITED = "favorited";
public static final String IS_UNREAD = "is_unread";
public static final String STATUS_TYPE = "status_type";
public static final String PIC_THUMB = "pic_thumbnail";
public static final String PIC_MID = "pic_middle";
public static final String PIC_ORIG = "pic_original";
// private static final String FIELD_PHOTO_URL = "photo_url";
// private double latitude = -1;
// private double longitude = -1;
// private String thumbnail_pic;
// private String bmiddle_pic;
// private String original_pic;
public static final String[] TABLE_COLUMNS = new String[] {_ID, USER_SCREEN_NAME,
TEXT, PROFILE_IMAGE_URL, IS_UNREAD, CREATED_AT,
FAVORITED, IN_REPLY_TO_STATUS_ID, IN_REPLY_TO_USER_ID,
IN_REPLY_TO_SCREEN_NAME, TRUNCATED,
PIC_THUMB, PIC_MID, PIC_ORIG,
SOURCE, USER_ID, STATUS_TYPE, OWNER_ID};
public static final String CREATE_TABLE = "CREATE TABLE "
+ TABLE_NAME + " ("
+ _ID + " text not null,"
+ STATUS_TYPE + " text not null, "
+ OWNER_ID + " text not null, "
+ USER_ID + " text not null, "
+ USER_SCREEN_NAME + " text not null, "
+ TEXT + " text not null, "
+ PROFILE_IMAGE_URL + " text not null, "
+ IS_UNREAD + " boolean not null, "
+ CREATED_AT + " date not null, "
+ SOURCE + " text not null, "
+ FAVORITED + " text, " // TODO : text -> boolean
+ IN_REPLY_TO_STATUS_ID + " text, "
+ IN_REPLY_TO_USER_ID + " text, "
+ IN_REPLY_TO_SCREEN_NAME + " text, "
+ PIC_THUMB + " text, "
+ PIC_MID + " text, "
+ PIC_ORIG + " text, "
+ TRUNCATED + " boolean ,"
+ "PRIMARY KEY (" + _ID + ","+ OWNER_ID + "," + STATUS_TYPE + "))";
/**
* 将游标解析为一条Tweet
*
*
* @param cursor 该方法不会移动或关闭游标
* @return 成功返回 Tweet 类型的单条数据, 失败返回null
*/
public static Tweet parseCursor(Cursor cursor) {
if (null == cursor || 0 == cursor.getCount()) {
Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty.");
return null;
} else if ( -1 == cursor.getPosition() ) {
cursor.moveToFirst();
}
Tweet tweet = new Tweet();
tweet.id = cursor.getString(cursor.getColumnIndex(_ID));
tweet.createdAt = DateTimeHelper.parseDateTimeFromSqlite(cursor.getString(cursor.getColumnIndex(CREATED_AT)));
tweet.favorited = cursor.getString(cursor.getColumnIndex(FAVORITED));
tweet.screenName = cursor.getString(cursor.getColumnIndex(USER_SCREEN_NAME));
tweet.userId = cursor.getString(cursor.getColumnIndex(USER_ID));
tweet.text = cursor.getString(cursor.getColumnIndex(TEXT));
tweet.source = cursor.getString(cursor.getColumnIndex(SOURCE));
tweet.profileImageUrl = cursor.getString(cursor.getColumnIndex(PROFILE_IMAGE_URL));
tweet.inReplyToScreenName = cursor.getString(cursor.getColumnIndex(IN_REPLY_TO_SCREEN_NAME));
tweet.inReplyToStatusId = cursor.getString(cursor.getColumnIndex(IN_REPLY_TO_STATUS_ID));
tweet.inReplyToUserId = cursor.getString(cursor.getColumnIndex(IN_REPLY_TO_USER_ID));
tweet.truncated = cursor.getString(cursor.getColumnIndex(TRUNCATED));
tweet.thumbnail_pic = cursor.getString(cursor.getColumnIndex(PIC_THUMB));
tweet.bmiddle_pic = cursor.getString(cursor.getColumnIndex(PIC_MID));
tweet.original_pic = cursor.getString(cursor.getColumnIndex(PIC_ORIG));
tweet.setStatusType(cursor.getInt(cursor.getColumnIndex(STATUS_TYPE)) );
return tweet;
}
} | Java |
package com.ch_linghu.fanfoudroid.db;
import java.text.ParseException;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import com.ch_linghu.fanfoudroid.data.User;
/**
* Table - Followers
*
*/
public final class FollowTable implements BaseColumns {
public static final String TAG = "FollowTable";
public static final String TABLE_NAME = "followers";
public static final String FIELD_USER_NAME = "name";
public static final String FIELD_USER_SCREEN_NAME = "screen_name";
public static final String FIELD_LOCALTION = "location";
public static final String FIELD_DESCRIPTION = "description";
public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url";
public static final String FIELD_URL = "url";
public static final String FIELD_PROTECTED = "protected";
public static final String FIELD_FOLLOWERS_COUNT = "followers_count";
public static final String FIELD_FRIENDS_COUNT = "friends_count";
public static final String FIELD_FAVORITES_COUNT = "favourites_count";
public static final String FIELD_STATUSES_COUNT = "statuses_count";
public static final String FIELD_LAST_STATUS = "last_status";
public static final String FIELD_CREATED_AT = "created_at";
public static final String FIELD_FOLLOWING = "following";
public static final String[] TABLE_COLUMNS = new String[] { _ID,
FIELD_USER_NAME, FIELD_USER_SCREEN_NAME,
FIELD_LOCALTION, FIELD_DESCRIPTION,
FIELD_PROFILE_IMAGE_URL, FIELD_URL, FIELD_PROTECTED,
FIELD_FOLLOWERS_COUNT, FIELD_FRIENDS_COUNT,
FIELD_FAVORITES_COUNT, FIELD_STATUSES_COUNT,
FIELD_LAST_STATUS, FIELD_CREATED_AT, FIELD_FOLLOWING};
public static final String CREATE_TABLE = "create table "
+ TABLE_NAME + " ("
+ _ID + " text primary key on conflict replace, "
+ FIELD_USER_NAME + " text not null, "
+ FIELD_USER_SCREEN_NAME + " text, "
+ FIELD_LOCALTION + " text, "
+ FIELD_DESCRIPTION + " text, "
+ FIELD_PROFILE_IMAGE_URL + " text, "
+ FIELD_URL + " text, "
+ FIELD_PROTECTED + " boolean, "
+ FIELD_FOLLOWERS_COUNT + " integer, "
+ FIELD_FRIENDS_COUNT + " integer, "
+ FIELD_FAVORITES_COUNT + " integer, "
+ FIELD_STATUSES_COUNT + " integer, "
+ FIELD_LAST_STATUS + " text, "
+ FIELD_CREATED_AT + " date, "
+ FIELD_FOLLOWING + " boolean "
+ ")";
/**
* TODO: 将游标解析为一条用户信息
*
* @param cursor 该方法不会关闭游标
* @return 成功返回User类型的单条数据, 失败返回null
*/
public static User parseCursor(Cursor cursor) {
if (null == cursor || 0 == cursor.getCount()) {
Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty.");
return null;
}
User user = new User();
user.id = cursor.getString(cursor.getColumnIndex(FollowTable._ID));
user.name = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_USER_NAME));
user.screenName = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_USER_SCREEN_NAME));
user.location = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_LOCALTION));
user.description = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_DESCRIPTION));
user.profileImageUrl = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_PROFILE_IMAGE_URL));
user.url = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_URL));
user.isProtected = (0 == cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_PROTECTED))) ? false : true;
user.followersCount = cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_FOLLOWERS_COUNT));
user.lastStatus = cursor.getString(cursor.getColumnIndex(FollowTable.FIELD_LAST_STATUS));;
user.friendsCount = cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_FRIENDS_COUNT));
user.favoritesCount = cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_FAVORITES_COUNT));
user.statusesCount = cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_STATUSES_COUNT));
user.isFollowing = (0 == cursor.getInt(cursor.getColumnIndex(FollowTable.FIELD_FOLLOWING))) ? false : true;
try {
user.createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT)));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
return user;
}
} | Java |
package com.ch_linghu.fanfoudroid.db;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.dao.StatusDAO;
import com.ch_linghu.fanfoudroid.data.Dm;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.util.DebugTimer;
/**
* A Database which contains all statuses and direct-messages, use
* getInstane(Context) to get a new instance
*
*/
public class TwitterDatabase {
private static final String TAG = "TwitterDatabase";
private static final String DATABASE_NAME = "status_db";
private static final int DATABASE_VERSION = 1;
private static TwitterDatabase instance = null;
private static DatabaseHelper mOpenHelper = null;
private Context mContext = null;
/**
* SQLiteOpenHelper
*
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
// Construct
public DatabaseHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
public DatabaseHelper(Context context, String name) {
this(context, name, DATABASE_VERSION);
}
public DatabaseHelper(Context context) {
this(context, DATABASE_NAME, DATABASE_VERSION);
}
public DatabaseHelper(Context context, int version) {
this(context, DATABASE_NAME, null, version);
}
public DatabaseHelper(Context context, String name, int version) {
this(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "Create Database.");
// Log.d(TAG, StatusTable.STATUS_TABLE_CREATE);
db.execSQL(StatusTable.CREATE_TABLE);
db.execSQL(MessageTable.CREATE_TABLE);
db.execSQL(FollowTable.CREATE_TABLE);
//2011.03.01 add beta
db.execSQL(UserInfoTable.CREATE_TABLE);
}
@Override
public synchronized void close() {
Log.d(TAG, "Close Database.");
super.close();
}
@Override
public void onOpen(SQLiteDatabase db) {
Log.d(TAG, "Open Database.");
super.onOpen(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "Upgrade Database.");
dropAllTables(db);
}
private void dropAllTables(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + StatusTable.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + MessageTable.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + FollowTable.TABLE_NAME);
//2011.03.01 add
db.execSQL("DROP TABLE IF EXISTS "+UserInfoTable.TABLE_NAME);
}
}
private TwitterDatabase(Context context) {
mContext = context;
mOpenHelper = new DatabaseHelper(context);
}
public static synchronized TwitterDatabase getInstance(Context context) {
if (null == instance) {
return new TwitterDatabase(context);
}
return instance;
}
// 测试用
public SQLiteOpenHelper getSQLiteOpenHelper() {
return mOpenHelper;
}
public static SQLiteDatabase getDb(boolean writeable) {
if (writeable) {
return mOpenHelper.getWritableDatabase();
} else {
return mOpenHelper.getReadableDatabase();
}
}
public void close() {
if (null != instance) {
mOpenHelper.close();
instance = null;
}
}
/**
* 清空所有表中数据, 谨慎使用
*
*/
public void clearData() {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.execSQL("DELETE FROM " + StatusTable.TABLE_NAME);
db.execSQL("DELETE FROM " + MessageTable.TABLE_NAME);
db.execSQL("DELETE FROM " + FollowTable.TABLE_NAME);
//2011.03.01 add
db.execSQL("DELETE FROM "+UserInfoTable.TABLE_NAME);
}
/**
* 直接删除数据库文件, 调试用
*
* @return true if this file was deleted, false otherwise.
* @deprecated
*/
private boolean deleteDatabase() {
File dbFile = mContext.getDatabasePath(DATABASE_NAME);
return dbFile.delete();
}
/**
* 取出某类型的一条消息
*
* @param tweetId
* @param type of status
* <li>StatusTable.TYPE_HOME</li>
* <li>StatusTable.TYPE_MENTION</li>
* <li>StatusTable.TYPE_USER</li>
* <li>StatusTable.TYPE_FAVORITE</li>
* <li>-1 means all types</li>
* @return 将Cursor转换过的Tweet对象
* @deprecated use StatusDAO#findStatus()
*/
public Tweet queryTweet(String tweetId, int type) {
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
String selection = StatusTable._ID + "=? ";
if (-1 != type) {
selection += " AND " + StatusTable.STATUS_TYPE + "=" + type;
}
Cursor cursor = Db.query(StatusTable.TABLE_NAME,
StatusTable.TABLE_COLUMNS, selection, new String[] { tweetId },
null, null, null);
Tweet tweet = null;
if (cursor != null) {
cursor.moveToFirst();
if (cursor.getCount() > 0) {
tweet = StatusTable.parseCursor(cursor);
}
}
cursor.close();
return tweet;
}
/**
* 快速检查某条消息是否存在(指定类型)
*
* @param tweetId
* @param type
* <li>StatusTable.TYPE_HOME</li>
* <li>StatusTable.TYPE_MENTION</li>
* <li>StatusTable.TYPE_USER</li>
* <li>StatusTable.TYPE_FAVORITE</li>
* @return is exists
* @deprecated use StatusDAO#isExists()
*/
public boolean isExists(String tweetId, String owner, int type) {
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
boolean result = false;
Cursor cursor = Db.query(StatusTable.TABLE_NAME,
new String[] { StatusTable._ID }, StatusTable._ID + " =? AND "
+ StatusTable.OWNER_ID + "=? AND "
+ StatusTable.STATUS_TYPE + " = " + type,
new String[] { tweetId, owner }, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
result = true;
}
cursor.close();
return result;
}
/**
* 删除一条消息
*
* @param tweetId
* @param type -1 means all types
* @return the number of rows affected if a whereClause is passed in, 0
* otherwise. To remove all rows and get a count pass "1" as the
* whereClause.
* @deprecated use {@link StatusDAO#deleteStatus(String, String, int)}
*/
public int deleteTweet(String tweetId, String owner, int type) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
String where = StatusTable._ID + " =? ";
if (!TextUtils.isEmpty(owner)){
where += " AND " + StatusTable.OWNER_ID + " = '" + owner + "' ";
}
if (-1 != type) {
where += " AND " + StatusTable.STATUS_TYPE + " = " + type;
}
return db.delete(StatusTable.TABLE_NAME, where, new String[] { tweetId });
}
/**
* 删除超过MAX_ROW_NUM垃圾数据
*
* @param type
* <li>StatusTable.TYPE_HOME</li>
* <li>StatusTable.TYPE_MENTION</li>
* <li>StatusTable.TYPE_USER</li>
* <li>StatusTable.TYPE_FAVORITE</li>
* <li>-1 means all types</li>
*/
public void gc(String owner, int type) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
String sql = "DELETE FROM " + StatusTable.TABLE_NAME
+ " WHERE " + StatusTable._ID + " NOT IN "
+ " (SELECT " + StatusTable._ID // 子句
+ " FROM " + StatusTable.TABLE_NAME;
boolean first = true;
if (!TextUtils.isEmpty(owner)){
sql += " WHERE " + StatusTable.OWNER_ID + " = '" + owner + "' ";
first = false;
}
if (type != -1){
if (first){
sql += " WHERE ";
}else{
sql += " AND ";
}
sql += StatusTable.STATUS_TYPE + " = " + type + " ";
}
sql += " ORDER BY " + StatusTable.CREATED_AT + " DESC LIMIT "
+ StatusTable.MAX_ROW_NUM + ")";
if (!TextUtils.isEmpty(owner)){
sql += " AND " + StatusTable.OWNER_ID + " = '" + owner + "' ";
}
if (type != -1) {
sql += " AND " + StatusTable.STATUS_TYPE + " = " + type + " ";
}
Log.v(TAG, sql);
mDb.execSQL(sql);
}
public final static DateFormat DB_DATE_FORMATTER = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
private static final int CONFLICT_REPLACE = 0x00000005;
/**
* 向Status表中写入一行数据, 此方法为私有方法, 外部插入数据请使用 putTweets()
*
* @param tweet
* 需要写入的单条消息
* @return the row ID of the newly inserted row, or -1 if an error occurred
* @deprecated use {@link StatusDAO#insertStatus(Status, boolean)}
*/
public long insertTweet(Tweet tweet, String owner, int type, boolean isUnread) {
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
if (isExists(tweet.id, owner, type)) {
Log.w(TAG, tweet.id + "is exists.");
return -1;
}
ContentValues initialValues = makeTweetValues(tweet, owner, type, isUnread);
long id = Db.insert(StatusTable.TABLE_NAME, null, initialValues);
if (-1 == id) {
Log.e(TAG, "cann't insert the tweet : " + tweet.toString());
} else {
//Log.v(TAG, "Insert a status into database : " + tweet.toString());
}
return id;
}
/**
* 更新一条消息
*
* @param tweetId
* @param values
* ContentValues 需要更新字段的键值对
* @return the number of rows affected
* @deprecated use {@link StatusDAO#updateStatus(String, ContentValues)}
*/
public int updateTweet(String tweetId, ContentValues values) {
Log.v(TAG, "Update Tweet : " + tweetId + " " + values.toString());
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
return Db.update(StatusTable.TABLE_NAME, values,
StatusTable._ID + "=?", new String[] { tweetId });
}
/** @deprecated */
private ContentValues makeTweetValues(Tweet tweet, String owner, int type, boolean isUnread) {
// 插入一条新消息
ContentValues initialValues = new ContentValues();
initialValues.put(StatusTable.OWNER_ID, owner);
initialValues.put(StatusTable.STATUS_TYPE, type);
initialValues.put(StatusTable._ID, tweet.id);
initialValues.put(StatusTable.TEXT, tweet.text);
initialValues.put(StatusTable.USER_ID, tweet.userId);
initialValues.put(StatusTable.USER_SCREEN_NAME, tweet.screenName);
initialValues.put(StatusTable.PROFILE_IMAGE_URL,
tweet.profileImageUrl);
initialValues.put(StatusTable.PIC_THUMB, tweet.thumbnail_pic);
initialValues.put(StatusTable.PIC_MID, tweet.bmiddle_pic);
initialValues.put(StatusTable.PIC_ORIG, tweet.original_pic);
initialValues.put(StatusTable.FAVORITED, tweet.favorited);
initialValues.put(StatusTable.IN_REPLY_TO_STATUS_ID,
tweet.inReplyToStatusId);
initialValues.put(StatusTable.IN_REPLY_TO_USER_ID,
tweet.inReplyToUserId);
initialValues.put(StatusTable.IN_REPLY_TO_SCREEN_NAME,
tweet.inReplyToScreenName);
// initialValues.put(FIELD_IS_REPLY, tweet.isReply());
initialValues.put(StatusTable.CREATED_AT,
DB_DATE_FORMATTER.format(tweet.createdAt));
initialValues.put(StatusTable.SOURCE, tweet.source);
initialValues.put(StatusTable.IS_UNREAD, isUnread);
initialValues.put(StatusTable.TRUNCATED, tweet.truncated);
// TODO: truncated
return initialValues;
}
/**
* 写入N条消息
*
* @param tweets
* 需要写入的消息List
* @return
* 写入的记录条数
*/
public int putTweets(List<Tweet> tweets, String owner, int type, boolean isUnread) {
if (TwitterApplication.DEBUG){
DebugTimer.betweenStart("Status DB");
}
if (null == tweets || 0 == tweets.size())
{
return 0;
}
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int result = 0;
try {
db.beginTransaction();
for (int i = tweets.size() - 1; i >= 0; i--) {
Tweet tweet = tweets.get(i);
ContentValues initialValues = makeTweetValues(tweet, owner, type, isUnread);
long id = db.insert(StatusTable.TABLE_NAME, null, initialValues);
if (-1 == id) {
Log.e(TAG, "cann't insert the tweet : " + tweet.toString());
} else {
++result;
//Log.v(TAG, String.format("Insert a status into database[%s] : %s", owner, tweet.toString()));
Log.v("TAG", "Insert Status");
}
}
// gc(type); // 保持总量
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
if (TwitterApplication.DEBUG){
DebugTimer.betweenEnd("Status DB");
}
return result;
}
/**
* 取出指定用户的某一类型的所有消息
*
* @param userId
* @param tableName
* @return a cursor
* @deprecated use {@link StatusDAO#findStatuses(String, int)}
*/
public Cursor fetchAllTweets(String owner, int type) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
return mDb.query(StatusTable.TABLE_NAME, StatusTable.TABLE_COLUMNS,
StatusTable.OWNER_ID + " = ? AND " + StatusTable.STATUS_TYPE + " = " + type,
new String[]{owner}, null, null,
StatusTable.CREATED_AT + " DESC ");
//LIMIT " + StatusTable.MAX_ROW_NUM);
}
/**
* 取出自己的某一类型的所有消息
*
* @param tableName
* @return a cursor
*/
public Cursor fetchAllTweets(int type) {
// 获取登录用户id
SharedPreferences preferences = TwitterApplication.mPref;
String myself = preferences.getString(Preferences.CURRENT_USER_ID,
TwitterApplication.mApi.getUserId());
return fetchAllTweets(myself, type);
}
/**
* 清空某类型的所有信息
*
* @param tableName
* @return the number of rows affected if a whereClause is passed in, 0
* otherwise. To remove all rows and get a count pass "1" as the
* whereClause.
*/
public int dropAllTweets(int type) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
return mDb.delete(StatusTable.TABLE_NAME, StatusTable.STATUS_TYPE
+ " = " + type, null);
}
/**
* 取出本地某类型最新消息ID
*
* @param type
* @return The newest Status Id
*/
public String fetchMaxTweetId(String owner, int type) {
return fetchMaxOrMinTweetId(owner, type, true);
}
/**
* 取出本地某类型最旧消息ID
*
* @param tableName
* @return The oldest Status Id
*/
public String fetchMinTweetId(String owner, int type) {
return fetchMaxOrMinTweetId(owner, type, false);
}
private String fetchMaxOrMinTweetId(String owner, int type, boolean isMax) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
String sql = "SELECT " + StatusTable._ID + " FROM "
+ StatusTable.TABLE_NAME + " WHERE "
+ StatusTable.STATUS_TYPE + " = " + type + " AND "
+ StatusTable.OWNER_ID + " = '" + owner + "' "
+ " ORDER BY "
+ StatusTable.CREATED_AT;
if (isMax)
sql += " DESC ";
Cursor mCursor = mDb.rawQuery(sql + " LIMIT 1", null);
String result = null;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
if (mCursor.getCount() == 0) {
result = null;
} else {
result = mCursor.getString(0);
}
mCursor.close();
return result;
}
/**
* Count unread tweet
*
* @param tableName
* @return
*/
public int fetchUnreadCount(String owner, int type) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + StatusTable._ID + ")"
+ " FROM " + StatusTable.TABLE_NAME + " WHERE "
+ StatusTable.STATUS_TYPE + " = " + type + " AND "
+ StatusTable.OWNER_ID + " = '" + owner + "' AND "
+ StatusTable.IS_UNREAD + " = 1 ",
// "LIMIT " + StatusTable.MAX_ROW_NUM,
null);
int result = 0;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
result = mCursor.getInt(0);
mCursor.close();
return result;
}
public int addNewTweetsAndCountUnread(List<Tweet> tweets, String owner, int type) {
putTweets(tweets, owner, type, true);
return fetchUnreadCount(owner, type);
}
/**
* Set isFavorited
*
* @param tweetId
* @param isFavorited
* @return Is Succeed
* @deprecated use {@link Status#setFavorited(boolean)} and
* {@link StatusDAO#updateStatus(Status)}
*/
public boolean setFavorited(String tweetId, String isFavorited) {
ContentValues values = new ContentValues();
values.put(StatusTable.FAVORITED, isFavorited);
int i = updateTweet(tweetId, values);
return (i > 0) ? true : false;
}
// DM & Follower
/**
* 写入一条私信
*
* @param dm
* @param isUnread
* @return the row ID of the newly inserted row, or -1 if an error occurred,
* 因为主键的原因,此处返回的不是 _ID 的值, 而是一个自增长的 row_id
*/
public long createDm(Dm dm, boolean isUnread) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(MessageTable._ID, dm.id);
initialValues.put(MessageTable.FIELD_USER_SCREEN_NAME, dm.screenName);
initialValues.put(MessageTable.FIELD_TEXT, dm.text);
initialValues.put(MessageTable.FIELD_PROFILE_IMAGE_URL,
dm.profileImageUrl);
initialValues.put(MessageTable.FIELD_IS_UNREAD, isUnread);
initialValues.put(MessageTable.FIELD_IS_SENT, dm.isSent);
initialValues.put(MessageTable.FIELD_CREATED_AT,
DB_DATE_FORMATTER.format(dm.createdAt));
initialValues.put(MessageTable.FIELD_USER_ID, dm.userId);
return mDb.insert(MessageTable.TABLE_NAME, null, initialValues);
}
//
/**
* Create a follower
*
* @param userId
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long createFollower(String userId) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(FollowTable._ID, userId);
long rowId = mDb.insert(FollowTable.TABLE_NAME, null, initialValues);
if (-1 == rowId) {
Log.e(TAG, "Cann't create Follower : " + userId);
} else {
Log.v(TAG, "Success create follower : " + userId);
}
return rowId;
}
/**
* 清空Followers表并添加新内容
*
* @param followers
*/
public void syncFollowers(List<String> followers) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
try {
mDb.beginTransaction();
boolean result = deleteAllFollowers();
Log.v(TAG, "Result of DeleteAllFollowers: " + result);
for (String userId : followers) {
createFollower(userId);
}
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
/**
* @param type
* <li>MessageTable.TYPE_SENT</li>
* <li>MessageTable.TYPE_GET</li>
* <li>其他任何值都认为取出所有类型</li>
* @return
*/
public Cursor fetchAllDms(int type) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
String selection = null;
if (MessageTable.TYPE_SENT == type) {
selection = MessageTable.FIELD_IS_SENT + " = "
+ MessageTable.TYPE_SENT;
} else if (MessageTable.TYPE_GET == type) {
selection = MessageTable.FIELD_IS_SENT + " = "
+ MessageTable.TYPE_GET;
}
return mDb.query(MessageTable.TABLE_NAME, MessageTable.TABLE_COLUMNS,
selection, null, null, null, MessageTable.FIELD_CREATED_AT
+ " DESC");
}
public Cursor fetchInboxDms() {
return fetchAllDms(MessageTable.TYPE_GET);
}
public Cursor fetchSendboxDms() {
return fetchAllDms(MessageTable.TYPE_SENT);
}
public Cursor fetchAllFollowers() {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
return mDb.query(FollowTable.TABLE_NAME, FollowTable.TABLE_COLUMNS,
null, null, null, null, null);
}
/**
* FIXME:
* @param filter
* @return
*/
public Cursor getFollowerUsernames(String filter) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
String likeFilter = '%' + filter + '%';
// FIXME: 此方法的作用应该是在于在写私信时自动完成联系人的功能,
// 改造数据库后,因为本地tweets表中的数据有限, 所以几乎使得该功能没有实际价值(因为能从数据库中读到的联系人很少)
// 在完成关注者/被关注者两个界面后, 看能不能使得本地有一份
// [互相关注] 的 id/name 缓存(即getFriendsIds和getFollowersIds的交集, 因为客户端只能给他们发私信, 如果按现在
// 只提示followers的列表则很容易造成服务器返回"只能给互相关注的人发私信"的错误信息, 这会造成用户无法理解, 因为此联系人是我们提供给他们选择的,
// 并且将目前的自动完成功能的基础上加一个[选择联系人]按钮, 用于启动一个新的联系人列表页面以显示所有可发送私信的联系人对象, 类似手机写短信时的选择联系人功能
return null;
// FIXME: clean this up. 新数据库中失效, 表名, 列名
// return mDb.rawQuery(
// "SELECT user_id AS _id, user"
// + " FROM (SELECT user_id, user FROM tweets"
// + " INNER JOIN followers on tweets.user_id = followers._id UNION"
// + " SELECT user_id, user FROM dms INNER JOIN followers"
// + " on dms.user_id = followers._id)"
// + " WHERE user LIKE ?"
// + " ORDER BY user COLLATE NOCASE",
// new String[] { likeFilter });
}
/**
* @param userId
* 该用户是否follow Me
* @deprecated 未使用
* @return
*/
public boolean isFollower(String userId) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor cursor = mDb.query(FollowTable.TABLE_NAME,
FollowTable.TABLE_COLUMNS, FollowTable._ID + "= ?",
new String[] { userId }, null, null, null);
boolean result = false;
if (cursor != null && cursor.moveToFirst()) {
result = true;
}
cursor.close();
return result;
}
public boolean deleteAllFollowers() {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
return mDb.delete(FollowTable.TABLE_NAME, null, null) > 0;
}
public boolean deleteDm(String id) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
return mDb.delete(MessageTable.TABLE_NAME,
String.format("%s = '%s'", MessageTable._ID, id), null) > 0;
}
/**
* @param tableName
* @return the number of rows affected
*/
public int markAllTweetsRead(String owner, int type) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(StatusTable.IS_UNREAD, 0);
return mDb.update(StatusTable.TABLE_NAME, values,
StatusTable.STATUS_TYPE + "=" + type, null);
}
public boolean deleteAllDms() {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
return mDb.delete(MessageTable.TABLE_NAME, null, null) > 0;
}
public int markAllDmsRead() {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(MessageTable.FIELD_IS_UNREAD, 0);
return mDb.update(MessageTable.TABLE_NAME, values, null, null);
}
public String fetchMaxDmId(boolean isSent) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor mCursor = mDb.rawQuery("SELECT " + MessageTable._ID + " FROM "
+ MessageTable.TABLE_NAME + " WHERE "
+ MessageTable.FIELD_IS_SENT + " = ? " + " ORDER BY "
+ MessageTable.FIELD_CREATED_AT + " DESC LIMIT 1",
new String[] { isSent ? "1" : "0" });
String result = null;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
if (mCursor.getCount() == 0) {
result = null;
} else {
result = mCursor.getString(0);
}
mCursor.close();
return result;
}
public int addNewDmsAndCountUnread(List<Dm> dms) {
addDms(dms, true);
return fetchUnreadDmCount();
}
public int fetchDmCount() {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + MessageTable._ID
+ ") FROM " + MessageTable.TABLE_NAME, null);
int result = 0;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
result = mCursor.getInt(0);
mCursor.close();
return result;
}
private int fetchUnreadDmCount() {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + MessageTable._ID
+ ") FROM " + MessageTable.TABLE_NAME + " WHERE "
+ MessageTable.FIELD_IS_UNREAD + " = 1", null);
int result = 0;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
result = mCursor.getInt(0);
mCursor.close();
return result;
}
public void addDms(List<Dm> dms, boolean isUnread) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
try {
mDb.beginTransaction();
for (Dm dm : dms) {
createDm(dm, isUnread);
}
// limitRows(TABLE_DIRECTMESSAGE, TwitterApi.RETRIEVE_LIMIT);
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
//2011.03.01 add
//UserInfo操作
public Cursor getAllUserInfo(){
SQLiteDatabase mDb=mOpenHelper.getReadableDatabase();
return mDb.query(UserInfoTable.TABLE_NAME,UserInfoTable.TABLE_COLUMNS, null, null, null, null, null);
}
/**
* 根据id列表获取user数据
* @param userIds
* @return
*/
public Cursor getUserInfoByIds(String[] userIds){
SQLiteDatabase mDb=mOpenHelper.getReadableDatabase();
String userIdStr="";
for(String id:userIds){
userIdStr+="'"+id+"',";
}
if(userIds.length==0){
userIdStr="'',";
}
userIdStr=userIdStr.substring(0, userIdStr.lastIndexOf(","));//删除最后的逗号
return mDb.query(UserInfoTable.TABLE_NAME, UserInfoTable.TABLE_COLUMNS, UserInfoTable._ID+" in ("+userIdStr+")", null, null, null, null);
}
/**
* 新建用户
*
* @param user
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long createUserInfo(com.ch_linghu.fanfoudroid.data.User user) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(UserInfoTable._ID, user.id);
initialValues.put(UserInfoTable.FIELD_USER_NAME, user.name);
initialValues.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.screenName);
initialValues.put(UserInfoTable.FIELD_LOCALTION, user.location);
initialValues.put(UserInfoTable.FIELD_DESCRIPTION, user.description);
initialValues.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user.profileImageUrl);
initialValues.put(UserInfoTable.FIELD_URL, user.url);
initialValues.put(UserInfoTable.FIELD_PROTECTED, user.isProtected);
initialValues.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.followersCount);
initialValues.put(UserInfoTable.FIELD_LAST_STATUS, user.lastStatus);
initialValues.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.friendsCount);
initialValues.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.favoritesCount);
initialValues.put(UserInfoTable.FIELD_STATUSES_COUNT, user.statusesCount);
initialValues.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing);
//long rowId = mDb.insertWithOnConflict(UserInfoTable.TABLE_NAME, null, initialValues,SQLiteDatabase.CONFLICT_REPLACE);
long rowId = insertWithOnConflict(mDb, UserInfoTable.TABLE_NAME, null, initialValues, CONFLICT_REPLACE);
if (-1 == rowId) {
Log.e(TAG, "Cann't create user : " + user.id);
} else {
Log.v(TAG, "create create user : " + user.id);
}
return rowId;
}
//SQLiteDatabase.insertWithConflict是LEVEL 8(2.2)才引入的新方法
//为了兼容旧版,这里给出一个简化的兼容实现
//要注意的是这个实现和标准的函数行为并不完全一致
private long insertWithOnConflict(SQLiteDatabase db, String tableName,
String nullColumnHack, ContentValues initialValues, int conflictReplace) {
long rowId = db.insert(tableName, nullColumnHack, initialValues);
if(-1 == rowId){
//尝试update
rowId = db.update(tableName, initialValues,
UserInfoTable._ID+"="+initialValues.getAsString(UserInfoTable._ID), null);
}
return rowId;
}
public long createWeiboUserInfo(com.ch_linghu.fanfoudroid.fanfou.User user){
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(UserInfoTable._ID, user.getId());
args.put(UserInfoTable.FIELD_USER_NAME, user.getName());
args.put(UserInfoTable.FIELD_USER_SCREEN_NAME,
user.getScreenName());
String location = user.getLocation();
args.put(UserInfoTable.FIELD_LOCALTION, location);
String description = user.getDescription();
args.put(UserInfoTable.FIELD_DESCRIPTION, description);
args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL,
user.getProfileImageURL().toString());
if (user.getURL() != null) {
args.put(UserInfoTable.FIELD_URL, user.getURL().toString());
}
args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected());
args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT,
user.getFollowersCount());
args.put(UserInfoTable.FIELD_LAST_STATUS, user.getStatusSource());
args.put(UserInfoTable.FIELD_FRIENDS_COUNT,
user.getFriendsCount());
args.put(UserInfoTable.FIELD_FAVORITES_COUNT,
user.getFavouritesCount());
args.put(UserInfoTable.FIELD_STATUSES_COUNT,
user.getStatusesCount());
args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing());
//long rowId = mDb.insert(UserInfoTable.TABLE_NAME, null, args);
//省去判断existUser,如果存在数据则replace
//long rowId=mDb.insertWithOnConflict(UserInfoTable.TABLE_NAME, null, args, SQLiteDatabase.CONFLICT_REPLACE);
long rowId=insertWithOnConflict(mDb, UserInfoTable.TABLE_NAME, null, args, CONFLICT_REPLACE);
if (-1 == rowId) {
Log.e(TAG, "Cann't createWeiboUserInfo : " + user.getId());
} else {
Log.v(TAG, "create createWeiboUserInfo : " + user.getId());
}
return rowId;
}
/**
* 查看数据是否已保存用户数据
* @param userId
* @return
*/
public boolean existsUser(String userId) {
SQLiteDatabase Db = mOpenHelper.getReadableDatabase();
boolean result = false;
Cursor cursor = Db.query(UserInfoTable.TABLE_NAME,
new String[] { UserInfoTable._ID }, UserInfoTable._ID +"='"+userId+"'",
null, null, null, null);
Log.v("testesetesteste", String.valueOf(cursor.getCount()));
if (cursor != null && cursor.getCount() > 0) {
result = true;
}
cursor.close();
return result;
}
/**
* 根据userid提取信息
* @param userId
* @return
*/
public Cursor getUserInfoById(String userId){
SQLiteDatabase Db = mOpenHelper.getReadableDatabase();
Cursor cursor = Db.query(UserInfoTable.TABLE_NAME,
UserInfoTable.TABLE_COLUMNS, UserInfoTable._ID + " = '" +userId+"'",
null, null, null, null);
return cursor;
}
/**
* 更新用户
* @param uid
* @param args
* @return
*/
public boolean updateUser(String uid,ContentValues args){
SQLiteDatabase Db=mOpenHelper.getWritableDatabase();
return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID+"='"+uid+"'", null)>0;
}
/**
* 更新用户信息
*/
public boolean updateUser(com.ch_linghu.fanfoudroid.data.User user){
SQLiteDatabase Db=mOpenHelper.getWritableDatabase();
ContentValues args=new ContentValues();
args.put(UserInfoTable._ID, user.id);
args.put(UserInfoTable.FIELD_USER_NAME, user.name);
args.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.screenName);
args.put(UserInfoTable.FIELD_LOCALTION, user.location);
args.put(UserInfoTable.FIELD_DESCRIPTION, user.description);
args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user.profileImageUrl);
args.put(UserInfoTable.FIELD_URL, user.url);
args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected);
args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.followersCount);
args.put(UserInfoTable.FIELD_LAST_STATUS, user.lastStatus);
args.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.friendsCount);
args.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.favoritesCount);
args.put(UserInfoTable.FIELD_STATUSES_COUNT, user.statusesCount);
args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing);
return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID+"='"+user.id+"'", null)>0;
}
/**
* 减少转换的开销
* @param user
* @return
*/
public boolean updateWeiboUser(com.ch_linghu.fanfoudroid.fanfou.User user){
SQLiteDatabase Db=mOpenHelper.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(UserInfoTable._ID, user.getName());
args.put(UserInfoTable.FIELD_USER_NAME, user.getName());
args.put(UserInfoTable.FIELD_USER_SCREEN_NAME,
user.getScreenName());
String location = user.getLocation();
args.put(UserInfoTable.FIELD_LOCALTION, location);
String description = user.getDescription();
args.put(UserInfoTable.FIELD_DESCRIPTION, description);
args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL,
user.getProfileImageURL().toString());
if (user.getURL() != null) {
args.put(UserInfoTable.FIELD_URL, user.getURL().toString());
}
args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected());
args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT,
user.getFollowersCount());
args.put(UserInfoTable.FIELD_LAST_STATUS, user.getStatusSource());
args.put(UserInfoTable.FIELD_FRIENDS_COUNT,
user.getFriendsCount());
args.put(UserInfoTable.FIELD_FAVORITES_COUNT,
user.getFavouritesCount());
args.put(UserInfoTable.FIELD_STATUSES_COUNT,
user.getStatusesCount());
args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing());
return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID+"='"+user.getId()+"'", null)>0;
}
/**
* 同步用户,更新已存在的用户,插入未存在的用户
*/
public void syncUsers(List<com.ch_linghu.fanfoudroid.data.User> users){
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
try{
mDb.beginTransaction();
for(com.ch_linghu.fanfoudroid.data.User u:users){
// if(existsUser(u.id)){
// updateUser(u);
// }else{
// createUserInfo(u);
// }
createUserInfo(u);
}
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
public void syncWeiboUsers(List<com.ch_linghu.fanfoudroid.fanfou.User> users) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
try {
mDb.beginTransaction();
for (com.ch_linghu.fanfoudroid.fanfou.User u : users) {
// if (existsUser(u.getId())) {
// updateWeiboUser(u);
// } else {
// createWeiboUserInfo(u);
// }
createWeiboUserInfo(u);
}
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.util.ArrayList;
import java.util.List;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.fanfou.SavedSearch;
import com.ch_linghu.fanfoudroid.fanfou.Trend;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.util.TextHelper;
import com.commonsware.cwac.merge.MergeAdapter;
public class SearchActivity extends BaseActivity {
private static final String TAG = SearchActivity.class.getSimpleName();
private static final int LOADING = 1;
private static final int NETWORKERROR = 2;
private static final int SUCCESS = 3;
private EditText mSearchEdit;
private ListView mSearchSectionList;
private TextView trendsTitle;
private TextView savedSearchTitle;
private MergeAdapter mSearchSectionAdapter;
private SearchAdapter trendsAdapter;
private SearchAdapter savedSearchesAdapter;
private ArrayList<SearchItem> trends;
private ArrayList<SearchItem> savedSearch;
private String initialQuery;
private NavBar mNavbar;
private Feedback mFeedback;
private GenericTask trendsAndSavedSearchesTask;
private TaskListener trendsAndSavedSearchesTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "trendsAndSavedSearchesTask";
}
@Override
public void onPreExecute(GenericTask task) {
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
refreshSearchSectionList(SearchActivity.SUCCESS);
} else if (result == TaskResult.IO_ERROR) {
refreshSearchSectionList(SearchActivity.NETWORKERROR);
Toast.makeText(
SearchActivity.this,
getResources()
.getString(
R.string.login_status_network_or_connection_error),
Toast.LENGTH_SHORT).show();
}
}
};
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate()...");
if (super._onCreate(savedInstanceState)) {
setContentView(R.layout.search);
mNavbar = new NavBar(NavBar.HEADER_STYLE_SEARCH, this);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
initView();
initSearchSectionList();
refreshSearchSectionList(SearchActivity.LOADING);
doGetSavedSearches();
return true;
} else {
return false;
}
}
private void initView() {
mSearchEdit = (EditText) findViewById(R.id.search_edit);
mSearchEdit.setOnKeyListener(enterKeyHandler);
trendsTitle = (TextView) getLayoutInflater().inflate(
R.layout.search_section_header, null);
trendsTitle.setText(getResources().getString(R.string.trends_title));
savedSearchTitle = (TextView) getLayoutInflater().inflate(
R.layout.search_section_header, null);
savedSearchTitle.setText(getResources().getString(
R.string.saved_search_title));
mSearchSectionAdapter = new MergeAdapter();
mSearchSectionList = (ListView) findViewById(R.id.search_section_list);
mNavbar.getSearchButton().setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
initialQuery = mSearchEdit.getText().toString();
startSearch();
}
});
}
@Override
protected void onResume() {
Log.d(TAG, "onResume()...");
super.onResume();
}
private void doGetSavedSearches() {
if (trendsAndSavedSearchesTask != null
&& trendsAndSavedSearchesTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
trendsAndSavedSearchesTask = new TrendsAndSavedSearchesTask();
trendsAndSavedSearchesTask
.setListener(trendsAndSavedSearchesTaskListener);
trendsAndSavedSearchesTask.setFeedback(mFeedback);
trendsAndSavedSearchesTask.execute();
}
}
private void initSearchSectionList() {
trends = new ArrayList<SearchItem>();
savedSearch = new ArrayList<SearchItem>();
trendsAdapter = new SearchAdapter(this);
savedSearchesAdapter = new SearchAdapter(this);
mSearchSectionAdapter.addView(savedSearchTitle);
mSearchSectionAdapter.addAdapter(savedSearchesAdapter);
mSearchSectionAdapter.addView(trendsTitle);
mSearchSectionAdapter.addAdapter(trendsAdapter);
mSearchSectionList.setAdapter(mSearchSectionAdapter);
}
/**
* 辅助计算位置的类
*
* @author jmx
*
*/
class PositionHelper {
/**
* 返回指定位置属于哪一个小节
*
* @param position
* 绝对位置
* @return 小节的序号,0是第一小节,1是第二小节, -1为无效位置
*/
public int getSectionIndex(int position) {
int[] contentLength = new int[2];
contentLength[0] = savedSearchesAdapter.getCount();
contentLength[1] = trendsAdapter.getCount();
if (position > 0 && position < contentLength[0] + 1) {
return 0;
} else if (position > contentLength[0] + 1
&& position < (contentLength[0] + contentLength[1] + 1) + 1) {
return 1;
} else {
return -1;
}
}
/**
* 返回指定位置在自己所在小节的相对位置
*
* @param position
* 绝对位置
* @return 所在小节的相对位置,-1为无效位置
*/
public int getRelativePostion(int position) {
int[] contentLength = new int[2];
contentLength[0] = savedSearchesAdapter.getCount();
contentLength[1] = trendsAdapter.getCount();
int sectionIndex = getSectionIndex(position);
int offset = 0;
for (int i = 0; i < sectionIndex; ++i) {
offset += contentLength[i] + 1;
}
return position - offset - 1;
}
}
/**
* flag: loading;network error;success
*/
PositionHelper pos_helper = new PositionHelper();
private void refreshSearchSectionList(int flag) {
AdapterView.OnItemClickListener searchSectionListListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long id) {
MergeAdapter adapter = (MergeAdapter) (adapterView.getAdapter());
SearchAdapter subAdapter = (SearchAdapter) adapter
.getAdapter(position);
// 计算针对subAdapter中的相对位置
int relativePos = pos_helper.getRelativePostion(position);
SearchItem item = (SearchItem) (subAdapter.getItem(relativePos));
initialQuery = item.query;
startSearch();
}
};
if (flag == SearchActivity.LOADING) {
mSearchSectionList.setOnItemClickListener(null);
savedSearch.clear();
trends.clear();
savedSearchesAdapter.refresh(getString(R.string.search_loading));
trendsAdapter.refresh(getString(R.string.search_loading));
} else if (flag == SearchActivity.NETWORKERROR) {
mSearchSectionList.setOnItemClickListener(null);
savedSearch.clear();
trends.clear();
savedSearchesAdapter
.refresh(getString(R.string.login_status_network_or_connection_error));
trendsAdapter
.refresh(getString(R.string.login_status_network_or_connection_error));
} else {
savedSearchesAdapter.refresh(savedSearch);
trendsAdapter.refresh(trends);
}
if (flag == SearchActivity.SUCCESS) {
mSearchSectionList
.setOnItemClickListener(searchSectionListListener);
}
}
protected boolean startSearch() {
if (!TextUtils.isEmpty(initialQuery)) {
// 以下这个方法在7可用,在8就报空指针
// triggerSearch(initialQuery, null);
Intent i = new Intent(this, SearchResultActivity.class);
i.putExtra(SearchManager.QUERY, initialQuery);
startActivity(i);
} else if (TextUtils.isEmpty(initialQuery)) {
Toast.makeText(this,
getResources().getString(R.string.search_box_null),
Toast.LENGTH_SHORT).show();
return false;
}
return false;
}
// 搜索框回车键判断
private View.OnKeyListener enterKeyHandler = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER
|| keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
if (event.getAction() == KeyEvent.ACTION_UP) {
initialQuery = mSearchEdit.getText().toString();
startSearch();
}
return true;
}
return false;
}
};
private class TrendsAndSavedSearchesTask extends GenericTask {
Trend[] trendsList;
List<SavedSearch> savedSearchsList;
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
trendsList = getApi().getTrends().getTrends();
savedSearchsList = getApi().getSavedSearches();
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
trends.clear();
savedSearch.clear();
for (int i = 0; i < trendsList.length; i++) {
SearchItem item = new SearchItem();
item.name = trendsList[i].getName();
item.query = trendsList[i].getQuery();
trends.add(item);
}
for (int i = 0; i < savedSearchsList.size(); i++) {
SearchItem item = new SearchItem();
item.name = savedSearchsList.get(i).getName();
item.query = savedSearchsList.get(i).getQuery();
savedSearch.add(item);
}
return TaskResult.OK;
}
}
}
class SearchItem {
public String name;
public String query;
}
class SearchAdapter extends BaseAdapter {
protected ArrayList<SearchItem> mSearchList;
private Context mContext;
protected LayoutInflater mInflater;
protected StringBuilder mMetaBuilder;
public SearchAdapter(Context context) {
mSearchList = new ArrayList<SearchItem>();
mContext = context;
mInflater = LayoutInflater.from(mContext);
mMetaBuilder = new StringBuilder();
}
public SearchAdapter(Context context, String prompt) {
this(context);
refresh(prompt);
}
public void refresh(ArrayList<SearchItem> searchList) {
mSearchList = searchList;
notifyDataSetChanged();
}
public void refresh(String prompt) {
SearchItem item = new SearchItem();
item.name = prompt;
item.query = null;
mSearchList.clear();
mSearchList.add(item);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mSearchList.size();
}
@Override
public Object getItem(int position) {
return mSearchList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = mInflater.inflate(R.layout.search_section_view, parent,
false);
TextView text = (TextView) view
.findViewById(R.id.search_section_text);
view.setTag(text);
} else {
view = convertView;
}
TextView text = (TextView) view.getTag();
SearchItem item = mSearchList.get(position);
text.setText(item.name);
return view;
}
}
| Java |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.data.Dm;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.DirectMessage;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.TweetEdit;
//FIXME: 将WriteDmActivity和WriteActivity进行整合。
/**
* 撰写私信界面
* @author lds
*
*/
public class WriteDmActivity extends BaseActivity {
public static final String NEW_TWEET_ACTION = "com.ch_linghu.fanfoudroid.NEW";
public static final String EXTRA_TEXT = "text";
public static final String REPLY_ID = "reply_id";
private static final String TAG = "WriteActivity";
private static final String SIS_RUNNING_KEY = "running";
private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid";
// View
private TweetEdit mTweetEdit;
private EditText mTweetEditText;
private TextView mProgressText;
private Button mSendButton;
//private AutoCompleteTextView mToEdit;
private TextView mToEdit;
private NavBar mNavbar;
// Task
private GenericTask mSendTask;
private TaskListener mSendTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
disableEntry();
updateProgress(getString(R.string.page_status_updating));
}
@Override
public void onPostExecute(GenericTask task,
TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
mToEdit.setText("");
mTweetEdit.setText("");
updateProgress("");
enableEntry();
// 发送成功就直接关闭界面
finish();
// 关闭软键盘
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mTweetEdit.getEditText().getWindowToken(), 0);
} else if (result == TaskResult.NOT_FOLLOWED_ERROR) {
updateProgress(getString(R.string.direct_meesage_status_the_person_not_following_you));
enableEntry();
} else if (result == TaskResult.IO_ERROR) {
// TODO: 什么情况下会抛出IO_ERROR?需要给用户更为具体的失败原因
updateProgress(getString(R.string.page_status_unable_to_update));
enableEntry();
}
}
@Override
public String getName() {
return "DMSend";
}
};
private FriendsAdapter mFriendsAdapter; // Adapter for To: recipient
// autocomplete.
private static final String EXTRA_USER = "user";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMSW";
public static Intent createIntent(String user) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (!TextUtils.isEmpty(user)) {
intent.putExtra(EXTRA_USER, user);
}
return intent;
}
// sub menu
// protected void createInsertPhotoDialog() {
//
// final CharSequence[] items = {
// getString(R.string.write_label_take_a_picture),
// getString(R.string.write_label_choose_a_picture) };
//
// AlertDialog.Builder builder = new AlertDialog.Builder(this);
// builder.setTitle(getString(R.string.write_label_insert_picture));
// builder.setItems(items, new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int item) {
// // Toast.makeText(getApplicationContext(), items[item],
// // Toast.LENGTH_SHORT).show();
// switch (item) {
// case 0:
// openImageCaptureMenu();
// break;
// case 1:
// openPhotoLibraryMenu();
// }
// }
// });
// AlertDialog alert = builder.create();
// alert.show();
// }
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)){
// init View
setContentView(R.layout.write_dm);
mNavbar = new NavBar(NavBar.HEADER_STYLE_WRITE, this);
// Intent & Action & Extras
Intent intent = getIntent();
Bundle extras = intent.getExtras();
// View
mProgressText = (TextView) findViewById(R.id.progress_text);
mTweetEditText = (EditText) findViewById(R.id.tweet_edit);
TwitterDatabase db = getDb();
//FIXME: 暂时取消收件人自动完成功能
//FIXME: 可根据目前以后内容重新完成自动完成功能
//mToEdit = (AutoCompleteTextView) findViewById(R.id.to_edit);
//Cursor cursor = db.getFollowerUsernames("");
//// startManagingCursor(cursor);
//mFriendsAdapter = new FriendsAdapter(this, cursor);
//mToEdit.setAdapter(mFriendsAdapter);
mToEdit = (TextView) findViewById(R.id.to_edit);
// Update status
mTweetEdit = new TweetEdit(mTweetEditText,
(TextView) findViewById(R.id.chars_text));
mTweetEdit.setOnKeyListener(editEnterHandler);
mTweetEdit
.addTextChangedListener(new MyTextWatcher(WriteDmActivity.this));
// With extras
if (extras != null) {
String to = extras.getString(EXTRA_USER);
if (!TextUtils.isEmpty(to)) {
mToEdit.setText(to);
mTweetEdit.requestFocus();
}
}
View.OnClickListener sendListenner = new View.OnClickListener() {
public void onClick(View v) {
doSend();
}
};
mSendButton = (Button) findViewById(R.id.send_button);
mSendButton.setOnClickListener(sendListenner);
Button mTopSendButton = (Button) findViewById(R.id.top_send_btn);
mTopSendButton.setOnClickListener(sendListenner);
return true;
}else{
return false;
}
}
@Override
protected void onRestoreInstanceState(Bundle bundle) {
super.onRestoreInstanceState(bundle);
mTweetEdit.updateCharsRemain();
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause.");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart.");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume.");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart.");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop.");
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
// Doesn't really cancel execution (we let it continue running).
// See the SendTask code for more details.
mSendTask.cancel(true);
}
// Don't need to cancel FollowersTask (assuming it ends properly).
super.onDestroy();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
public static Intent createNewTweetIntent(String text) {
Intent intent = new Intent(NEW_TWEET_ACTION);
intent.putExtra(EXTRA_TEXT, text);
return intent;
}
private class MyTextWatcher implements TextWatcher {
private WriteDmActivity _activity;
public MyTextWatcher(WriteDmActivity activity) {
_activity = activity;
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if (s.length() == 0) {
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
}
private void doSend() {
if (mSendTask != null
&& mSendTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
String to = mToEdit.getText().toString();
String status = mTweetEdit.getText().toString();
if (!TextUtils.isEmpty(status) && !TextUtils.isEmpty(to)) {
mSendTask = new DmSendTask();
mSendTask.setListener(mSendTaskListener);
mSendTask.execute();
} else if (TextUtils.isEmpty(status)) {
updateProgress(getString(R.string.direct_meesage_status_texting_is_null));
} else if (TextUtils.isEmpty(to)) {
updateProgress(getString(R.string.direct_meesage_status_user_is_null));
}
}
}
private class DmSendTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
try {
String user = mToEdit.getText().toString();
String text = mTweetEdit.getText().toString();
DirectMessage directMessage = getApi().sendDirectMessage(user,
text);
Dm dm = Dm.create(directMessage, true);
// if (!Utils.isEmpty(dm.profileImageUrl)) {
// // Fetch image to cache.
// try {
// getImageManager().put(dm.profileImageUrl);
// } catch (IOException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
getDb().createDm(dm, false);
} catch (HttpException e) {
Log.d(TAG, e.getMessage());
// TODO: check is this is actually the case.
return TaskResult.NOT_FOLLOWED_ERROR;
}
return TaskResult.OK;
}
}
private static class FriendsAdapter extends CursorAdapter {
public FriendsAdapter(Context context, Cursor cursor) {
super(context, cursor);
mInflater = LayoutInflater.from(context);
mUserTextColumn = cursor
.getColumnIndexOrThrow(StatusTable.USER_SCREEN_NAME);
}
private LayoutInflater mInflater;
private int mUserTextColumn;
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater
.inflate(R.layout.dropdown_item, parent, false);
ViewHolder holder = new ViewHolder();
holder.userText = (TextView) view.findViewById(android.R.id.text1);
view.setTag(holder);
return view;
}
class ViewHolder {
public TextView userText;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
holder.userText.setText(cursor.getString(mUserTextColumn));
}
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
String filter = constraint == null ? "" : constraint.toString();
return TwitterApplication.mDb.getFollowerUsernames(filter);
}
@Override
public String convertToString(Cursor cursor) {
return cursor.getString(mUserTextColumn);
}
}
private void enableEntry() {
mTweetEdit.setEnabled(true);
mSendButton.setEnabled(true);
}
private void disableEntry() {
mTweetEdit.setEnabled(false);
mSendButton.setEnabled(false);
}
// UI helpers.
private void updateProgress(String progress) {
mProgressText.setText(progress);
}
private View.OnKeyListener editEnterHandler = new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_ENTER
|| keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
if (event.getAction() == KeyEvent.ACTION_UP) {
doSend();
}
return true;
}
return false;
}
};
} | Java |
package com.ch_linghu.fanfoudroid;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Dm;
import com.ch_linghu.fanfoudroid.db.MessageTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.DirectMessage;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.base.Refreshable;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class DmActivity extends BaseActivity implements Refreshable {
private static final String TAG = "DmActivity";
// Views.
private ListView mTweetList;
private Adapter mAdapter;
private Adapter mInboxAdapter;
private Adapter mSendboxAdapter;
Button inbox;
Button sendbox;
Button newMsg;
private int mDMType;
private static final int DM_TYPE_ALL = 0;
private static final int DM_TYPE_INBOX = 1;
private static final int DM_TYPE_SENDBOX = 2;
private TextView mProgressText;
private NavBar mNavbar;
private Feedback mFeedback;
// Tasks.
private GenericTask mRetrieveTask;
private GenericTask mDeleteTask;
private TaskListener mDeleteTaskListener = new TaskAdapter(){
@Override
public void onPreExecute(GenericTask task) {
updateProgress(getString(R.string.page_status_deleting));
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
mAdapter.refresh();
} else {
// Do nothing.
}
updateProgress("");
}
@Override
public String getName() {
return "DmDeleteTask";
}
};
private TaskListener mRetrieveTaskListener = new TaskAdapter(){
@Override
public void onPreExecute(GenericTask task) {
updateProgress(getString(R.string.page_status_refreshing));
}
@Override
public void onProgressUpdate(GenericTask task, Object params) {
draw();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putLong(Preferences.LAST_DM_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
draw();
goTop();
} else {
// Do nothing.
}
updateProgress("");
}
@Override
public String getName() {
return "DmRetrieve";
}
};
// Refresh data at startup if last refresh was this long ago or greater.
private static final long REFRESH_THRESHOLD = 5 * 60 * 1000;
private static final String EXTRA_USER = "user";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMS";
public static Intent createIntent() {
return createIntent("");
}
public static Intent createIntent(String user) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (!TextUtils.isEmpty(user)) {
intent.putExtra(EXTRA_USER, user);
}
return intent;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState))
{
setContentView(R.layout.dm);
mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this);
mNavbar.setHeaderTitle("我的私信");
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
bindFooterButtonEvent();
mTweetList = (ListView) findViewById(R.id.tweet_list);
mProgressText = (TextView) findViewById(R.id.progress_text);
TwitterDatabase db = getDb();
// Mark all as read.
db.markAllDmsRead();
setupAdapter(); // Make sure call bindFooterButtonEvent first
boolean shouldRetrieve = false;
long lastRefreshTime = mPreferences.getLong(
Preferences.LAST_DM_REFRESH_KEY, 0);
long nowTime = DateTimeHelper.getNowTime();
long diff = nowTime - lastRefreshTime;
Log.d(TAG, "Last refresh was " + diff + " ms ago.");
if (diff > REFRESH_THRESHOLD) {
shouldRetrieve = true;
} else if (isTrue(savedInstanceState, SIS_RUNNING_KEY)) {
// Check to see if it was running a send or retrieve task.
// It makes no sense to resend the send request (don't want dupes)
// so we instead retrieve (refresh) to see if the message has
// posted.
Log.d(TAG,
"Was last running a retrieve or send task. Let's refresh.");
shouldRetrieve = true;
}
if (shouldRetrieve) {
doRetrieve();
}
// Want to be able to focus on the items with the trackball.
// That way, we can navigate up and down by changing item focus.
mTweetList.setItemsCanFocus(true);
return true;
}else{
return false;
}
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
private static final String SIS_RUNNING_KEY = "running";
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
mRetrieveTask.cancel(true);
}
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
mDeleteTask.cancel(true);
}
super.onDestroy();
}
// UI helpers.
private void bindFooterButtonEvent() {
inbox = (Button) findViewById(R.id.inbox);
sendbox = (Button) findViewById(R.id.sendbox);
newMsg = (Button) findViewById(R.id.new_message);
inbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mDMType != DM_TYPE_INBOX) {
mDMType = DM_TYPE_INBOX;
inbox.setEnabled(false);
sendbox.setEnabled(true);
mTweetList.setAdapter(mInboxAdapter);
mInboxAdapter.refresh();
}
}
});
sendbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mDMType != DM_TYPE_SENDBOX) {
mDMType = DM_TYPE_SENDBOX;
inbox.setEnabled(true);
sendbox.setEnabled(false);
mTweetList.setAdapter(mSendboxAdapter);
mSendboxAdapter.refresh();
}
}
});
newMsg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(DmActivity.this, WriteDmActivity.class);
intent.putExtra("reply_to_id", 0); // TODO: 传入实际的reply_to_id
startActivity(intent);
}
});
}
private void setupAdapter() {
Cursor cursor = getDb().fetchAllDms(-1);
startManagingCursor(cursor);
mAdapter = new Adapter(this, cursor);
Cursor inboxCursor = getDb().fetchInboxDms();
startManagingCursor(inboxCursor);
mInboxAdapter = new Adapter(this, inboxCursor);
Cursor sendboxCursor = getDb().fetchSendboxDms();
startManagingCursor(sendboxCursor);
mSendboxAdapter = new Adapter(this, sendboxCursor);
mTweetList.setAdapter(mInboxAdapter);
registerForContextMenu(mTweetList);
inbox.setEnabled(false);
}
private class DmRetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams...params) {
List<DirectMessage> dmList;
ArrayList<Dm> dms = new ArrayList<Dm>();
TwitterDatabase db = getDb();
//ImageManager imageManager = getImageManager();
String maxId = db.fetchMaxDmId(false);
HashSet<String> imageUrls = new HashSet<String>();
try {
if (maxId != null) {
Paging paging = new Paging(maxId);
dmList = getApi().getDirectMessages(paging);
} else {
dmList = getApi().getDirectMessages();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, dmList));
for (DirectMessage directMessage : dmList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Dm dm;
dm = Dm.create(directMessage, false);
dms.add(dm);
imageUrls.add(dm.profileImageUrl);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
maxId = db.fetchMaxDmId(true);
try {
if (maxId != null) {
Paging paging = new Paging(maxId);
dmList = getApi().getSentDirectMessages(paging);
} else {
dmList = getApi().getSentDirectMessages();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
for (DirectMessage directMessage : dmList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Dm dm;
dm = Dm.create(directMessage, true);
dms.add(dm);
imageUrls.add(dm.profileImageUrl);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
db.addDms(dms, false);
// if (isCancelled()) {
// return TaskResult.CANCELLED;
// }
//
// publishProgress(null);
//
// for (String imageUrl : imageUrls) {
// if (!Utils.isEmpty(imageUrl)) {
// // Fetch image to cache.
// try {
// imageManager.put(imageUrl);
// } catch (IOException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
//
// if (isCancelled()) {
// return TaskResult.CANCELLED;
// }
// }
return TaskResult.OK;
}
}
private static class Adapter extends CursorAdapter {
public Adapter(Context context, Cursor cursor) {
super(context, cursor);
mInflater = LayoutInflater.from(context);
// TODO: 可使用:
//DM dm = MessageTable.parseCursor(cursor);
mUserTextColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_USER_SCREEN_NAME);
mTextColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_TEXT);
mProfileImageUrlColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_PROFILE_IMAGE_URL);
mCreatedAtColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_CREATED_AT);
mIsSentColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_IS_SENT);
}
private LayoutInflater mInflater;
private int mUserTextColumn;
private int mTextColumn;
private int mProfileImageUrlColumn;
private int mIsSentColumn;
private int mCreatedAtColumn;
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(R.layout.direct_message, parent,
false);
ViewHolder holder = new ViewHolder();
holder.userText = (TextView) view
.findViewById(R.id.tweet_user_text);
holder.tweetText = (TextView) view.findViewById(R.id.tweet_text);
holder.profileImage = (ImageView) view
.findViewById(R.id.profile_image);
holder.metaText = (TextView) view
.findViewById(R.id.tweet_meta_text);
view.setTag(holder);
return view;
}
class ViewHolder {
public TextView userText;
public TextView tweetText;
public ImageView profileImage;
public TextView metaText;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
int isSent = cursor.getInt(mIsSentColumn);
String user = cursor.getString(mUserTextColumn);
if (0 == isSent) {
holder.userText.setText(context
.getString(R.string.direct_message_label_from_prefix)
+ user);
} else {
holder.userText.setText(context
.getString(R.string.direct_message_label_to_prefix)
+ user);
}
TextHelper.setTweetText(holder.tweetText, cursor.getString(mTextColumn));
String profileImageUrl = cursor.getString(mProfileImageUrlColumn);
if (!TextUtils.isEmpty(profileImageUrl)) {
holder.profileImage
.setImageBitmap(TwitterApplication.mImageLoader
.get(profileImageUrl, new ImageLoaderCallback(){
@Override
public void refresh(String url,
Bitmap bitmap) {
Adapter.this.refresh();
}
}));
}
try {
holder.metaText.setText(DateTimeHelper
.getRelativeDate(TwitterDatabase.DB_DATE_FORMATTER
.parse(cursor.getString(mCreatedAtColumn))));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
}
public void refresh() {
getCursor().requery();
}
}
// Menu.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// FIXME: 将刷新功能绑定到顶部的刷新按钮上,主菜单中的刷新选项已删除
// case OPTIONS_MENU_ID_REFRESH:
// doRetrieve();
// return true;
case OPTIONS_MENU_ID_TWEETS:
launchActivity(TwitterActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_REPLIES:
launchActivity(MentionActivity.createIntent(this));
return true;
}
return super.onOptionsItemSelected(item);
}
private static final int CONTEXT_REPLY_ID = 0;
private static final int CONTEXT_DELETE_ID = 1;
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply);
menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Cursor cursor = (Cursor) mAdapter.getItem(info.position);
if (cursor == null) {
Log.w(TAG, "Selected item not available.");
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case CONTEXT_REPLY_ID:
String user_id = cursor.getString(cursor
.getColumnIndexOrThrow(MessageTable.FIELD_USER_ID));
Intent intent = WriteDmActivity.createIntent(user_id);
startActivity(intent);
return true;
case CONTEXT_DELETE_ID:
int idIndex = cursor.getColumnIndexOrThrow(MessageTable._ID);
String id = cursor.getString(idIndex);
doDestroy(id);
return true;
default:
return super.onContextItemSelected(item);
}
}
private void doDestroy(String id) {
Log.d(TAG, "Attempting delete.");
if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
mDeleteTask = new DmDeleteTask();
mDeleteTask.setListener(mDeleteTaskListener);
TaskParams params = new TaskParams();
params.put("id", id);
mDeleteTask.execute(params);
}
}
private class DmDeleteTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams...params) {
TaskParams param = params[0];
try {
String id = param.getString("id");
DirectMessage directMessage = getApi().destroyDirectMessage(id);
Dm.create(directMessage, false);
getDb().deleteDm(id);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
if (isCancelled()) {
return TaskResult.CANCELLED;
}
return TaskResult.OK;
}
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING){
return;
}else{
mRetrieveTask = new DmRetrieveTask();
mRetrieveTask.setFeedback(mFeedback);
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute();
}
}
public void goTop() {
mTweetList.setSelection(0);
}
public void draw() {
mAdapter.refresh();
mInboxAdapter.refresh();
mSendboxAdapter.refresh();
}
private void updateProgress(String msg) {
mProgressText.setText(msg);
}
}
| Java |
package com.ch_linghu.fanfoudroid.util;
import java.io.InputStream;
import java.io.OutputStream;
public class StreamUtils {
public static void CopyStream(InputStream is, OutputStream os)
{
final int buffer_size=1024;
try
{
byte[] bytes=new byte[buffer_size];
for(;;)
{
int count=is.read(bytes, 0, buffer_size);
if(count==-1)
break;
os.write(bytes, 0, count);
}
}
catch(Exception ex){}
}
} | Java |
package com.ch_linghu.fanfoudroid.util;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.HashMap;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
/**
* Debug Timer
*
* Usage:
* --------------------------------
* DebugTimer.start();
* DebugTimer.mark("my_mark1"); // optional
* DebugTimer.stop();
*
* System.out.println(DebugTimer.__toString()); // get report
* --------------------------------
*
* @author LDS
*/
public class DebugTimer {
public static final int START = 0;
public static final int END = 1;
private static HashMap<String, Long> mTime = new HashMap<String, Long>();
private static long mStartTime = 0;
private static long mLastTime = 0;
/**
* Start a timer
*/
public static void start() {
reset();
mStartTime = touch();
}
/**
* Mark current time
*
* @param tag mark tag
* @return
*/
public static long mark(String tag) {
long time = System.currentTimeMillis() - mStartTime;
mTime.put(tag, time);
return time;
}
/**
* Mark current time
*
* @param tag mark tag
* @return
*/
public static long between(String tag, int startOrEnd) {
if(TwitterApplication.DEBUG){
Log.v("DEBUG", tag + " " + startOrEnd);
}
switch (startOrEnd) {
case START:
return mark(tag);
case END:
long time = System.currentTimeMillis() - mStartTime - get(tag, mStartTime);
mTime.put(tag, time);
//touch();
return time;
default:
return -1;
}
}
public static long betweenStart(String tag) {
return between(tag, START);
}
public static long betweenEnd(String tag) {
return between(tag, END);
}
/**
* Stop timer
*
* @return result
*/
public static String stop() {
mTime.put("_TOTLE", touch() - mStartTime);
return __toString();
}
public static String stop(String tag) {
mark(tag);
return stop();
}
/**
* Get a mark time
*
* @param tag mark tag
* @return time(milliseconds) or NULL
*/
public static long get(String tag) {
return get(tag, 0);
}
public static long get(String tag, long defaultValue) {
if (mTime.containsKey(tag)) {
return mTime.get(tag);
}
return defaultValue;
}
/**
* Reset timer
*/
public static void reset() {
mTime = new HashMap<String, Long>();
mStartTime = 0;
mLastTime = 0;
}
/**
* static toString()
*
* @return
*/
public static String __toString() {
return "Debuger [time =" + mTime.toString() + "]";
}
private static long touch() {
return mLastTime = System.currentTimeMillis();
}
public static DebugProfile[] getProfile() {
DebugProfile[] profile = new DebugProfile[mTime.size()];
long totel = mTime.get("_TOTLE");
int i = 0;
for (String key : mTime.keySet()) {
long time = mTime.get(key);
profile[i] = new DebugProfile(key, time, time/(totel*1.0) );
i++;
}
try {
Arrays.sort(profile);
} catch (NullPointerException e) {
// in case item is null, do nothing
}
return profile;
}
public static String getProfileAsString() {
StringBuilder sb = new StringBuilder();
for (DebugProfile p : getProfile()) {
sb.append("TAG: ");
sb.append(p.tag);
sb.append("\t INC: ");
sb.append(p.inc);
sb.append("\t INCP: ");
sb.append(p.incPercent);
sb.append("\n");
}
return sb.toString();
}
@Override
public String toString() {
return __toString();
}
}
class DebugProfile implements Comparable<DebugProfile> {
private static NumberFormat percent = NumberFormat.getPercentInstance();
public String tag;
public long inc;
public String incPercent;
public DebugProfile(String tag, long inc, double incPercent) {
this.tag = tag;
this.inc = inc;
percent = new DecimalFormat("0.00#%");
this.incPercent = percent.format(incPercent);
}
@Override
public int compareTo(DebugProfile o) {
// TODO Auto-generated method stub
return (int) (o.inc - this.inc);
}
}
| Java |
package com.ch_linghu.fanfoudroid.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import android.util.Log;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
public class DateTimeHelper {
private static final String TAG = "DateTimeHelper";
// Wed Dec 15 02:53:36 +0000 2010
public static final DateFormat TWITTER_DATE_FORMATTER = new SimpleDateFormat(
"E MMM d HH:mm:ss Z yyyy", Locale.US);
public static final DateFormat TWITTER_SEARCH_API_DATE_FORMATTER = new SimpleDateFormat(
"E, d MMM yyyy HH:mm:ss Z", Locale.US); // TODO: Z -> z ?
public static final Date parseDateTime(String dateString) {
try {
Log.v(TAG, String.format("in parseDateTime, dateString=%s", dateString));
return TWITTER_DATE_FORMATTER.parse(dateString);
} catch (ParseException e) {
Log.w(TAG, "Could not parse Twitter date string: " + dateString);
return null;
}
}
// Handle "yyyy-MM-dd'T'HH:mm:ss.SSS" from sqlite
public static final Date parseDateTimeFromSqlite(String dateString) {
try {
Log.v(TAG, String.format("in parseDateTime, dateString=%s", dateString));
return TwitterDatabase.DB_DATE_FORMATTER.parse(dateString);
} catch (ParseException e) {
Log.w(TAG, "Could not parse Twitter date string: " + dateString);
return null;
}
}
public static final Date parseSearchApiDateTime(String dateString) {
try {
return TWITTER_SEARCH_API_DATE_FORMATTER.parse(dateString);
} catch (ParseException e) {
Log.w(TAG, "Could not parse Twitter search date string: "
+ dateString);
return null;
}
}
public static final DateFormat AGO_FULL_DATE_FORMATTER = new SimpleDateFormat(
"yyyy-MM-dd HH:mm");
public static String getRelativeDate(Date date) {
Date now = new Date();
String prefix = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_prefix);
String sec = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_sec);
String min = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_min);
String hour = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_hour);
String day = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_day);
String suffix = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_suffix);
// Seconds.
long diff = (now.getTime() - date.getTime()) / 1000;
if (diff < 0) {
diff = 0;
}
if (diff < 60) {
return diff + sec + suffix;
}
// Minutes.
diff /= 60;
if (diff < 60) {
return prefix + diff + min + suffix;
}
// Hours.
diff /= 60;
if (diff < 24) {
return prefix + diff + hour + suffix;
}
return AGO_FULL_DATE_FORMATTER.format(date);
}
public static long getNowTime() {
return Calendar.getInstance().getTime().getTime();
}
}
| Java |
package com.ch_linghu.fanfoudroid.util;
import java.io.File;
import java.io.IOException;
import android.os.Environment;
/**
* 对SD卡文件的管理
* @author ch.linghu
*
*/
public class FileHelper {
private static final String TAG = "FileHelper";
private static final String BASE_PATH="fanfoudroid";
public static File getBasePath() throws IOException{
File basePath = new File(Environment.getExternalStorageDirectory(),
BASE_PATH);
if (!basePath.exists()){
if (!basePath.mkdirs()){
throw new IOException(String.format("%s cannot be created!", basePath.toString()));
}
}
if (!basePath.isDirectory()){
throw new IOException(String.format("%s is not a directory!", basePath.toString()));
}
return basePath;
}
}
| Java |
package com.ch_linghu.fanfoudroid.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.text.Html;
import android.text.util.Linkify;
import android.util.Log;
import android.widget.TextView;
import android.widget.TextView.BufferType;
public class TextHelper {
private static final String TAG = "TextHelper";
public static String stringifyStream(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
return sb.toString();
}
private static HashMap<String, String> _userLinkMapping = new HashMap<String, String>();
private static final Pattern NAME_MATCHER = Pattern.compile("@.+?\\s");
private static final Linkify.MatchFilter NAME_MATCHER_MATCH_FILTER = new Linkify.MatchFilter() {
@Override
public final boolean acceptMatch(final CharSequence s, final int start,
final int end) {
String name = s.subSequence(start + 1, end).toString().trim();
boolean result = _userLinkMapping.containsKey(name);
return result;
}
};
private static final Linkify.TransformFilter NAME_MATCHER_TRANSFORM_FILTER = new Linkify.TransformFilter() {
@Override
public String transformUrl(Matcher match, String url) {
// TODO Auto-generated method stub
String name = url.subSequence(1, url.length()).toString().trim();
return _userLinkMapping.get(name);
}
};
private static final String TWITTA_USER_URL = "twitta://users/";
public static void linkifyUsers(TextView view) {
Linkify.addLinks(view, NAME_MATCHER, TWITTA_USER_URL,
NAME_MATCHER_MATCH_FILTER, NAME_MATCHER_TRANSFORM_FILTER);
}
private static final Pattern TAG_MATCHER = Pattern.compile("#\\w+#");
private static final Linkify.TransformFilter TAG_MATCHER_TRANSFORM_FILTER = new Linkify.TransformFilter() {
@Override
public final String transformUrl(Matcher match, String url) {
String result = url.substring(1, url.length() - 1);
return "%23" + result + "%23";
}
};
private static final String TWITTA_SEARCH_URL = "twitta://search/";
public static void linkifyTags(TextView view) {
Linkify.addLinks(view, TAG_MATCHER, TWITTA_SEARCH_URL, null,
TAG_MATCHER_TRANSFORM_FILTER);
}
private static Pattern USER_LINK = Pattern
.compile("@<a href=\"http:\\/\\/fanfou\\.com\\/(.*?)\" class=\"former\">(.*?)<\\/a>");
private static String preprocessText(String text) {
// 处理HTML格式返回的用户链接
Matcher m = USER_LINK.matcher(text);
while (m.find()) {
_userLinkMapping.put(m.group(2), m.group(1));
Log.d(TAG,
String.format("Found mapping! %s=%s", m.group(2),
m.group(1)));
}
// 将User Link的连接去掉
StringBuffer sb = new StringBuffer();
m = USER_LINK.matcher(text);
while (m.find()) {
m.appendReplacement(sb, "@$2");
}
m.appendTail(sb);
return sb.toString();
}
public static String getSimpleTweetText(String text) {
return Html.fromHtml(text).toString();
}
public static void setSimpleTweetText(TextView textView, String text) {
String processedText = getSimpleTweetText(text);
textView.setText(processedText);
}
public static void setTweetText(TextView textView, String text) {
String processedText = preprocessText(text);
textView.setText(Html.fromHtml(processedText), BufferType.SPANNABLE);
Linkify.addLinks(textView, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES);
linkifyUsers(textView);
linkifyTags(textView);
_userLinkMapping.clear();
}
/**
* 从消息中获取全部提到的人,将它们按先后顺序放入一个列表
* @param msg 消息文本
* @return 消息中@的人的列表,按顺序存放
*/
public static List<String> getMentions(String msg){
ArrayList<String> mentionList = new ArrayList<String>();
final Pattern p = Pattern.compile("@(.*?)\\s");
final int MAX_NAME_LENGTH = 12; //简化判断,无论中英文最长12个字
Matcher m = p.matcher(msg);
while(m.find()){
String mention = m.group(1);
//过长的名字就忽略(不是合法名字) +1是为了补上“@”所占的长度
if (mention.length() <= MAX_NAME_LENGTH+1){
//避免重复名字
if (!mentionList.contains(mention)){
mentionList.add(m.group(1));
}
}
}
return mentionList;
}
}
| Java |
/*
* Copyright (C) 2009 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.ch_linghu.fanfoudroid;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.app.ImageCache;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.http.HttpClient;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.task.TweetCommonTask;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
public class StatusActivity extends BaseActivity {
private static final String TAG = "StatusActivity";
private static final String SIS_RUNNING_KEY = "running";
private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid";
private static final String EXTRA_TWEET = "tweet";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.STATUS";
static final private int CONTEXT_REFRESH_ID = 0x0001;
static final private int CONTEXT_CLIPBOARD_ID = 0x0002;
static final private int CONTEXT_DELETE_ID = 0x0003;
// Task TODO: tasks
private GenericTask mReplyTask;
private GenericTask mStatusTask;
private GenericTask mPhotoTask; // TODO: 压缩图片,提供获取图片的过程中可取消获取
private GenericTask mFavTask;
private GenericTask mDeleteTask;
private NavBar mNavbar;
private Feedback mFeedback;
private TaskListener mReplyTaskListener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
showReplyStatus(replyTweet);
StatusActivity.this.mFeedback.success("");
}
@Override
public String getName() {
return "GetReply";
}
};
private TaskListener mStatusTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
clean();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
StatusActivity.this.mFeedback.success("");
draw();
}
@Override
public String getName() {
return "GetStatus";
}
};
private TaskListener mPhotoTaskListener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
status_photo.setImageBitmap(mPhotoBitmap);
} else {
status_photo.setVisibility(View.GONE);
}
StatusActivity.this.mFeedback.success("");
}
@Override
public String getName() {
// TODO Auto-generated method stub
return "GetPhoto";
}
};
private TaskListener mFavTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "FavoriteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onFavSuccess();
} else if (result == TaskResult.IO_ERROR) {
onFavFailure();
}
}
};
private TaskListener mDeleteTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "DeleteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onDeleteSuccess();
} else if (result == TaskResult.IO_ERROR) {
onDeleteFailure();
}
}
};
// View
private TextView tweet_screen_name;
private TextView tweet_text;
private TextView tweet_user_info;
private ImageView profile_image;
private TextView tweet_source;
private TextView tweet_created_at;
private ImageButton btn_person_more;
private ImageView status_photo = null; // if exists
private ViewGroup reply_wrap;
private TextView reply_status_text = null; // if exists
private TextView reply_status_date = null; // if exists
private ImageButton tweet_fav;
private Tweet tweet = null;
private Tweet replyTweet = null; // if exists
private HttpClient mClient;
private Bitmap mPhotoBitmap = ImageCache.mDefaultBitmap; // if exists
public static Intent createIntent(Tweet tweet) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.putExtra(EXTRA_TWEET, tweet);
return intent;
}
private static Pattern PHOTO_PAGE_LINK = Pattern
.compile("http://fanfou.com(/photo/[-a-zA-Z0-9+&@#%?=~_|!:,.;]*[-a-zA-Z0-9+&@#%=~_|])");
private static Pattern PHOTO_SRC_LINK = Pattern
.compile("src=\"(http:\\/\\/photo\\.fanfou\\.com\\/.*?)\"");
/**
* 获得消息中的照片页面链接
*
* @param text
* 消息文本
* @param size
* 照片尺寸
* @return 照片页面的链接,若不存在,则返回null
*/
public static String getPhotoPageLink(String text, String size) {
Matcher m = PHOTO_PAGE_LINK.matcher(text);
if (m.find()) {
String THUMBNAIL = TwitterApplication.mContext
.getString(R.string.pref_photo_preview_type_thumbnail);
String MIDDLE = TwitterApplication.mContext
.getString(R.string.pref_photo_preview_type_middle);
String ORIGINAL = TwitterApplication.mContext
.getString(R.string.pref_photo_preview_type_original);
if (size.equals(THUMBNAIL) || size.equals(MIDDLE)) {
return "http://m.fanfou.com" + m.group(1);
} else if (size.endsWith(ORIGINAL)) {
return m.group(0);
} else {
return null;
}
} else {
return null;
}
}
/**
* 获得照片页面中的照片链接
*
* @param pageHtml
* 照片页面文本
* @return 照片链接,若不存在,则返回null
*/
public static String getPhotoURL(String pageHtml) {
Matcher m = PHOTO_SRC_LINK.matcher(pageHtml);
if (m.find()) {
return m.group(1);
} else {
return null;
}
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
mClient = getApi().getHttpClient();
// Intent & Action & Extras
Intent intent = getIntent();
String action = intent.getAction();
Bundle extras = intent.getExtras();
// Must has extras
if (null == extras) {
Log.e(TAG, this.getClass().getName() + " must has extras.");
finish();
return false;
}
setContentView(R.layout.status);
mNavbar = new NavBar(NavBar.HEADER_STYLE_BACK, this);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
findView();
bindNavBarListener();
// Set view with intent data
this.tweet = extras.getParcelable(EXTRA_TWEET);
draw();
bindFooterBarListener();
bindReplyViewListener();
return true;
} else {
return false;
}
}
private void findView() {
tweet_screen_name = (TextView) findViewById(R.id.tweet_screen_name);
tweet_user_info = (TextView) findViewById(R.id.tweet_user_info);
tweet_text = (TextView) findViewById(R.id.tweet_text);
tweet_source = (TextView) findViewById(R.id.tweet_source);
profile_image = (ImageView) findViewById(R.id.profile_image);
tweet_created_at = (TextView) findViewById(R.id.tweet_created_at);
btn_person_more = (ImageButton) findViewById(R.id.person_more);
tweet_fav = (ImageButton) findViewById(R.id.tweet_fav);
reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap);
reply_status_text = (TextView) findViewById(R.id.reply_status_text);
reply_status_date = (TextView) findViewById(R.id.reply_tweet_created_at);
status_photo = (ImageView) findViewById(R.id.status_photo);
}
private void bindNavBarListener() {
mNavbar.getRefreshButton().setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
doGetStatus(tweet.id);
}
});
}
private void bindFooterBarListener() {
// person_more
btn_person_more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = ProfileActivity.createIntent(tweet.userId);
startActivity(intent);
}
});
// Footer bar
TextView footer_btn_share = (TextView) findViewById(R.id.footer_btn_share);
TextView footer_btn_reply = (TextView) findViewById(R.id.footer_btn_reply);
TextView footer_btn_retweet = (TextView) findViewById(R.id.footer_btn_retweet);
TextView footer_btn_fav = (TextView) findViewById(R.id.footer_btn_fav);
TextView footer_btn_more = (TextView) findViewById(R.id.footer_btn_more);
// 分享
footer_btn_share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(
Intent.EXTRA_TEXT,
String.format("@%s %s", tweet.screenName,
TextHelper.getSimpleTweetText(tweet.text)));
startActivity(Intent.createChooser(intent,
getString(R.string.cmenu_share)));
}
});
// 回复
footer_btn_reply.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteActivity.createNewReplyIntent(
tweet.text, tweet.screenName, tweet.id);
startActivity(intent);
}
});
// 转发
footer_btn_retweet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteActivity.createNewRepostIntent(
StatusActivity.this, tweet.text, tweet.screenName,
tweet.id);
startActivity(intent);
}
});
// 收藏/取消收藏
footer_btn_fav.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (tweet.favorited.equals("true")) {
doFavorite("del", tweet.id);
} else {
doFavorite("add", tweet.id);
}
}
});
// TODO: 更多操作
registerForContextMenu(footer_btn_more);
footer_btn_more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openContextMenu(v);
}
});
}
private void bindReplyViewListener() {
// 点击回复消息打开新的Status界面
OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!TextUtils.isEmpty(tweet.inReplyToStatusId)) {
if (replyTweet == null) {
Log.w(TAG, "Selected item not available.");
} else {
launchActivity(StatusActivity.createIntent(replyTweet));
}
}
}
};
reply_wrap.setOnClickListener(listener);
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause.");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart.");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume.");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart.");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop.");
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mReplyTask != null
&& mReplyTask.getStatus() == GenericTask.Status.RUNNING) {
mReplyTask.cancel(true);
}
if (mPhotoTask != null
&& mPhotoTask.getStatus() == GenericTask.Status.RUNNING) {
mPhotoTask.cancel(true);
}
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
mFavTask.cancel(true);
}
super.onDestroy();
}
private ImageLoaderCallback callback = new ImageLoaderCallback() {
@Override
public void refresh(String url, Bitmap bitmap) {
profile_image.setImageBitmap(bitmap);
}
};
private void clean() {
tweet_screen_name.setText("");
tweet_text.setText("");
tweet_created_at.setText("");
tweet_source.setText("");
tweet_user_info.setText("");
tweet_fav.setEnabled(false);
profile_image.setImageBitmap(ImageCache.mDefaultBitmap);
status_photo.setVisibility(View.GONE);
ViewGroup reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap);
reply_wrap.setVisibility(View.GONE);
}
private void draw() {
Log.d(TAG, "draw");
String PHOTO_PREVIEW_TYPE_NONE = getString(R.string.pref_photo_preview_type_none);
String PHOTO_PREVIEW_TYPE_THUMBNAIL = getString(R.string.pref_photo_preview_type_thumbnail);
String PHOTO_PREVIEW_TYPE_MIDDLE = getString(R.string.pref_photo_preview_type_middle);
String PHOTO_PREVIEW_TYPE_ORIGINAL = getString(R.string.pref_photo_preview_type_original);
SharedPreferences pref = getPreferences();
String photoPreviewSize = pref.getString(Preferences.PHOTO_PREVIEW,
PHOTO_PREVIEW_TYPE_ORIGINAL);
boolean forceShowAllImage = pref.getBoolean(
Preferences.FORCE_SHOW_ALL_IMAGE, false);
tweet_screen_name.setText(tweet.screenName);
TextHelper.setTweetText(tweet_text, tweet.text);
tweet_created_at.setText(DateTimeHelper.getRelativeDate(tweet.createdAt));
tweet_source.setText(getString(R.string.tweet_source_prefix)
+ tweet.source);
tweet_user_info.setText(tweet.userId);
boolean isFav = (tweet.favorited.equals("true")) ? true : false;
tweet_fav.setEnabled(isFav);
// Bitmap mProfileBitmap =
// TwitterApplication.mImageManager.get(tweet.profileImageUrl);
profile_image
.setImageBitmap(TwitterApplication.mImageLoader
.get(tweet.profileImageUrl, callback));
// has photo
if (!photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_NONE)) {
String photoLink;
boolean isPageLink = false;
if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_THUMBNAIL)) {
photoLink = tweet.thumbnail_pic;
} else if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_MIDDLE)) {
photoLink = tweet.bmiddle_pic;
} else if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_ORIGINAL)) {
photoLink = tweet.original_pic;
} else {
Log.e(TAG, "Invalid Photo Preview Size Type");
photoLink = "";
}
// 如果选用了强制显示则再尝试分析图片链接
if (forceShowAllImage) {
photoLink = getPhotoPageLink(tweet.text, photoPreviewSize);
isPageLink = true;
}
if (!TextUtils.isEmpty(photoLink)) {
status_photo.setVisibility(View.VISIBLE);
status_photo.setImageBitmap(mPhotoBitmap);
doGetPhoto(photoLink, isPageLink);
}
} else {
status_photo.setVisibility(View.GONE);
}
// has reply
if (!TextUtils.isEmpty(tweet.inReplyToStatusId)) {
ViewGroup reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap);
reply_wrap.setVisibility(View.VISIBLE);
reply_status_text = (TextView) findViewById(R.id.reply_status_text);
reply_status_date = (TextView) findViewById(R.id.reply_tweet_created_at);
doGetReply(tweet.inReplyToStatusId);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mReplyTask != null
&& mReplyTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
private String fetchWebPage(String url) throws HttpException {
Log.d(TAG, "Fetching WebPage: " + url);
Response res = mClient.get(url);
return res.asString();
}
private Bitmap fetchPhotoBitmap(String url) throws HttpException,
IOException {
Log.d(TAG, "Fetching Photo: " + url);
Response res = mClient.get(url);
//FIXME:这里使用了一个作废的方法,如何修正?
InputStream is = res.asStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
return bitmap;
}
private void doGetReply(String status_id) {
Log.d(TAG, "Attempting get status task.");
mFeedback.start("");
if (mReplyTask != null
&& mReplyTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mReplyTask = new GetReplyTask();
mReplyTask.setListener(mReplyTaskListener);
TaskParams params = new TaskParams();
params.put("reply_id", status_id);
mReplyTask.execute(params);
}
}
private class GetReplyTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
com.ch_linghu.fanfoudroid.fanfou.Status status;
try {
String reply_id = param.getString("reply_id");
if (!TextUtils.isEmpty(reply_id)) {
// 首先查看是否在数据库中,如不在再去获取
replyTweet = getDb().queryTweet(reply_id, -1);
if (replyTweet == null) {
status = getApi().showStatus(reply_id);
replyTweet = Tweet.create(status);
}
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
private void doGetStatus(String status_id) {
Log.d(TAG, "Attempting get status task.");
mFeedback.start("");
if (mStatusTask != null
&& mStatusTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mStatusTask = new GetStatusTask();
mStatusTask.setListener(mStatusTaskListener);
TaskParams params = new TaskParams();
params.put("id", status_id);
mStatusTask.execute(params);
}
}
private class GetStatusTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
com.ch_linghu.fanfoudroid.fanfou.Status status;
try {
String id = param.getString("id");
if (!TextUtils.isEmpty(id)) {
status = getApi().showStatus(id);
mFeedback.update(80);
tweet = Tweet.create(status);
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
mFeedback.update(99);
return TaskResult.OK;
}
}
private void doGetPhoto(String photoPageURL, boolean isPageLink) {
mFeedback.start("");
if (mPhotoTask != null
&& mPhotoTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mPhotoTask = new GetPhotoTask();
mPhotoTask.setListener(mPhotoTaskListener);
TaskParams params = new TaskParams();
params.put("photo_url", photoPageURL);
params.put("is_page_link", isPageLink);
mPhotoTask.execute(params);
}
}
private class GetPhotoTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
try {
String photoURL = param.getString("photo_url");
boolean isPageLink = param.getBoolean("is_page_link");
if (!TextUtils.isEmpty(photoURL)) {
if (isPageLink) {
String pageHtml = fetchWebPage(photoURL);
String photoSrcURL = getPhotoURL(pageHtml);
if (photoSrcURL != null) {
mPhotoBitmap = fetchPhotoBitmap(photoSrcURL);
}
} else {
mPhotoBitmap = fetchPhotoBitmap(photoURL);
}
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
private void showReplyStatus(Tweet tweet) {
if (tweet != null) {
String text = tweet.screenName + " : " + tweet.text;
TextHelper.setSimpleTweetText(reply_status_text, text);
reply_status_date.setText(DateTimeHelper.getRelativeDate(tweet.createdAt));
} else {
String msg = MessageFormat.format(
getString(R.string.status_status_reply_cannot_display),
this.tweet.inReplyToScreenName);
reply_status_text.setText(msg);
}
}
public void onDeleteFailure() {
Log.e(TAG, "Delete failed");
}
public void onDeleteSuccess() {
finish();
}
// for HasFavorite interface
public void doFavorite(String action, String id) {
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
if (!TextUtils.isEmpty(id)) {
Log.d(TAG, "doFavorite.");
mFavTask = new TweetCommonTask.FavoriteTask(this);
mFavTask.setListener(mFavTaskListener);
TaskParams param = new TaskParams();
param.put("action", action);
param.put("id", id);
mFavTask.execute(param);
}
}
}
public void onFavSuccess() {
// updateProgress(getString(R.string.refreshing));
if (((TweetCommonTask.FavoriteTask) mFavTask).getType().equals(
TweetCommonTask.FavoriteTask.TYPE_ADD)) {
tweet.favorited = "true";
tweet_fav.setEnabled(true);
} else {
tweet.favorited = "false";
tweet_fav.setEnabled(false);
}
}
public void onFavFailure() {
// updateProgress(getString(R.string.refreshing));
}
private void doDelete(String id) {
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mDeleteTask = new TweetCommonTask.DeleteTask(this);
mDeleteTask.setListener(mDeleteTaskListener);
TaskParams params = new TaskParams();
params.put("id", id);
mDeleteTask.execute(params);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CONTEXT_REFRESH_ID:
doGetStatus(tweet.id);
return true;
case CONTEXT_CLIPBOARD_ID:
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(TextHelper.getSimpleTweetText(tweet.text));
return true;
case CONTEXT_DELETE_ID:
doDelete(tweet.id);
return true;
}
return super.onContextItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
menu.setHeaderIcon(android.R.drawable.ic_menu_more);
menu.setHeaderTitle(getString(R.string.cmenu_more));
menu.add(0, CONTEXT_REFRESH_ID, 0, R.string.omenu_refresh);
menu.add(0, CONTEXT_CLIPBOARD_ID, 0, R.string.cmenu_clipboard);
if (tweet.userId.equals(TwitterApplication.getMyselfId())) {
menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete);
}
}
} | Java |
package com.ch_linghu.fanfoudroid;
import java.text.MessageFormat;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.UserArrayBaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter;
public class FollowingActivity extends UserArrayBaseActivity {
private ListView mUserList;
private UserArrayAdapter mAdapter;
private String userId;
private String userName;
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FOLLOWING";
private static final String USER_ID = "userId";
private static final String USER_NAME = "userName";
private int currentPage=1;
String myself="";
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
this.userId = extras.getString(USER_ID);
this.userName = extras.getString(USER_NAME);
} else {
// 获取登录用户id
userId=TwitterApplication.getMyselfId();
userName = TwitterApplication.getMyselfName();
}
if(super._onCreate(savedInstanceState)){
myself = TwitterApplication.getMyselfId();
if(getUserId()==myself){
mNavbar.setHeaderTitle(MessageFormat.format(
getString(R.string.profile_friends_count_title), "我"));
} else {
mNavbar.setHeaderTitle(MessageFormat.format(
getString(R.string.profile_friends_count_title), userName));
}
return true;
}else{
return false;
}
}
/*
* 添加取消关注按钮
* @see com.ch_linghu.fanfoudroid.ui.base.UserListBaseActivity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo)
*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if(getUserId()==myself){
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
User user = getContextItemUser(info.position);
menu.add(0,CONTENT_DEL_FRIEND,0,getResources().getString(R.string.cmenu_user_addfriend_prefix)+user.screenName+getResources().getString(R.string.cmenu_user_friend_suffix));
}
}
public static Intent createIntent(String userId, String userName) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(USER_ID, userId);
intent.putExtra(USER_NAME, userName);
return intent;
}
@Override
public Paging getNextPage() {
currentPage+=1;
return new Paging(currentPage);
}
@Override
protected String getUserId() {
return this.userId;
}
@Override
public Paging getCurrentPage() {
return new Paging(this.currentPage);
}
@Override
protected List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers(
String userId, Paging page) throws HttpException {
return getApi().getFriendsStatuses(userId, page);
}
}
| Java |
package com.ch_linghu.fanfoudroid;
import java.util.HashSet;
//import org.acra.ReportingInteractionMode;
//import org.acra.annotation.ReportsCrashes;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.Configuration;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.fanfou.Weibo;
import com.ch_linghu.fanfoudroid.http.HttpException;
//@ReportsCrashes(formKey="dHowMk5LMXQweVJkWGthb1E1T1NUUHc6MQ",
// mode = ReportingInteractionMode.NOTIFICATION,
// resNotifTickerText = R.string.crash_notif_ticker_text,
// resNotifTitle = R.string.crash_notif_title,
// resNotifText = R.string.crash_notif_text,
// resNotifIcon = android.R.drawable.stat_notify_error, // optional. default is a warning sign
// resDialogText = R.string.crash_dialog_text,
// resDialogIcon = android.R.drawable.ic_dialog_info, //optional. default is a warning sign
// resDialogTitle = R.string.crash_dialog_title, // optional. default is your application name
// resDialogCommentPrompt = R.string.crash_dialog_comment_prompt, // optional. when defined, adds a user text field input with this text resource as a label
// resDialogOkToast = R.string.crash_dialog_ok_toast // optional. displays a Toast message when the user accepts to send a report.
//)
public class TwitterApplication extends Application {
public static final String TAG = "TwitterApplication";
// public static ImageManager mImageManager;
public static LazyImageLoader mImageLoader;
public static TwitterDatabase mDb;
public static Weibo mApi; // new API
public static Context mContext;
public static SharedPreferences mPref;
public static int networkType = 0;
public final static boolean DEBUG = Configuration.getDebug();
// FIXME:获取登录用户id, 据肉眼观察,刚注册的用户系统分配id都是~开头的,因为不知道
// 用户何时去修改这个ID,目前只有把所有以~开头的ID在每次需要UserId时都去服务器
// 取一次数据,看看新的ID是否已经设定,判断依据是是否以~开头。这么判断会把有些用户
// 就是把自己ID设置的以~开头的造成,每次都需要去服务器取数。
// 只是简单处理了mPref没有CURRENT_USER_ID的情况,因为用户在登陆时,肯定会记一个CURRENT_USER_ID
// 到mPref.
private static void fetchMyselfInfo() {
User myself;
try {
myself = TwitterApplication.mApi.showUser(TwitterApplication.mApi.getUserId());
TwitterApplication.mPref.edit().putString(
Preferences.CURRENT_USER_ID, myself.getId()).commit();
TwitterApplication.mPref.edit().putString(
Preferences.CURRENT_USER_SCREEN_NAME, myself.getScreenName()).commit();
} catch (HttpException e) {
e.printStackTrace();
}
}
public static String getMyselfId() {
if (!mPref.contains(Preferences.CURRENT_USER_ID)
|| mPref.getString(Preferences.CURRENT_USER_ID, "~")
.startsWith("~")) {
fetchMyselfInfo();
}
return mPref.getString(Preferences.CURRENT_USER_ID, "~");
}
public static String getMyselfName() {
if (!mPref.contains(Preferences.CURRENT_USER_ID)
|| !mPref.contains(Preferences.CURRENT_USER_SCREEN_NAME)
|| mPref.getString(Preferences.CURRENT_USER_ID, "~")
.startsWith("~")) {
fetchMyselfInfo();
}
return mPref.getString(Preferences.CURRENT_USER_SCREEN_NAME, "");
}
@Override
public void onCreate() {
// FIXME: StrictMode类在1.6以下的版本中没有,会导致类加载失败。
// 因此将这些代码设成关闭状态,仅在做性能调试时才打开。
// //NOTE: StrictMode模式需要2.3+ API支持。
// if (DEBUG){
// StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
// .detectAll()
// .penaltyLog()
// .build());
// StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
// .detectAll()
// .penaltyLog()
// .build());
// }
super.onCreate();
mContext = this.getApplicationContext();
// mImageManager = new ImageManager(this);
mImageLoader = new LazyImageLoader();
mApi = new Weibo();
mDb = TwitterDatabase.getInstance(this);
mPref = PreferenceManager.getDefaultSharedPreferences(this);
String username = mPref.getString(Preferences.USERNAME_KEY, "");
String password = mPref.getString(Preferences.PASSWORD_KEY, "");
password = LoginActivity.decryptPassword(password);
if (Weibo.isValidCredentials(username, password)) {
mApi.setCredentials(username, password); // Setup API and HttpClient
}
// 为cmwap用户设置代理上网
String type = getNetworkType();
if (null != type && type.equalsIgnoreCase("cmwap")) {
Toast.makeText(this, "您当前正在使用cmwap网络上网.", Toast.LENGTH_SHORT);
mApi.getHttpClient().setProxy("10.0.0.172", 80, "http");
}
}
public String getNetworkType() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
//NetworkInfo mobNetInfo = connectivityManager
// .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (activeNetInfo != null){
return activeNetInfo.getExtraInfo(); // 接入点名称: 此名称可被用户任意更改 如: cmwap, cmnet,
// internet ...
}else{
return null;
}
}
@Override
public void onTerminate() {
//FIXME: 根据android文档,onTerminate不会在真实机器上被执行到
//因此这些清理动作需要再找合适的地方放置,以确保执行。
cleanupImages();
mDb.close();
Toast.makeText(this, "exit app", Toast.LENGTH_LONG);
super.onTerminate();
}
private void cleanupImages() {
HashSet<String> keepers = new HashSet<String>();
Cursor cursor = mDb.fetchAllTweets(StatusTable.TYPE_HOME);
if (cursor.moveToFirst()) {
int imageIndex = cursor
.getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL);
do {
keepers.add(cursor.getString(imageIndex));
} while (cursor.moveToNext());
}
cursor.close();
cursor = mDb.fetchAllDms(-1);
if (cursor.moveToFirst()) {
int imageIndex = cursor
.getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL);
do {
keepers.add(cursor.getString(imageIndex));
} while (cursor.moveToNext());
}
cursor.close();
mImageLoader.getImageManager().cleanup(keepers);
}
}
| Java |
/*
* 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 android.test.ActivityInstrumentationTestCase2;
/**
* This is a simple framework for a test of an Application. See
* {@link android.test.ApplicationTestCase ApplicationTestCase} for more
* information on how to write and extend Application tests.
* <p/>
* To run this test, you can type:
* adb shell am instrument -w \
* -e class org.connectbot.HostListActivityTest \
* org.connectbot.tests/android.test.InstrumentationTestRunner
*/
public class SettingsActivityTest extends
ActivityInstrumentationTestCase2<SettingsActivity> {
public SettingsActivityTest() {
super("org.connectbot", SettingsActivity.class);
}
public void testOpenMenu() {
SettingsActivity a = getActivity();
a.openOptionsMenu();
a.closeOptionsMenu();
}
}
| Java |
/*
* 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 org.connectbot.bean.HostBean;
import org.connectbot.mock.BeanTestCase;
import android.test.AndroidTestCase;
/**
* @author Kenny Root
*
*/
public class HostBeanTest extends AndroidTestCase {
private static final String[] FIELDS = { "nickname", "username",
"hostname", "port" };
HostBean host1;
HostBean host2;
@Override
protected void setUp() throws Exception {
super.setUp();
host1 = new HostBean();
host1.setNickname("Home");
host1.setUsername("bob");
host1.setHostname("server.example.com");
host1.setPort(22);
host2 = new HostBean();
host2.setNickname("Home");
host2.setUsername("bob");
host2.setHostname("server.example.com");
host2.setPort(22);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public void testIdEquality() {
host1.setId(1);
host2.setId(1);
assertTrue(host1.equals(host2));
assertTrue(host1.hashCode() == host2.hashCode());
}
public void testIdInequality() {
host1.setId(1);
host2.setId(2);
// HostBeans shouldn't be equal when their IDs are not the same
assertFalse("HostBeans are equal when their ID is different", host1
.equals(host2));
assertFalse("HostBean hash codes are equal when their ID is different",
host1.hashCode() == host2.hashCode());
}
public void testIdEquality2() {
host1.setId(1);
host2.setId(1);
host2.setNickname("Work");
host2.setUsername("alice");
host2.setHostname("client.example.com");
assertTrue(
"HostBeans are not equal when their ID is the same but other fields are different!",
host1.equals(host2));
assertTrue(
"HostBeans hashCodes are not equal when their ID is the same but other fields are different!",
host1.hashCode() == host2.hashCode());
}
public void testBeanMeetsEqualsContract() {
BeanTestCase.assertMeetsEqualsContract(HostBean.class, FIELDS);
}
public void testBeanMeetsHashCodeContract() {
BeanTestCase.assertMeetsHashCodeContract(HostBean.class, FIELDS);
}
}
| Java |
/*
* 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 org.connectbot.bean.SelectionArea;
import android.test.AndroidTestCase;
/**
* @author Kenny Root
*
*/
public class SelectionAreaTest extends AndroidTestCase {
private static final int WIDTH = 80;
private static final int HEIGHT = 24;
public void testCreate() {
SelectionArea sa = new SelectionArea();
assertTrue(sa.getLeft() == 0);
assertTrue(sa.getRight() == 0);
assertTrue(sa.getTop() == 0);
assertTrue(sa.getBottom() == 0);
assertTrue(sa.isSelectingOrigin());
}
public void testCheckMovement() {
SelectionArea sa = new SelectionArea();
sa.setBounds(WIDTH, HEIGHT);
sa.incrementColumn();
// Should be (1,0) to (1,0)
assertTrue(sa.getLeft() == 1);
assertTrue(sa.getTop() == 0);
assertTrue(sa.getRight() == 1);
assertTrue(sa.getBottom() == 0);
sa.finishSelectingOrigin();
assertFalse(sa.isSelectingOrigin());
sa.incrementColumn();
sa.incrementColumn();
// Should be (1,0) to (3,0)
assertTrue(sa.getLeft() == 1);
assertTrue(sa.getTop() == 0);
assertTrue(sa.getRight() == 3);
assertTrue(sa.getBottom() == 0);
}
public void testBounds() {
SelectionArea sa = new SelectionArea();
sa.setBounds(WIDTH, HEIGHT);
for (int i = 0; i <= WIDTH; i++)
sa.decrementColumn();
assertTrue("Left bound should be 0, but instead is " + sa.getLeft(),
sa.getLeft() == 0);
for (int i = 0; i <= HEIGHT; i++)
sa.decrementRow();
assertTrue("Top bound should be 0, but instead is " + sa.getLeft(),
sa.getTop() == 0);
sa.finishSelectingOrigin();
for (int i = 0; i <= WIDTH * 2; i++)
sa.incrementColumn();
assertTrue("Left bound should be 0, but instead is " + sa.getLeft(),
sa.getLeft() == 0);
assertTrue("Right bound should be " + (WIDTH - 1) + ", but instead is " + sa.getRight(),
sa.getRight() == (WIDTH - 1));
for (int i = 0; i <= HEIGHT * 2; i++)
sa.incrementRow();
assertTrue("Bottom bound should be " + (HEIGHT - 1) + ", but instead is " + sa.getBottom(),
sa.getBottom() == (HEIGHT - 1));
assertTrue("Top bound should be 0, but instead is " + sa.getTop(),
sa.getTop() == 0);
}
public void testSetThenMove() {
SelectionArea sa = new SelectionArea();
sa.setBounds(WIDTH, HEIGHT);
int targetColumn = WIDTH / 2;
int targetRow = HEIGHT / 2;
sa.setColumn(targetColumn);
sa.setRow(targetRow);
sa.incrementRow();
assertTrue("Row should be " + (targetRow + 1) + ", but instead is " + sa.getTop(),
sa.getTop() == (targetRow + 1));
sa.decrementColumn();
assertTrue("Column shold be " + (targetColumn - 1) + ", but instead is " + sa.getLeft(),
sa.getLeft() == (targetColumn - 1));
sa.finishSelectingOrigin();
sa.setRow(0);
sa.setColumn(0);
sa.incrementRow();
sa.decrementColumn();
assertTrue("Top row should be 1, but instead is " + sa.getTop(),
sa.getTop() == 1);
assertTrue("Left column shold be 0, but instead is " + sa.getLeft(),
sa.getLeft() == 0);
assertTrue("Bottom row should be " + (targetRow + 1) + ", but instead is " + sa.getBottom(),
sa.getBottom() == (targetRow + 1));
assertTrue("Right column shold be " + (targetColumn - 1) + ", but instead is " + sa.getRight(),
sa.getRight() == (targetColumn - 1));
}
}
| Java |
/*
* 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 android.app.Activity;
import android.test.ActivityInstrumentationTestCase2;
/**
* This is a simple framework for a test of an Application. See
* {@link android.test.ApplicationTestCase ApplicationTestCase} for more
* information on how to write and extend Application tests.
* <p/>
* To run this test, you can type: adb shell am instrument -w \ -e class
* org.connectbot.HostListActivityTest \
* org.connectbot.tests/android.test.InstrumentationTestRunner
*/
public class HostListActivityTest extends ActivityInstrumentationTestCase2<HostListActivity> {
private Activity mActivity;
public HostListActivityTest() {
super("org.connectbot", HostListActivity.class);
}
@Override
protected void setUp() throws Exception {
super.setUp();
setActivityInitialTouchMode(false);
mActivity = getActivity();
}
}
| Java |
/*
* 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.util;
import java.util.Arrays;
import android.test.AndroidTestCase;
/**
* @author Kenny Root
*
*/
public class PubkeyUtilsTest extends AndroidTestCase {
public void testEncodeHex_Null_Failure() throws Exception {
try {
PubkeyUtils.encodeHex(null);
fail("Should throw null pointer exception when argument is null");
} catch (NullPointerException e) {
// success
}
}
public void testEncodeHex_Success() throws Exception {
byte[] input = {(byte) 0xFF, 0x00, (byte) 0xA5, 0x5A, 0x12, 0x23};
String expected = "ff00a55a1223";
assertEquals("Encoded hex should match expected",
PubkeyUtils.encodeHex(input), expected);
}
public void testSha256_Empty_Success() throws Exception {
byte[] empty_hashed = new byte[] {
(byte) 0xe3, (byte) 0xb0, (byte) 0xc4, (byte) 0x42,
(byte) 0x98, (byte) 0xfc, (byte) 0x1c, (byte) 0x14,
(byte) 0x9a, (byte) 0xfb, (byte) 0xf4, (byte) 0xc8,
(byte) 0x99, (byte) 0x6f, (byte) 0xb9, (byte) 0x24,
(byte) 0x27, (byte) 0xae, (byte) 0x41, (byte) 0xe4,
(byte) 0x64, (byte) 0x9b, (byte) 0x93, (byte) 0x4c,
(byte) 0xa4, (byte) 0x95, (byte) 0x99, (byte) 0x1b,
(byte) 0x78, (byte) 0x52, (byte) 0xb8, (byte) 0x55,
};
final byte[] empty = new byte[] {};
assertTrue("Empty string should be equal to known test vector",
Arrays.equals(empty_hashed, PubkeyUtils.sha256(empty)));
}
}
| Java |
/*
* 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 android.test.AndroidTestCase;
/**
* @author Kenny Root
*
*/
public class TerminalBridgeTest extends AndroidTestCase {
public void testShiftLock() throws SecurityException, NoSuchFieldException,
IllegalArgumentException, IllegalAccessException {
// TerminalBridge bridge = new TerminalBridge();
// AbsTransport nullTransport = new NullTransport();
//
// // Make sure onKey will work when we call it
// Field disconnected = TerminalBridge.class
// .getDeclaredField("disconnected");
// Field keymode = TerminalBridge.class.getDeclaredField("keymode");
// Field transport = TerminalBridge.class.getDeclaredField("transport");
//
// disconnected.setAccessible(true);
// keymode.setAccessible(true);
// transport.setAccessible(true);
//
// disconnected.setBoolean(bridge, false);
// keymode.set(bridge, PreferenceConstants.KEYMODE_RIGHT);
// transport.set(bridge, nullTransport);
//
// // Begin tests
// assertTrue("Meta state is " + bridge.getMetaState()
// + " when it should be 0", bridge.getMetaState() == 0);
//
// KeyEvent shiftDown = new KeyEvent(KeyEvent.ACTION_DOWN,
// KeyEvent.KEYCODE_SHIFT_LEFT);
// bridge.onKey(null, shiftDown.getKeyCode(), shiftDown);
//
// assertTrue("Shift test: after shift press, meta state is "
// + bridge.getMetaState() + " when it should be "
// + TerminalBridge.META_SHIFT_ON,
// bridge.getMetaState() == TerminalBridge.META_SHIFT_ON);
//
// KeyEvent shiftUp = KeyEvent.changeAction(shiftDown, KeyEvent.ACTION_UP);
// bridge.onKey(null, shiftUp.getKeyCode(), shiftUp);
//
// assertTrue("Shift test: after shift release, meta state is "
// + bridge.getMetaState() + " when it should be "
// + TerminalBridge.META_SHIFT_ON,
// bridge.getMetaState() == TerminalBridge.META_SHIFT_ON);
//
// KeyEvent letterAdown = new KeyEvent(KeyEvent.ACTION_DOWN,
// KeyEvent.KEYCODE_A);
// KeyEvent letterAup = KeyEvent.changeAction(letterAdown,
// KeyEvent.ACTION_UP);
//
// bridge.onKey(null, letterAdown.getKeyCode(), letterAdown);
// bridge.onKey(null, letterAup.getKeyCode(), letterAup);
//
// assertTrue("Shift test: after letter press and release, meta state is "
// + bridge.getMetaState() + " when it should be 0", bridge
// .getMetaState() == 0);
//
// bridge.onKey(null, shiftDown.getKeyCode(), shiftDown);
// bridge.onKey(null, shiftUp.getKeyCode(), shiftUp);
// bridge.onKey(null, shiftDown.getKeyCode(), shiftDown);
// bridge.onKey(null, shiftUp.getKeyCode(), shiftUp);
//
// assertTrue("Shift lock test: after two shift presses, meta state is "
// + bridge.getMetaState() + " when it should be "
// + TerminalBridge.META_SHIFT_LOCK,
// bridge.getMetaState() == TerminalBridge.META_SHIFT_LOCK);
//
// bridge.onKey(null, letterAdown.getKeyCode(), letterAdown);
//
// assertTrue(
// "Shift lock test: after letter press, meta state is "
// + bridge.getMetaState() + " when it should be "
// + TerminalBridge.META_SHIFT_LOCK,
// bridge.getMetaState() == TerminalBridge.META_SHIFT_LOCK);
//
// bridge.onKey(null, letterAup.getKeyCode(), letterAup);
//
// assertTrue(
// "Shift lock test: after letter press and release, meta state is "
// + bridge.getMetaState() + " when it should be "
// + TerminalBridge.META_SHIFT_LOCK,
// bridge.getMetaState() == TerminalBridge.META_SHIFT_LOCK);
}
}
| Java |
/**
* Originally from http://www.cornetdesign.com/files/BeanTestCase.java.txt
*/
package org.connectbot.mock;
import junit.framework.TestCase;
import java.lang.reflect.Field;
public class BeanTestCase extends TestCase {
private static final String TEST_STRING_VAL1 = "Some Value";
private static final String TEST_STRING_VAL2 = "Some Other Value";
public static void assertMeetsEqualsContract(Class<?> classUnderTest,
String[] fieldNames) {
Object o1;
Object o2;
try {
// Get Instances
o1 = classUnderTest.newInstance();
o2 = classUnderTest.newInstance();
assertTrue(
"Instances with default constructor not equal (o1.equals(o2))",
o1.equals(o2));
assertTrue(
"Instances with default constructor not equal (o2.equals(o1))",
o2.equals(o1));
Field[] fields = getFieldsByNameOrAll(classUnderTest, fieldNames);
for (int i = 0; i < fields.length; i++) {
// Reset the instances
o1 = classUnderTest.newInstance();
o2 = classUnderTest.newInstance();
Field field = fields[i];
field.setAccessible(true);
if (field.getType() == String.class) {
field.set(o1, TEST_STRING_VAL1);
} else if (field.getType() == boolean.class) {
field.setBoolean(o1, true);
} else if (field.getType() == short.class) {
field.setShort(o1, (short) 1);
} else if (field.getType() == long.class) {
field.setLong(o1, (long) 1);
} else if (field.getType() == float.class) {
field.setFloat(o1, (float) 1);
} else if (field.getType() == int.class) {
field.setInt(o1, 1);
} else if (field.getType() == byte.class) {
field.setByte(o1, (byte) 1);
} else if (field.getType() == char.class) {
field.setChar(o1, (char) 1);
} else if (field.getType() == double.class) {
field.setDouble(o1, (double) 1);
} else if (field.getType().isEnum()) {
field.set(o1, field.getType().getEnumConstants()[0]);
} else if (Object.class.isAssignableFrom(field.getType())) {
field.set(o1, field.getType().newInstance());
} else {
fail("Don't know how to set a " + field.getType().getName());
}
assertFalse("Instances with o1 having " + field.getName()
+ " set and o2 having it not set are equal", o1
.equals(o2));
field.set(o2, field.get(o1));
assertTrue(
"After setting o2 with the value of the object in o1, the two objects in the field are not equal",
field.get(o1).equals(field.get(o2)));
assertTrue(
"Instances with o1 having "
+ field.getName()
+ " set and o2 having it set to the same object of type "
+ field.get(o2).getClass().getName()
+ " are not equal", o1.equals(o2));
if (field.getType() == String.class) {
field.set(o2, TEST_STRING_VAL2);
} else if (field.getType() == boolean.class) {
field.setBoolean(o2, false);
} else if (field.getType() == short.class) {
field.setShort(o2, (short) 0);
} else if (field.getType() == long.class) {
field.setLong(o2, (long) 0);
} else if (field.getType() == float.class) {
field.setFloat(o2, (float) 0);
} else if (field.getType() == int.class) {
field.setInt(o2, 0);
} else if (field.getType() == byte.class) {
field.setByte(o2, (byte) 0);
} else if (field.getType() == char.class) {
field.setChar(o2, (char) 0);
} else if (field.getType() == double.class) {
field.setDouble(o2, (double) 1);
} else if (field.getType().isEnum()) {
field.set(o2, field.getType().getEnumConstants()[1]);
} else if (Object.class.isAssignableFrom(field.getType())) {
field.set(o2, field.getType().newInstance());
} else {
fail("Don't know how to set a " + field.getType().getName());
}
if (field.get(o1).equals(field.get(o2))) {
// Even though we have different instances, they are equal.
// Let's walk one of them
// to see if we can find a field to set
Field[] paramFields = field.get(o1).getClass()
.getDeclaredFields();
for (int j = 0; j < paramFields.length; j++) {
paramFields[j].setAccessible(true);
if (paramFields[j].getType() == String.class) {
paramFields[j].set(field.get(o1), TEST_STRING_VAL1);
}
}
}
assertFalse(
"After setting o2 with a different object than what is in o1, the two objects in the field are equal. "
+ "This is after an attempt to walk the fields to make them different",
field.get(o1).equals(field.get(o2)));
assertFalse(
"Instances with o1 having "
+ field.getName()
+ " set and o2 having it set to a different object are equal",
o1.equals(o2));
}
} catch (InstantiationException e) {
e.printStackTrace();
throw new AssertionError(
"Unable to construct an instance of the class under test");
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new AssertionError(
"Unable to construct an instance of the class under test");
} catch (SecurityException e) {
e.printStackTrace();
throw new AssertionError(
"Unable to read the field from the class under test");
} catch (NoSuchFieldException e) {
e.printStackTrace();
throw new AssertionError(
"Unable to find field in the class under test");
}
}
/**
* @param classUnderTest
* @param fieldNames
* @return
* @throws NoSuchFieldException
*/
private static Field[] getFieldsByNameOrAll(Class<?> classUnderTest,
String[] fieldNames) throws NoSuchFieldException {
Field fields[];
if (fieldNames == null) {
fields = classUnderTest.getDeclaredFields();
} else {
fields = new Field[fieldNames.length];
for (int i = 0; i < fieldNames.length; i++)
fields[i] = classUnderTest.getDeclaredField(fieldNames[i]);
}
return fields;
}
public static void assertMeetsHashCodeContract(Class<?> classUnderTest,
String[] fieldNames) {
try {
Field[] fields = getFieldsByNameOrAll(classUnderTest, fieldNames);
for (int i = 0; i < fields.length; i++) {
Object o1 = classUnderTest.newInstance();
int initialHashCode = o1.hashCode();
Field field = fields[i];
field.setAccessible(true);
if (field.getType() == String.class) {
field.set(o1, TEST_STRING_VAL1);
} else if (field.getType() == boolean.class) {
field.setBoolean(o1, true);
} else if (field.getType() == short.class) {
field.setShort(o1, (short) 1);
} else if (field.getType() == long.class) {
field.setLong(o1, (long) 1);
} else if (field.getType() == float.class) {
field.setFloat(o1, (float) 1);
} else if (field.getType() == int.class) {
field.setInt(o1, 1);
} else if (field.getType() == byte.class) {
field.setByte(o1, (byte) 1);
} else if (field.getType() == char.class) {
field.setChar(o1, (char) 1);
} else if (field.getType() == double.class) {
field.setDouble(o1, (double) 1);
} else if (field.getType().isEnum()) {
field.set(o1, field.getType().getEnumConstants()[0]);
} else if (Object.class.isAssignableFrom(field.getType())) {
field.set(o1, field.getType().newInstance());
} else {
fail("Don't know how to set a " + field.getType().getName());
}
int updatedHashCode = o1.hashCode();
assertFalse(
"The field "
+ field.getName()
+ " was not taken into account for the hashCode contract ",
initialHashCode == updatedHashCode);
}
} catch (InstantiationException e) {
e.printStackTrace();
throw new AssertionError(
"Unable to construct an instance of the class under test");
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new AssertionError(
"Unable to construct an instance of the class under test");
} catch (NoSuchFieldException e) {
e.printStackTrace();
throw new AssertionError(
"Unable to find field in the class under test");
}
}
}
| Java |
/*
* 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.mock;
import java.io.IOException;
import java.io.OutputStream;
/**
* @author Kenny Root
*
*/
public class NullOutputStream extends OutputStream {
@Override
public void write(int arg0) throws IOException {
// do nothing
}
}
| Java |
/*
* 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.mock;
import java.io.IOException;
import java.util.Map;
import org.connectbot.bean.HostBean;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import org.connectbot.transport.AbsTransport;
import android.net.Uri;
/**
* @author kenny
*
*/
public class NullTransport extends AbsTransport {
/**
*
*/
public NullTransport() {
// TODO Auto-generated constructor stub
}
/**
* @param host
* @param bridge
* @param manager
*/
public NullTransport(HostBean host, TerminalBridge bridge,
TerminalManager manager) {
super(host, bridge, manager);
// TODO Auto-generated constructor stub
}
@Override
public void close() {
// TODO Auto-generated method stub
}
@Override
public void connect() {
// TODO Auto-generated method stub
}
@Override
public HostBean createHost(Uri uri) {
// TODO Auto-generated method stub
return null;
}
@Override
public void flush() throws IOException {
// TODO Auto-generated method stub
}
@Override
public String getDefaultNickname(String username, String hostname, int port) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getDefaultPort() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void getSelectionArgs(Uri uri, Map<String, String> selection) {
// TODO Auto-generated method stub
}
@Override
public boolean isConnected() {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean isSessionOpen() {
// TODO Auto-generated method stub
return false;
}
@Override
public int read(byte[] buffer, int offset, int length) throws IOException {
// TODO Auto-generated method stub
return 0;
}
@Override
public void setDimensions(int columns, int rows, int width, int height) {
// TODO Auto-generated method stub
}
@Override
public void write(byte[] buffer) throws IOException {
// TODO Auto-generated method stub
}
@Override
public void write(int c) throws IOException {
// TODO Auto-generated method stub
}
@Override
public boolean usesNetwork() {
// TODO Auto-generated method stub
return false;
}
}
| Java |
/*
* This file is part of "JTA - Telnet/SSH for the JAVA(tm) platform".
*
* (c) Matthias L. Jugel, Marcus Meißner 1996-2005. All Rights Reserved.
*
* Please visit http://javatelnet.org/ for updates and contact.
*
* --LICENSE NOTICE--
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* --LICENSE NOTICE--
*
*/
package de.mud.terminal;
/**
* Generic display
*/
public interface VDUDisplay {
public void redraw();
public void updateScrollBar();
public void setVDUBuffer(VDUBuffer buffer);
public VDUBuffer getVDUBuffer();
public void setColor(int index, int red, int green, int blue);
public void resetColors();
}
| Java |
/*
* This file is part of "JTA - Telnet/SSH for the JAVA(tm) platform".
*
* (c) Matthias L. Jugel, Marcus Mei�ner 1996-2005. All Rights Reserved.
*
* Please visit http://javatelnet.org/ for updates and contact.
*
* --LICENSE NOTICE--
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* --LICENSE NOTICE--
*
*/
package de.mud.terminal;
import java.util.Arrays;
/**
* Implementation of a Video Display Unit (VDU) buffer. This class contains
* all methods to manipulate the buffer that stores characters and their
* attributes as well as the regions displayed.
*
* @author Matthias L. Jugel, Marcus Meißner
* @version $Id: VDUBuffer.java 503 2005-10-24 07:34:13Z marcus $
*/
public class VDUBuffer {
/** The current version id tag */
public final static String ID = "$Id: VDUBuffer.java 503 2005-10-24 07:34:13Z marcus $";
/** Enable debug messages. */
public final static int debug = 0;
public int height, width; /* rows and columns */
public boolean[] update; /* contains the lines that need update */
public char[][] charArray; /* contains the characters */
public int[][] charAttributes; /* contains character attrs */
public int bufSize;
public int maxBufSize; /* buffer sizes */
public int screenBase; /* the actual screen start */
public int windowBase; /* where the start displaying */
public int scrollMarker; /* marks the last line inserted */
private int topMargin; /* top scroll margin */
private int bottomMargin; /* bottom scroll margin */
// cursor variables
protected boolean showcursor = true;
protected int cursorX, cursorY;
/** Scroll up when inserting a line. */
public final static boolean SCROLL_UP = false;
/** Scroll down when inserting a line. */
public final static boolean SCROLL_DOWN = true;
/* Attributes bit-field usage:
*
* 8421 8421 8421 8421 8421 8421 8421 8421
* |||| |||| |||| |||| |||| |||| |||| |||`- Bold
* |||| |||| |||| |||| |||| |||| |||| ||`-- Underline
* |||| |||| |||| |||| |||| |||| |||| |`--- Invert
* |||| |||| |||| |||| |||| |||| |||| `---- Low
* |||| |||| |||| |||| |||| |||| |||`------ Invisible
* |||| |||| |||| |||| ||`+-++++-+++------- Foreground Color
* |||| |||| |`++-++++-++------------------ Background Color
* |||| |||| `----------------------------- Fullwidth character
* `+++-++++------------------------------- Reserved for future use
*/
/** Make character normal. */
public final static int NORMAL = 0x00;
/** Make character bold. */
public final static int BOLD = 0x01;
/** Underline character. */
public final static int UNDERLINE = 0x02;
/** Invert character. */
public final static int INVERT = 0x04;
/** Lower intensity character. */
public final static int LOW = 0x08;
/** Invisible character. */
public final static int INVISIBLE = 0x10;
/** Unicode full-width character (CJK, et al.) */
public final static int FULLWIDTH = 0x8000000;
/** how much to left shift the foreground color */
public final static int COLOR_FG_SHIFT = 5;
/** how much to left shift the background color */
public final static int COLOR_BG_SHIFT = 14;
/** color mask */
public final static int COLOR = 0x7fffe0; /* 0000 0000 0111 1111 1111 1111 1110 0000 */
/** foreground color mask */
public final static int COLOR_FG = 0x3fe0; /* 0000 0000 0000 0000 0011 1111 1110 0000 */
/** background color mask */
public final static int COLOR_BG = 0x7fc000; /* 0000 0000 0111 1111 1100 0000 0000 0000 */
/**
* Create a new video display buffer with the passed width and height in
* characters.
* @param width the length of the character lines
* @param height the amount of lines on the screen
*/
public VDUBuffer(int width, int height) {
// set the display screen size
setScreenSize(width, height, false);
}
/**
* Create a standard video display buffer with 80 columns and 24 lines.
*/
public VDUBuffer() {
this(80, 24);
}
/**
* Put a character on the screen with normal font and outline.
* The character previously on that position will be overwritten.
* You need to call redraw() to update the screen.
* @param c x-coordinate (column)
* @param l y-coordinate (line)
* @param ch the character to show on the screen
* @see #insertChar
* @see #deleteChar
* @see #redraw
*/
public void putChar(int c, int l, char ch) {
putChar(c, l, ch, NORMAL);
}
/**
* Put a character on the screen with specific font and outline.
* The character previously on that position will be overwritten.
* You need to call redraw() to update the screen.
* @param c x-coordinate (column)
* @param l y-coordinate (line)
* @param ch the character to show on the screen
* @param attributes the character attributes
* @see #BOLD
* @see #UNDERLINE
* @see #INVERT
* @see #INVISIBLE
* @see #NORMAL
* @see #LOW
* @see #insertChar
* @see #deleteChar
* @see #redraw
*/
public void putChar(int c, int l, char ch, int attributes) {
charArray[screenBase + l][c] = ch;
charAttributes[screenBase + l][c] = attributes;
if (l < height)
update[l + 1] = true;
}
/**
* Get the character at the specified position.
* @param c x-coordinate (column)
* @param l y-coordinate (line)
* @see #putChar
*/
public char getChar(int c, int l) {
return charArray[screenBase + l][c];
}
/**
* Get the attributes for the specified position.
* @param c x-coordinate (column)
* @param l y-coordinate (line)
* @see #putChar
*/
public int getAttributes(int c, int l) {
return charAttributes[screenBase + l][c];
}
/**
* Insert a character at a specific position on the screen.
* All character right to from this position will be moved one to the right.
* You need to call redraw() to update the screen.
* @param c x-coordinate (column)
* @param l y-coordinate (line)
* @param ch the character to insert
* @param attributes the character attributes
* @see #BOLD
* @see #UNDERLINE
* @see #INVERT
* @see #INVISIBLE
* @see #NORMAL
* @see #LOW
* @see #putChar
* @see #deleteChar
* @see #redraw
*/
public void insertChar(int c, int l, char ch, int attributes) {
System.arraycopy(charArray[screenBase + l], c,
charArray[screenBase + l], c + 1, width - c - 1);
System.arraycopy(charAttributes[screenBase + l], c,
charAttributes[screenBase + l], c + 1, width - c - 1);
putChar(c, l, ch, attributes);
}
/**
* Delete a character at a given position on the screen.
* All characters right to the position will be moved one to the left.
* You need to call redraw() to update the screen.
* @param c x-coordinate (column)
* @param l y-coordinate (line)
* @see #putChar
* @see #insertChar
* @see #redraw
*/
public void deleteChar(int c, int l) {
if (c < width - 1) {
System.arraycopy(charArray[screenBase + l], c + 1,
charArray[screenBase + l], c, width - c - 1);
System.arraycopy(charAttributes[screenBase + l], c + 1,
charAttributes[screenBase + l], c, width - c - 1);
}
putChar(width - 1, l, (char) 0);
}
/**
* Put a String at a specific position. Any characters previously on that
* position will be overwritten. You need to call redraw() for screen update.
* @param c x-coordinate (column)
* @param l y-coordinate (line)
* @param s the string to be shown on the screen
* @see #BOLD
* @see #UNDERLINE
* @see #INVERT
* @see #INVISIBLE
* @see #NORMAL
* @see #LOW
* @see #putChar
* @see #insertLine
* @see #deleteLine
* @see #redraw
*/
public void putString(int c, int l, String s) {
putString(c, l, s, NORMAL);
}
/**
* Put a String at a specific position giving all characters the same
* attributes. Any characters previously on that position will be
* overwritten. You need to call redraw() to update the screen.
* @param c x-coordinate (column)
* @param l y-coordinate (line)
* @param s the string to be shown on the screen
* @param attributes character attributes
* @see #BOLD
* @see #UNDERLINE
* @see #INVERT
* @see #INVISIBLE
* @see #NORMAL
* @see #LOW
* @see #putChar
* @see #insertLine
* @see #deleteLine
* @see #redraw
*/
public void putString(int c, int l, String s, int attributes) {
for (int i = 0; i < s.length() && c + i < width; i++)
putChar(c + i, l, s.charAt(i), attributes);
}
/**
* Insert a blank line at a specific position.
* The current line and all previous lines are scrolled one line up. The
* top line is lost. You need to call redraw() to update the screen.
* @param l the y-coordinate to insert the line
* @see #deleteLine
* @see #redraw
*/
public void insertLine(int l) {
insertLine(l, 1, SCROLL_UP);
}
/**
* Insert blank lines at a specific position.
* You need to call redraw() to update the screen
* @param l the y-coordinate to insert the line
* @param n amount of lines to be inserted
* @see #deleteLine
* @see #redraw
*/
public void insertLine(int l, int n) {
insertLine(l, n, SCROLL_UP);
}
/**
* Insert a blank line at a specific position. Scroll text according to
* the argument.
* You need to call redraw() to update the screen
* @param l the y-coordinate to insert the line
* @param scrollDown scroll down
* @see #deleteLine
* @see #SCROLL_UP
* @see #SCROLL_DOWN
* @see #redraw
*/
public void insertLine(int l, boolean scrollDown) {
insertLine(l, 1, scrollDown);
}
/**
* Insert blank lines at a specific position.
* The current line and all previous lines are scrolled one line up. The
* top line is lost. You need to call redraw() to update the screen.
* @param l the y-coordinate to insert the line
* @param n number of lines to be inserted
* @param scrollDown scroll down
* @see #deleteLine
* @see #SCROLL_UP
* @see #SCROLL_DOWN
* @see #redraw
*/
public synchronized void insertLine(int l, int n, boolean scrollDown) {
char cbuf[][] = null;
int abuf[][] = null;
int offset = 0;
int oldBase = screenBase;
int newScreenBase = screenBase;
int newWindowBase = windowBase;
int newBufSize = bufSize;
if (l > bottomMargin) /* We do not scroll below bottom margin (below the scrolling region). */
return;
int top = (l < topMargin ?
0 : (l > bottomMargin ?
(bottomMargin + 1 < height ?
bottomMargin + 1 : height - 1) : topMargin));
int bottom = (l > bottomMargin ?
height - 1 : (l < topMargin ?
(topMargin > 0 ?
topMargin - 1 : 0) : bottomMargin));
// System.out.println("l is "+l+", top is "+top+", bottom is "+bottom+", bottomargin is "+bottomMargin+", topMargin is "+topMargin);
if (scrollDown) {
if (n > (bottom - top)) n = (bottom - top);
int size = bottom - l - (n - 1);
if(size < 0) size = 0;
cbuf = new char[size][];
abuf = new int[size][];
System.arraycopy(charArray, oldBase + l, cbuf, 0, bottom - l - (n - 1));
System.arraycopy(charAttributes, oldBase + l,
abuf, 0, bottom - l - (n - 1));
System.arraycopy(cbuf, 0, charArray, oldBase + l + n,
bottom - l - (n - 1));
System.arraycopy(abuf, 0, charAttributes, oldBase + l + n,
bottom - l - (n - 1));
cbuf = charArray;
abuf = charAttributes;
} else {
try {
if (n > (bottom - top) + 1) n = (bottom - top) + 1;
if (bufSize < maxBufSize) {
if (bufSize + n > maxBufSize) {
offset = n - (maxBufSize - bufSize);
scrollMarker += offset;
newBufSize = maxBufSize;
newScreenBase = maxBufSize - height - 1;
newWindowBase = screenBase;
} else {
scrollMarker += n;
newScreenBase += n;
newWindowBase += n;
newBufSize += n;
}
cbuf = new char[newBufSize][];
abuf = new int[newBufSize][];
} else {
offset = n;
cbuf = charArray;
abuf = charAttributes;
}
// copy anything from the top of the buffer (+offset) to the new top
// up to the screenBase.
if (oldBase > 0) {
System.arraycopy(charArray, offset,
cbuf, 0,
oldBase - offset);
System.arraycopy(charAttributes, offset,
abuf, 0,
oldBase - offset);
}
// copy anything from the top of the screen (screenBase) up to the
// topMargin to the new screen
if (top > 0) {
System.arraycopy(charArray, oldBase,
cbuf, newScreenBase,
top);
System.arraycopy(charAttributes, oldBase,
abuf, newScreenBase,
top);
}
// copy anything from the topMargin up to the amount of lines inserted
// to the gap left over between scrollback buffer and screenBase
if (oldBase >= 0) {
System.arraycopy(charArray, oldBase + top,
cbuf, oldBase - offset,
n);
System.arraycopy(charAttributes, oldBase + top,
abuf, oldBase - offset,
n);
}
// copy anything from topMargin + n up to the line linserted to the
// topMargin
System.arraycopy(charArray, oldBase + top + n,
cbuf, newScreenBase + top,
l - top - (n - 1));
System.arraycopy(charAttributes, oldBase + top + n,
abuf, newScreenBase + top,
l - top - (n - 1));
//
// copy the all lines next to the inserted to the new buffer
if (l < height - 1) {
System.arraycopy(charArray, oldBase + l + 1,
cbuf, newScreenBase + l + 1,
(height - 1) - l);
System.arraycopy(charAttributes, oldBase + l + 1,
abuf, newScreenBase + l + 1,
(height - 1) - l);
}
} catch (ArrayIndexOutOfBoundsException e) {
// this should not happen anymore, but I will leave the code
// here in case something happens anyway. That code above is
// so complex I always have a hard time understanding what
// I did, even though there are comments
System.err.println("*** Error while scrolling up:");
System.err.println("--- BEGIN STACK TRACE ---");
e.printStackTrace();
System.err.println("--- END STACK TRACE ---");
System.err.println("bufSize=" + bufSize + ", maxBufSize=" + maxBufSize);
System.err.println("top=" + top + ", bottom=" + bottom);
System.err.println("n=" + n + ", l=" + l);
System.err.println("screenBase=" + screenBase + ", windowBase=" + windowBase);
System.err.println("newScreenBase=" + newScreenBase + ", newWindowBase=" + newWindowBase);
System.err.println("oldBase=" + oldBase);
System.err.println("size.width=" + width + ", size.height=" + height);
System.err.println("abuf.length=" + abuf.length + ", cbuf.length=" + cbuf.length);
System.err.println("*** done dumping debug information");
}
}
// this is a little helper to mark the scrolling
scrollMarker -= n;
for (int i = 0; i < n; i++) {
cbuf[(newScreenBase + l) + (scrollDown ? i : -i)] = new char[width];
Arrays.fill(cbuf[(newScreenBase + l) + (scrollDown ? i : -i)], ' ');
abuf[(newScreenBase + l) + (scrollDown ? i : -i)] = new int[width];
}
charArray = cbuf;
charAttributes = abuf;
screenBase = newScreenBase;
windowBase = newWindowBase;
bufSize = newBufSize;
if (scrollDown)
markLine(l, bottom - l + 1);
else
markLine(top, l - top + 1);
display.updateScrollBar();
}
/**
* Delete a line at a specific position. Subsequent lines will be scrolled
* up to fill the space and a blank line is inserted at the end of the
* screen.
* @param l the y-coordinate to insert the line
* @see #deleteLine
*/
public void deleteLine(int l) {
int bottom = (l > bottomMargin ? height - 1:
(l < topMargin?topMargin:bottomMargin + 1));
int numRows = bottom - l - 1;
char[] discardedChars = charArray[screenBase + l];
int[] discardedAttributes = charAttributes[screenBase + l];
if (numRows > 0) {
System.arraycopy(charArray, screenBase + l + 1,
charArray, screenBase + l, numRows);
System.arraycopy(charAttributes, screenBase + l + 1,
charAttributes, screenBase + l, numRows);
}
int newBottomRow = screenBase + bottom - 1;
charArray[newBottomRow] = discardedChars;
charAttributes[newBottomRow] = discardedAttributes;
Arrays.fill(charArray[newBottomRow], ' ');
Arrays.fill(charAttributes[newBottomRow], 0);
markLine(l, bottom - l);
}
/**
* Delete a rectangular portion of the screen.
* You need to call redraw() to update the screen.
* @param c x-coordinate (column)
* @param l y-coordinate (row)
* @param w with of the area in characters
* @param h height of the area in characters
* @param curAttr attribute to fill
* @see #deleteChar
* @see #deleteLine
* @see #redraw
*/
public void deleteArea(int c, int l, int w, int h, int curAttr) {
int endColumn = c + w;
int targetRow = screenBase + l;
for (int i = 0; i < h && l + i < height; i++) {
Arrays.fill(charAttributes[targetRow], c, endColumn, curAttr);
Arrays.fill(charArray[targetRow], c, endColumn, ' ');
targetRow++;
}
markLine(l, h);
}
/**
* Delete a rectangular portion of the screen.
* You need to call redraw() to update the screen.
* @param c x-coordinate (column)
* @param l y-coordinate (row)
* @param w with of the area in characters
* @param h height of the area in characters
* @see #deleteChar
* @see #deleteLine
* @see #redraw
*/
public void deleteArea(int c, int l, int w, int h) {
deleteArea(c, l, w, h, 0);
}
/**
* Sets whether the cursor is visible or not.
* @param doshow
*/
public void showCursor(boolean doshow) {
showcursor = doshow;
}
/**
* Check whether the cursor is currently visible.
* @return visibility
*/
public boolean isCursorVisible() {
return showcursor;
}
/**
* Puts the cursor at the specified position.
* @param c column
* @param l line
*/
public void setCursorPosition(int c, int l) {
cursorX = c;
cursorY = l;
}
/**
* Get the current column of the cursor position.
*/
public int getCursorColumn() {
return cursorX;
}
/**
* Get the current line of the cursor position.
*/
public int getCursorRow() {
return cursorY;
}
/**
* Set the current window base. This allows to view the scrollback buffer.
* @param line the line where the screen window starts
* @see #setBufferSize
* @see #getBufferSize
*/
public void setWindowBase(int line) {
if (line > screenBase)
line = screenBase;
else if (line < 0) line = 0;
windowBase = line;
update[0] = true;
redraw();
}
/**
* Get the current window base.
* @see #setWindowBase
*/
public int getWindowBase() {
return windowBase;
}
/**
* Set the scroll margins simultaneously. If they're out of bounds, trim them.
* @param l1 line that is the top
* @param l2 line that is the bottom
*/
public void setMargins(int l1, int l2) {
if (l1 > l2)
return;
if (l1 < 0)
l1 = 0;
if (l2 >= height)
l2 = height - 1;
topMargin = l1;
bottomMargin = l2;
}
/**
* Set the top scroll margin for the screen. If the current bottom margin
* is smaller it will become the top margin and the line will become the
* bottom margin.
* @param l line that is the margin
*/
public void setTopMargin(int l) {
if (l > bottomMargin) {
topMargin = bottomMargin;
bottomMargin = l;
} else
topMargin = l;
if (topMargin < 0) topMargin = 0;
if (bottomMargin >= height) bottomMargin = height - 1;
}
/**
* Get the top scroll margin.
*/
public int getTopMargin() {
return topMargin;
}
/**
* Set the bottom scroll margin for the screen. If the current top margin
* is bigger it will become the bottom margin and the line will become the
* top margin.
* @param l line that is the margin
*/
public void setBottomMargin(int l) {
if (l < topMargin) {
bottomMargin = topMargin;
topMargin = l;
} else
bottomMargin = l;
if (topMargin < 0) topMargin = 0;
if (bottomMargin >= height) bottomMargin = height - 1;
}
/**
* Get the bottom scroll margin.
*/
public int getBottomMargin() {
return bottomMargin;
}
/**
* Set scrollback buffer size.
* @param amount new size of the buffer
*/
public void setBufferSize(int amount) {
if (amount < height) amount = height;
if (amount < maxBufSize) {
char cbuf[][] = new char[amount][width];
int abuf[][] = new int[amount][width];
int copyStart = bufSize - amount < 0 ? 0 : bufSize - amount;
int copyCount = bufSize - amount < 0 ? bufSize : amount;
if (charArray != null)
System.arraycopy(charArray, copyStart, cbuf, 0, copyCount);
if (charAttributes != null)
System.arraycopy(charAttributes, copyStart, abuf, 0, copyCount);
charArray = cbuf;
charAttributes = abuf;
bufSize = copyCount;
screenBase = bufSize - height;
windowBase = screenBase;
}
maxBufSize = amount;
update[0] = true;
redraw();
}
/**
* Retrieve current scrollback buffer size.
* @see #setBufferSize
*/
public int getBufferSize() {
return bufSize;
}
/**
* Retrieve maximum buffer Size.
* @see #getBufferSize
*/
public int getMaxBufferSize() {
return maxBufSize;
}
/**
* Change the size of the screen. This will include adjustment of the
* scrollback buffer.
* @param w of the screen
* @param h of the screen
*/
public void setScreenSize(int w, int h, boolean broadcast) {
char cbuf[][];
int abuf[][];
int maxSize = bufSize;
if (w < 1 || h < 1) return;
if (debug > 0)
System.err.println("VDU: screen size [" + w + "," + h + "]");
if (h > maxBufSize)
maxBufSize = h;
if (h > bufSize) {
bufSize = h;
screenBase = 0;
windowBase = 0;
}
if (windowBase + h >= bufSize)
windowBase = bufSize - h;
if (screenBase + h >= bufSize)
screenBase = bufSize - h;
cbuf = new char[bufSize][w];
abuf = new int[bufSize][w];
for (int i = 0; i < bufSize; i++) {
Arrays.fill(cbuf[i], ' ');
}
if (bufSize < maxSize)
maxSize = bufSize;
int rowLength;
if (charArray != null && charAttributes != null) {
for (int i = 0; i < maxSize && charArray[i] != null; i++) {
rowLength = charArray[i].length;
System.arraycopy(charArray[i], 0, cbuf[i], 0,
w < rowLength ? w : rowLength);
System.arraycopy(charAttributes[i], 0, abuf[i], 0,
w < rowLength ? w : rowLength);
}
}
int C = getCursorColumn();
if (C < 0)
C = 0;
else if (C >= width)
C = width - 1;
int R = getCursorRow();
if (R < 0)
R = 0;
else if (R >= height)
R = height - 1;
setCursorPosition(C, R);
charArray = cbuf;
charAttributes = abuf;
width = w;
height = h;
topMargin = 0;
bottomMargin = h - 1;
update = new boolean[h + 1];
update[0] = true;
/* FIXME: ???
if(resizeStrategy == RESIZE_FONT)
setBounds(getBounds());
*/
}
/**
* Get amount of rows on the screen.
*/
public int getRows() {
return height;
}
/**
* Get amount of columns on the screen.
*/
public int getColumns() {
return width;
}
/**
* Mark lines to be updated with redraw().
* @param l starting line
* @param n amount of lines to be updated
* @see #redraw
*/
public void markLine(int l, int n) {
for (int i = 0; (i < n) && (l + i < height); i++)
update[l + i + 1] = true;
}
// private static int checkBounds(int value, int lower, int upper) {
// if (value < lower)
// return lower;
// else if (value > upper)
// return upper;
// else
// return value;
// }
/** a generic display that should redraw on demand */
protected VDUDisplay display;
public void setDisplay(VDUDisplay display) {
this.display = display;
}
/**
* Trigger a redraw on the display.
*/
protected void redraw() {
if (display != null)
display.redraw();
}
}
| Java |
/*
* This file is part of "JTA - Telnet/SSH for the JAVA(tm) platform".
*
* (c) Matthias L. Jugel, Marcus Meiner 1996-2005. All Rights Reserved.
*
* Please visit http://javatelnet.org/ for updates and contact.
*
* --LICENSE NOTICE--
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* --LICENSE NOTICE--
*
*/
package de.mud.terminal;
import android.text.AndroidCharacter;
import java.util.Properties;
/**
* Implementation of a VT terminal emulation plus ANSI compatible.
* <P>
* <B>Maintainer:</B> Marcus Meißner
*
* @version $Id: vt320.java 507 2005-10-25 10:14:52Z marcus $
* @author Matthias L. Jugel, Marcus Meißner
*/
public abstract class vt320 extends VDUBuffer implements VDUInput {
/** The current version id tag.<P>
* $Id: vt320.java 507 2005-10-25 10:14:52Z marcus $
*
*/
public final static String ID = "$Id: vt320.java 507 2005-10-25 10:14:52Z marcus $";
/** the debug level */
private final static int debug = 0;
private StringBuilder debugStr;
public abstract void debug(String notice);
/**
* Write an answer back to the remote host. This is needed to be able to
* send terminal answers requests like status and type information.
* @param b the array of bytes to be sent
*/
public abstract void write(byte[] b);
/**
* Write an answer back to the remote host. This is needed to be able to
* send terminal answers requests like status and type information.
* @param b the array of bytes to be sent
*/
public abstract void write(int b);
/**
* Play the beep sound ...
*/
public void beep() { /* do nothing by default */
}
/**
* Convenience function for putString(char[], int, int)
*/
public void putString(String s) {
int len = s.length();
char[] tmp = new char[len];
s.getChars(0, len, tmp, 0);
putString(tmp, null, 0, len);
}
/**
* Put string at current cursor position. Moves cursor
* according to the String. Does NOT wrap.
* @param s character array
* @param start place to start in array
* @param len number of characters to process
*/
public void putString(char[] s, byte[] fullwidths, int start, int len) {
if (len > 0) {
//markLine(R, 1);
int lastChar = -1;
char c;
boolean isWide = false;
for (int i = 0; i < len; i++) {
c = s[start + i];
// Shortcut for my favorite ASCII
if (c <= 0x7F) {
if (lastChar != -1)
putChar((char) lastChar, isWide, false);
lastChar = c;
isWide = false;
} else if (!Character.isLowSurrogate(c) && !Character.isHighSurrogate(c)) {
if (Character.getType(c) == Character.NON_SPACING_MARK) {
if (lastChar != -1) {
char nc = Precomposer.precompose((char) lastChar, c);
putChar(nc, isWide, false);
lastChar = -1;
}
} else {
if (lastChar != -1)
putChar((char) lastChar, isWide, false);
lastChar = c;
if (fullwidths != null) {
final byte width = fullwidths[i];
isWide = (width == AndroidCharacter.EAST_ASIAN_WIDTH_WIDE)
|| (width == AndroidCharacter.EAST_ASIAN_WIDTH_FULL_WIDTH);
}
}
}
}
if (lastChar != -1)
putChar((char) lastChar, isWide, false);
setCursorPosition(C, R);
redraw();
}
}
protected void sendTelnetCommand(byte cmd) {
}
/**
* Sent the changed window size from the terminal to all listeners.
*/
protected void setWindowSize(int c, int r) {
/* To be overridden by Terminal.java */
}
@Override
public void setScreenSize(int c, int r, boolean broadcast) {
int oldrows = height;
if (debug>2) {
if (debugStr == null)
debugStr = new StringBuilder();
debugStr.append("setscreensize (")
.append(c)
.append(',')
.append(r)
.append(',')
.append(broadcast)
.append(')');
debug(debugStr.toString());
debugStr.setLength(0);
}
super.setScreenSize(c,r,false);
boolean cursorChanged = false;
// Don't let the cursor go off the screen.
if (C >= c) {
C = c - 1;
cursorChanged = true;
}
if (R >= r) {
R = r - 1;
cursorChanged = true;
}
if (cursorChanged) {
setCursorPosition(C, R);
redraw();
}
if (broadcast) {
setWindowSize(c, r); /* broadcast up */
}
}
/**
* Create a new vt320 terminal and intialize it with useful settings.
*/
public vt320(int width, int height) {
super(width, height);
debugStr = new StringBuilder();
setVMS(false);
setIBMCharset(false);
setTerminalID("vt320");
setBufferSize(100);
//setBorder(2, false);
gx = new char[4];
reset();
/* top row of numpad */
PF1 = "\u001bOP";
PF2 = "\u001bOQ";
PF3 = "\u001bOR";
PF4 = "\u001bOS";
/* the 3x2 keyblock on PC keyboards */
Insert = new String[4];
Remove = new String[4];
KeyHome = new String[4];
KeyEnd = new String[4];
NextScn = new String[4];
PrevScn = new String[4];
Escape = new String[4];
BackSpace = new String[4];
TabKey = new String[4];
Insert[0] = Insert[1] = Insert[2] = Insert[3] = "\u001b[2~";
Remove[0] = Remove[1] = Remove[2] = Remove[3] = "\u001b[3~";
PrevScn[0] = PrevScn[1] = PrevScn[2] = PrevScn[3] = "\u001b[5~";
NextScn[0] = NextScn[1] = NextScn[2] = NextScn[3] = "\u001b[6~";
KeyHome[0] = KeyHome[1] = KeyHome[2] = KeyHome[3] = "\u001b[H";
KeyEnd[0] = KeyEnd[1] = KeyEnd[2] = KeyEnd[3] = "\u001b[F";
Escape[0] = Escape[1] = Escape[2] = Escape[3] = "\u001b";
if (vms) {
BackSpace[1] = "" + (char) 10; // VMS shift deletes word back
BackSpace[2] = "\u0018"; // VMS control deletes line back
BackSpace[0] = BackSpace[3] = "\u007f"; // VMS other is delete
} else {
//BackSpace[0] = BackSpace[1] = BackSpace[2] = BackSpace[3] = "\b";
// ConnectBot modifications.
BackSpace[0] = "\b";
BackSpace[1] = "\u007f";
BackSpace[2] = "\u001b[3~";
BackSpace[3] = "\u001b[2~";
}
/* some more VT100 keys */
Find = "\u001b[1~";
Select = "\u001b[4~";
Help = "\u001b[28~";
Do = "\u001b[29~";
FunctionKey = new String[21];
FunctionKey[0] = "";
FunctionKey[1] = PF1;
FunctionKey[2] = PF2;
FunctionKey[3] = PF3;
FunctionKey[4] = PF4;
/* following are defined differently for vt220 / vt132 ... */
FunctionKey[5] = "\u001b[15~";
FunctionKey[6] = "\u001b[17~";
FunctionKey[7] = "\u001b[18~";
FunctionKey[8] = "\u001b[19~";
FunctionKey[9] = "\u001b[20~";
FunctionKey[10] = "\u001b[21~";
FunctionKey[11] = "\u001b[23~";
FunctionKey[12] = "\u001b[24~";
FunctionKey[13] = "\u001b[25~";
FunctionKey[14] = "\u001b[26~";
FunctionKey[15] = Help;
FunctionKey[16] = Do;
FunctionKey[17] = "\u001b[31~";
FunctionKey[18] = "\u001b[32~";
FunctionKey[19] = "\u001b[33~";
FunctionKey[20] = "\u001b[34~";
FunctionKeyShift = new String[21];
FunctionKeyAlt = new String[21];
FunctionKeyCtrl = new String[21];
for (int i = 0; i < 20; i++) {
FunctionKeyShift[i] = "";
FunctionKeyAlt[i] = "";
FunctionKeyCtrl[i] = "";
}
FunctionKeyShift[15] = Find;
FunctionKeyShift[16] = Select;
TabKey[0] = "\u0009";
TabKey[1] = "\u001bOP\u0009";
TabKey[2] = TabKey[3] = "";
KeyUp = new String[4];
KeyUp[0] = "\u001b[A";
KeyDown = new String[4];
KeyDown[0] = "\u001b[B";
KeyRight = new String[4];
KeyRight[0] = "\u001b[C";
KeyLeft = new String[4];
KeyLeft[0] = "\u001b[D";
Numpad = new String[10];
Numpad[0] = "\u001bOp";
Numpad[1] = "\u001bOq";
Numpad[2] = "\u001bOr";
Numpad[3] = "\u001bOs";
Numpad[4] = "\u001bOt";
Numpad[5] = "\u001bOu";
Numpad[6] = "\u001bOv";
Numpad[7] = "\u001bOw";
Numpad[8] = "\u001bOx";
Numpad[9] = "\u001bOy";
KPMinus = PF4;
KPComma = "\u001bOl";
KPPeriod = "\u001bOn";
KPEnter = "\u001bOM";
NUMPlus = new String[4];
NUMPlus[0] = "+";
NUMDot = new String[4];
NUMDot[0] = ".";
}
public void setBackspace(int type) {
switch (type) {
case DELETE_IS_DEL:
BackSpace[0] = "\u007f";
BackSpace[1] = "\b";
break;
case DELETE_IS_BACKSPACE:
BackSpace[0] = "\b";
BackSpace[1] = "\u007f";
break;
}
}
/**
* Create a default vt320 terminal with 80 columns and 24 lines.
*/
public vt320() {
this(80, 24);
}
/**
* Terminal is mouse-aware and requires (x,y) coordinates of
* on the terminal (character coordinates) and the button clicked.
* @param x
* @param y
* @param modifiers
*/
public void mousePressed(int x, int y, int modifiers) {
if (mouserpt == 0)
return;
int mods = modifiers;
mousebut = 3;
if ((mods & 16) == 16) mousebut = 0;
if ((mods & 8) == 8) mousebut = 1;
if ((mods & 4) == 4) mousebut = 2;
int mousecode;
if (mouserpt == 9) /* X10 Mouse */
mousecode = 0x20 | mousebut;
else /* normal xterm mouse reporting */
mousecode = mousebut | 0x20 | ((mods & 7) << 2);
byte b[] = new byte[6];
b[0] = 27;
b[1] = (byte) '[';
b[2] = (byte) 'M';
b[3] = (byte) mousecode;
b[4] = (byte) (0x20 + x + 1);
b[5] = (byte) (0x20 + y + 1);
write(b); // FIXME: writeSpecial here
}
/**
* Terminal is mouse-aware and requires the coordinates and button
* of the release.
* @param x
* @param y
* @param modifiers
*/
public void mouseReleased(int x, int y, int modifiers) {
if (mouserpt == 0)
return;
/* problem is tht modifiers still have the released button set in them.
int mods = modifiers;
mousebut = 3;
if ((mods & 16)==16) mousebut=0;
if ((mods & 8)==8 ) mousebut=1;
if ((mods & 4)==4 ) mousebut=2;
*/
int mousecode;
if (mouserpt == 9)
mousecode = 0x20 + mousebut; /* same as press? appears so. */
else
mousecode = '#';
byte b[] = new byte[6];
b[0] = 27;
b[1] = (byte) '[';
b[2] = (byte) 'M';
b[3] = (byte) mousecode;
b[4] = (byte) (0x20 + x + 1);
b[5] = (byte) (0x20 + y + 1);
write(b); // FIXME: writeSpecial here
mousebut = 0;
}
/** we should do localecho (passed from other modules). false is default */
private boolean localecho = false;
/**
* Enable or disable the local echo property of the terminal.
* @param echo true if the terminal should echo locally
*/
public void setLocalEcho(boolean echo) {
localecho = echo;
}
/**
* Enable the VMS mode of the terminal to handle some things differently
* for VMS hosts.
* @param vms true for vms mode, false for normal mode
*/
public void setVMS(boolean vms) {
this.vms = vms;
}
/**
* Enable the usage of the IBM character set used by some BBS's. Special
* graphical character are available in this mode.
* @param ibm true to use the ibm character set
*/
public void setIBMCharset(boolean ibm) {
useibmcharset = ibm;
}
/**
* Override the standard key codes used by the terminal emulation.
* @param codes a properties object containing key code definitions
*/
public void setKeyCodes(Properties codes) {
String res, prefixes[] = {"", "S", "C", "A"};
int i;
for (i = 0; i < 10; i++) {
res = codes.getProperty("NUMPAD" + i);
if (res != null) Numpad[i] = unEscape(res);
}
for (i = 1; i < 20; i++) {
res = codes.getProperty("F" + i);
if (res != null) FunctionKey[i] = unEscape(res);
res = codes.getProperty("SF" + i);
if (res != null) FunctionKeyShift[i] = unEscape(res);
res = codes.getProperty("CF" + i);
if (res != null) FunctionKeyCtrl[i] = unEscape(res);
res = codes.getProperty("AF" + i);
if (res != null) FunctionKeyAlt[i] = unEscape(res);
}
for (i = 0; i < 4; i++) {
res = codes.getProperty(prefixes[i] + "PGUP");
if (res != null) PrevScn[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "PGDOWN");
if (res != null) NextScn[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "END");
if (res != null) KeyEnd[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "HOME");
if (res != null) KeyHome[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "INSERT");
if (res != null) Insert[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "REMOVE");
if (res != null) Remove[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "UP");
if (res != null) KeyUp[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "DOWN");
if (res != null) KeyDown[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "LEFT");
if (res != null) KeyLeft[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "RIGHT");
if (res != null) KeyRight[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "ESCAPE");
if (res != null) Escape[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "BACKSPACE");
if (res != null) BackSpace[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "TAB");
if (res != null) TabKey[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "NUMPLUS");
if (res != null) NUMPlus[i] = unEscape(res);
res = codes.getProperty(prefixes[i] + "NUMDECIMAL");
if (res != null) NUMDot[i] = unEscape(res);
}
}
/**
* Set the terminal id used to identify this terminal.
* @param terminalID the id string
*/
public void setTerminalID(String terminalID) {
this.terminalID = terminalID;
if (terminalID.equals("scoansi")) {
FunctionKey[1] = "\u001b[M"; FunctionKey[2] = "\u001b[N";
FunctionKey[3] = "\u001b[O"; FunctionKey[4] = "\u001b[P";
FunctionKey[5] = "\u001b[Q"; FunctionKey[6] = "\u001b[R";
FunctionKey[7] = "\u001b[S"; FunctionKey[8] = "\u001b[T";
FunctionKey[9] = "\u001b[U"; FunctionKey[10] = "\u001b[V";
FunctionKey[11] = "\u001b[W"; FunctionKey[12] = "\u001b[X";
FunctionKey[13] = "\u001b[Y"; FunctionKey[14] = "?";
FunctionKey[15] = "\u001b[a"; FunctionKey[16] = "\u001b[b";
FunctionKey[17] = "\u001b[c"; FunctionKey[18] = "\u001b[d";
FunctionKey[19] = "\u001b[e"; FunctionKey[20] = "\u001b[f";
PrevScn[0] = PrevScn[1] = PrevScn[2] = PrevScn[3] = "\u001b[I";
NextScn[0] = NextScn[1] = NextScn[2] = NextScn[3] = "\u001b[G";
// more theoretically.
}
}
public void setAnswerBack(String ab) {
this.answerBack = unEscape(ab);
}
/**
* Get the terminal id used to identify this terminal.
*/
public String getTerminalID() {
return terminalID;
}
/**
* A small conveniance method thar converts the string to a byte array
* for sending.
* @param s the string to be sent
*/
private boolean write(String s, boolean doecho) {
if (debug > 2) {
debugStr.append("write(|")
.append(s)
.append("|,")
.append(doecho);
debug(debugStr.toString());
debugStr.setLength(0);
}
if (s == null) // aka the empty string.
return true;
/* NOTE: getBytes() honours some locale, it *CONVERTS* the string.
* However, we output only 7bit stuff towards the target, and *some*
* 8 bit control codes. We must not mess up the latter, so we do hand
* by hand copy.
*/
byte arr[] = new byte[s.length()];
for (int i = 0; i < s.length(); i++) {
arr[i] = (byte) s.charAt(i);
}
write(arr);
if (doecho)
putString(s);
return true;
}
private boolean write(int s, boolean doecho) {
if (debug > 2) {
debugStr.append("write(|")
.append(s)
.append("|,")
.append(doecho);
debug(debugStr.toString());
debugStr.setLength(0);
}
write(s);
// TODO check if character is wide
if (doecho)
putChar((char)s, false, false);
return true;
}
private boolean write(String s) {
return write(s, localecho);
}
// ===================================================================
// the actual terminal emulation code comes here:
// ===================================================================
private String terminalID = "vt320";
private String answerBack = "Use Terminal.answerback to set ...\n";
// X - COLUMNS, Y - ROWS
int R,C;
int attributes = 0;
int Sc,Sr,Sa,Stm,Sbm;
char Sgr,Sgl;
char Sgx[];
int insertmode = 0;
int statusmode = 0;
boolean vt52mode = false;
boolean keypadmode = false; /* false - numeric, true - application */
boolean output8bit = false;
int normalcursor = 0;
boolean moveoutsidemargins = true;
boolean wraparound = true;
boolean sendcrlf = true;
boolean capslock = false;
boolean numlock = false;
int mouserpt = 0;
byte mousebut = 0;
boolean useibmcharset = false;
int lastwaslf = 0;
boolean usedcharsets = false;
private final static char ESC = 27;
private final static char IND = 132;
private final static char NEL = 133;
private final static char RI = 141;
private final static char SS2 = 142;
private final static char SS3 = 143;
private final static char DCS = 144;
private final static char HTS = 136;
private final static char CSI = 155;
private final static char OSC = 157;
private final static int TSTATE_DATA = 0;
private final static int TSTATE_ESC = 1; /* ESC */
private final static int TSTATE_CSI = 2; /* ESC [ */
private final static int TSTATE_DCS = 3; /* ESC P */
private final static int TSTATE_DCEQ = 4; /* ESC [? */
private final static int TSTATE_ESCSQUARE = 5; /* ESC # */
private final static int TSTATE_OSC = 6; /* ESC ] */
private final static int TSTATE_SETG0 = 7; /* ESC (? */
private final static int TSTATE_SETG1 = 8; /* ESC )? */
private final static int TSTATE_SETG2 = 9; /* ESC *? */
private final static int TSTATE_SETG3 = 10; /* ESC +? */
private final static int TSTATE_CSI_DOLLAR = 11; /* ESC [ Pn $ */
private final static int TSTATE_CSI_EX = 12; /* ESC [ ! */
private final static int TSTATE_ESCSPACE = 13; /* ESC <space> */
private final static int TSTATE_VT52X = 14;
private final static int TSTATE_VT52Y = 15;
private final static int TSTATE_CSI_TICKS = 16;
private final static int TSTATE_CSI_EQUAL = 17; /* ESC [ = */
private final static int TSTATE_TITLE = 18; /* xterm title */
/* Keys we support */
public final static int KEY_PAUSE = 1;
public final static int KEY_F1 = 2;
public final static int KEY_F2 = 3;
public final static int KEY_F3 = 4;
public final static int KEY_F4 = 5;
public final static int KEY_F5 = 6;
public final static int KEY_F6 = 7;
public final static int KEY_F7 = 8;
public final static int KEY_F8 = 9;
public final static int KEY_F9 = 10;
public final static int KEY_F10 = 11;
public final static int KEY_F11 = 12;
public final static int KEY_F12 = 13;
public final static int KEY_UP = 14;
public final static int KEY_DOWN =15 ;
public final static int KEY_LEFT = 16;
public final static int KEY_RIGHT = 17;
public final static int KEY_PAGE_DOWN = 18;
public final static int KEY_PAGE_UP = 19;
public final static int KEY_INSERT = 20;
public final static int KEY_DELETE = 21;
public final static int KEY_BACK_SPACE = 22;
public final static int KEY_HOME = 23;
public final static int KEY_END = 24;
public final static int KEY_NUM_LOCK = 25;
public final static int KEY_CAPS_LOCK = 26;
public final static int KEY_SHIFT = 27;
public final static int KEY_CONTROL = 28;
public final static int KEY_ALT = 29;
public final static int KEY_ENTER = 30;
public final static int KEY_NUMPAD0 = 31;
public final static int KEY_NUMPAD1 = 32;
public final static int KEY_NUMPAD2 = 33;
public final static int KEY_NUMPAD3 = 34;
public final static int KEY_NUMPAD4 = 35;
public final static int KEY_NUMPAD5 = 36;
public final static int KEY_NUMPAD6 = 37;
public final static int KEY_NUMPAD7 = 38;
public final static int KEY_NUMPAD8 = 39;
public final static int KEY_NUMPAD9 = 40;
public final static int KEY_DECIMAL = 41;
public final static int KEY_ADD = 42;
public final static int KEY_ESCAPE = 43;
public final static int DELETE_IS_DEL = 0;
public final static int DELETE_IS_BACKSPACE = 1;
/* The graphics charsets
* B - default ASCII
* A - ISO Latin 1
* 0 - DEC SPECIAL
* < - User defined
* ....
*/
char gx[];
char gl; // GL (left charset)
char gr; // GR (right charset)
int onegl; // single shift override for GL.
// Map from scoansi linedrawing to DEC _and_ unicode (for the stuff which
// is not in linedrawing). Got from experimenting with scoadmin.
private final static String scoansi_acs = "Tm7k3x4u?kZl@mYjEnB\u2566DqCtAvM\u2550:\u2551N\u2557I\u2554;\u2557H\u255a0a<\u255d";
// array to store DEC Special -> Unicode mapping
// Unicode DEC Unicode name (DEC name)
private static char DECSPECIAL[] = {
'\u0040', //5f blank
'\u2666', //60 black diamond
'\u2592', //61 grey square
'\u2409', //62 Horizontal tab (ht) pict. for control
'\u240c', //63 Form Feed (ff) pict. for control
'\u240d', //64 Carriage Return (cr) pict. for control
'\u240a', //65 Line Feed (lf) pict. for control
'\u00ba', //66 Masculine ordinal indicator
'\u00b1', //67 Plus or minus sign
'\u2424', //68 New Line (nl) pict. for control
'\u240b', //69 Vertical Tab (vt) pict. for control
'\u2518', //6a Forms light up and left
'\u2510', //6b Forms light down and left
'\u250c', //6c Forms light down and right
'\u2514', //6d Forms light up and right
'\u253c', //6e Forms light vertical and horizontal
'\u2594', //6f Upper 1/8 block (Scan 1)
'\u2580', //70 Upper 1/2 block (Scan 3)
'\u2500', //71 Forms light horizontal or ?em dash? (Scan 5)
'\u25ac', //72 \u25ac black rect. or \u2582 lower 1/4 (Scan 7)
'\u005f', //73 \u005f underscore or \u2581 lower 1/8 (Scan 9)
'\u251c', //74 Forms light vertical and right
'\u2524', //75 Forms light vertical and left
'\u2534', //76 Forms light up and horizontal
'\u252c', //77 Forms light down and horizontal
'\u2502', //78 vertical bar
'\u2264', //79 less than or equal
'\u2265', //7a greater than or equal
'\u00b6', //7b paragraph
'\u2260', //7c not equal
'\u00a3', //7d Pound Sign (british)
'\u00b7' //7e Middle Dot
};
/** Strings to send on function key pressing */
private String Numpad[];
private String FunctionKey[];
private String FunctionKeyShift[];
private String FunctionKeyCtrl[];
private String FunctionKeyAlt[];
private String TabKey[];
private String KeyUp[],KeyDown[],KeyLeft[],KeyRight[];
private String KPMinus, KPComma, KPPeriod, KPEnter;
private String PF1, PF2, PF3, PF4;
private String Help, Do, Find, Select;
private String KeyHome[], KeyEnd[], Insert[], Remove[], PrevScn[], NextScn[];
private String Escape[], BackSpace[], NUMDot[], NUMPlus[];
private String osc,dcs; /* to memorize OSC & DCS control sequence */
/** vt320 state variable (internal) */
private int term_state = TSTATE_DATA;
/** in vms mode, set by Terminal.VMS property */
private boolean vms = false;
/** Tabulators */
private byte[] Tabs;
/** The list of integers as used by CSI */
private int[] DCEvars = new int[30];
private int DCEvar;
/**
* Replace escape code characters (backslash + identifier) with their
* respective codes.
* @param tmp the string to be parsed
* @return a unescaped string
*/
static String unEscape(String tmp) {
int idx = 0, oldidx = 0;
String cmd;
// f.println("unescape("+tmp+")");
cmd = "";
while ((idx = tmp.indexOf('\\', oldidx)) >= 0 &&
++idx <= tmp.length()) {
cmd += tmp.substring(oldidx, idx - 1);
if (idx == tmp.length()) return cmd;
switch (tmp.charAt(idx)) {
case 'b':
cmd += "\b";
break;
case 'e':
cmd += "\u001b";
break;
case 'n':
cmd += "\n";
break;
case 'r':
cmd += "\r";
break;
case 't':
cmd += "\t";
break;
case 'v':
cmd += "\u000b";
break;
case 'a':
cmd += "\u0012";
break;
default :
if ((tmp.charAt(idx) >= '0') && (tmp.charAt(idx) <= '9')) {
int i;
for (i = idx; i < tmp.length(); i++)
if ((tmp.charAt(i) < '0') || (tmp.charAt(i) > '9'))
break;
cmd += (char) Integer.parseInt(tmp.substring(idx, i));
idx = i - 1;
} else
cmd += tmp.substring(idx, ++idx);
break;
}
oldidx = ++idx;
}
if (oldidx <= tmp.length()) cmd += tmp.substring(oldidx);
return cmd;
}
/**
* A small conveniance method thar converts a 7bit string to the 8bit
* version depending on VT52/Output8Bit mode.
*
* @param s the string to be sent
*/
private boolean writeSpecial(String s) {
if (s == null)
return true;
if (((s.length() >= 3) && (s.charAt(0) == 27) && (s.charAt(1) == 'O'))) {
if (vt52mode) {
if ((s.charAt(2) >= 'P') && (s.charAt(2) <= 'S')) {
s = "\u001b" + s.substring(2); /* ESC x */
} else {
s = "\u001b?" + s.substring(2); /* ESC ? x */
}
} else {
if (output8bit) {
s = "\u008f" + s.substring(2); /* SS3 x */
} /* else keep string as it is */
}
}
if (((s.length() >= 3) && (s.charAt(0) == 27) && (s.charAt(1) == '['))) {
if (output8bit) {
s = "\u009b" + s.substring(2); /* CSI ... */
} /* else keep */
}
return write(s, false);
}
/**
* main keytyping event handler...
*/
public void keyPressed(int keyCode, char keyChar, int modifiers) {
boolean control = (modifiers & VDUInput.KEY_CONTROL) != 0;
boolean shift = (modifiers & VDUInput.KEY_SHIFT) != 0;
boolean alt = (modifiers & VDUInput.KEY_ALT) != 0;
if (debug > 1) {
debugStr.append("keyPressed(")
.append(keyCode)
.append(", ")
.append((int)keyChar)
.append(", ")
.append(modifiers)
.append(')');
debug(debugStr.toString());
debugStr.setLength(0);
}
int xind;
String fmap[];
xind = 0;
fmap = FunctionKey;
if (shift) {
fmap = FunctionKeyShift;
xind = 1;
}
if (control) {
fmap = FunctionKeyCtrl;
xind = 2;
}
if (alt) {
fmap = FunctionKeyAlt;
xind = 3;
}
switch (keyCode) {
case KEY_PAUSE:
if (shift || control)
sendTelnetCommand((byte) 243); // BREAK
break;
case KEY_F1:
writeSpecial(fmap[1]);
break;
case KEY_F2:
writeSpecial(fmap[2]);
break;
case KEY_F3:
writeSpecial(fmap[3]);
break;
case KEY_F4:
writeSpecial(fmap[4]);
break;
case KEY_F5:
writeSpecial(fmap[5]);
break;
case KEY_F6:
writeSpecial(fmap[6]);
break;
case KEY_F7:
writeSpecial(fmap[7]);
break;
case KEY_F8:
writeSpecial(fmap[8]);
break;
case KEY_F9:
writeSpecial(fmap[9]);
break;
case KEY_F10:
writeSpecial(fmap[10]);
break;
case KEY_F11:
writeSpecial(fmap[11]);
break;
case KEY_F12:
writeSpecial(fmap[12]);
break;
case KEY_UP:
writeSpecial(KeyUp[xind]);
break;
case KEY_DOWN:
writeSpecial(KeyDown[xind]);
break;
case KEY_LEFT:
writeSpecial(KeyLeft[xind]);
break;
case KEY_RIGHT:
writeSpecial(KeyRight[xind]);
break;
case KEY_PAGE_DOWN:
writeSpecial(NextScn[xind]);
break;
case KEY_PAGE_UP:
writeSpecial(PrevScn[xind]);
break;
case KEY_INSERT:
writeSpecial(Insert[xind]);
break;
case KEY_DELETE:
writeSpecial(Remove[xind]);
break;
case KEY_BACK_SPACE:
writeSpecial(BackSpace[xind]);
if (localecho) {
if (BackSpace[xind] == "\b") {
putString("\b \b"); // make the last char 'deleted'
} else {
putString(BackSpace[xind]); // echo it
}
}
break;
case KEY_HOME:
writeSpecial(KeyHome[xind]);
break;
case KEY_END:
writeSpecial(KeyEnd[xind]);
break;
case KEY_NUM_LOCK:
if (vms && control) {
writeSpecial(PF1);
}
if (!control)
numlock = !numlock;
break;
case KEY_CAPS_LOCK:
capslock = !capslock;
return;
case KEY_SHIFT:
case KEY_CONTROL:
case KEY_ALT:
return;
default:
break;
}
}
/*
public void keyReleased(KeyEvent evt) {
if (debug > 1) debug("keyReleased("+evt+")");
// ignore
}
*/
/**
* Handle key Typed events for the terminal, this will get
* all normal key types, but no shift/alt/control/numlock.
*/
public void keyTyped(int keyCode, char keyChar, int modifiers) {
boolean control = (modifiers & VDUInput.KEY_CONTROL) != 0;
boolean shift = (modifiers & VDUInput.KEY_SHIFT) != 0;
boolean alt = (modifiers & VDUInput.KEY_ALT) != 0;
if (debug > 1) debug("keyTyped("+keyCode+", "+(int)keyChar+", "+modifiers+")");
if (keyChar == '\t') {
if (shift) {
write(TabKey[1], false);
} else {
if (control) {
write(TabKey[2], false);
} else {
if (alt) {
write(TabKey[3], false);
} else {
write(TabKey[0], false);
}
}
}
return;
}
if (alt) {
write(((char) (keyChar | 0x80)));
return;
}
if (((keyCode == KEY_ENTER) || (keyChar == 10))
&& !control) {
write('\r');
if (localecho) putString("\r\n"); // bad hack
return;
}
if ((keyCode == 10) && !control) {
debug("Sending \\r");
write('\r');
return;
}
// FIXME: on german PC keyboards you have to use Alt-Ctrl-q to get an @,
// so we can't just use it here... will probably break some other VMS
// codes. -Marcus
// if(((!vms && keyChar == '2') || keyChar == '@' || keyChar == ' ')
// && control)
if (((!vms && keyChar == '2') || keyChar == ' ') && control)
write(0);
if (vms) {
if (keyChar == 127 && !control) {
if (shift)
writeSpecial(Insert[0]); // VMS shift delete = insert
else
writeSpecial(Remove[0]); // VMS delete = remove
return;
} else if (control)
switch (keyChar) {
case '0':
writeSpecial(Numpad[0]);
return;
case '1':
writeSpecial(Numpad[1]);
return;
case '2':
writeSpecial(Numpad[2]);
return;
case '3':
writeSpecial(Numpad[3]);
return;
case '4':
writeSpecial(Numpad[4]);
return;
case '5':
writeSpecial(Numpad[5]);
return;
case '6':
writeSpecial(Numpad[6]);
return;
case '7':
writeSpecial(Numpad[7]);
return;
case '8':
writeSpecial(Numpad[8]);
return;
case '9':
writeSpecial(Numpad[9]);
return;
case '.':
writeSpecial(KPPeriod);
return;
case '-':
case 31:
writeSpecial(KPMinus);
return;
case '+':
writeSpecial(KPComma);
return;
case 10:
writeSpecial(KPEnter);
return;
case '/':
writeSpecial(PF2);
return;
case '*':
writeSpecial(PF3);
return;
/* NUMLOCK handled in keyPressed */
default:
break;
}
/* Now what does this do and how did it get here. -Marcus
if (shift && keyChar < 32) {
write(PF1+(char)(keyChar + 64));
return;
}
*/
}
// FIXME: not used?
//String fmap[];
int xind;
xind = 0;
//fmap = FunctionKey;
if (shift) {
//fmap = FunctionKeyShift;
xind = 1;
}
if (control) {
//fmap = FunctionKeyCtrl;
xind = 2;
}
if (alt) {
//fmap = FunctionKeyAlt;
xind = 3;
}
if (keyCode == KEY_ESCAPE) {
writeSpecial(Escape[xind]);
return;
}
if ((modifiers & VDUInput.KEY_ACTION) != 0)
switch (keyCode) {
case KEY_NUMPAD0:
writeSpecial(Numpad[0]);
return;
case KEY_NUMPAD1:
writeSpecial(Numpad[1]);
return;
case KEY_NUMPAD2:
writeSpecial(Numpad[2]);
return;
case KEY_NUMPAD3:
writeSpecial(Numpad[3]);
return;
case KEY_NUMPAD4:
writeSpecial(Numpad[4]);
return;
case KEY_NUMPAD5:
writeSpecial(Numpad[5]);
return;
case KEY_NUMPAD6:
writeSpecial(Numpad[6]);
return;
case KEY_NUMPAD7:
writeSpecial(Numpad[7]);
return;
case KEY_NUMPAD8:
writeSpecial(Numpad[8]);
return;
case KEY_NUMPAD9:
writeSpecial(Numpad[9]);
return;
case KEY_DECIMAL:
writeSpecial(NUMDot[xind]);
return;
case KEY_ADD:
writeSpecial(NUMPlus[xind]);
return;
}
if (!((keyChar == 8) || (keyChar == 127) || (keyChar == '\r') || (keyChar == '\n'))) {
write(keyChar);
return;
}
}
private void handle_dcs(String dcs) {
debugStr.append("DCS: ")
.append(dcs);
debug(debugStr.toString());
debugStr.setLength(0);
}
private void handle_osc(String osc) {
if (osc.length() > 2 && osc.substring(0, 2).equals("4;")) {
// Define color palette
String[] colorData = osc.split(";");
try {
int colorIndex = Integer.parseInt(colorData[1]);
if ("rgb:".equals(colorData[2].substring(0, 4))) {
String[] rgb = colorData[2].substring(4).split("/");
int red = Integer.parseInt(rgb[0].substring(0, 2), 16) & 0xFF;
int green = Integer.parseInt(rgb[1].substring(0, 2), 16) & 0xFF;
int blue = Integer.parseInt(rgb[2].substring(0, 2), 16) & 0xFF;
display.setColor(colorIndex, red, green, blue);
}
} catch (Exception e) {
debugStr.append("OSC: invalid color sequence encountered: ")
.append(osc);
debug(debugStr.toString());
debugStr.setLength(0);
}
} else
debug("OSC: " + osc);
}
private final static char unimap[] = {
//#
//# Name: cp437_DOSLatinUS to Unicode table
//# Unicode version: 1.1
//# Table version: 1.1
//# Table format: Format A
//# Date: 03/31/95
//# Authors: Michel Suignard <michelsu@microsoft.com>
//# Lori Hoerth <lorih@microsoft.com>
//# General notes: none
//#
//# Format: Three tab-separated columns
//# Column #1 is the cp1255_WinHebrew code (in hex)
//# Column #2 is the Unicode (in hex as 0xXXXX)
//# Column #3 is the Unicode name (follows a comment sign, '#')
//#
//# The entries are in cp437_DOSLatinUS order
//#
0x0000, // #NULL
0x0001, // #START OF HEADING
0x0002, // #START OF TEXT
0x0003, // #END OF TEXT
0x0004, // #END OF TRANSMISSION
0x0005, // #ENQUIRY
0x0006, // #ACKNOWLEDGE
0x0007, // #BELL
0x0008, // #BACKSPACE
0x0009, // #HORIZONTAL TABULATION
0x000a, // #LINE FEED
0x000b, // #VERTICAL TABULATION
0x000c, // #FORM FEED
0x000d, // #CARRIAGE RETURN
0x000e, // #SHIFT OUT
0x000f, // #SHIFT IN
0x0010, // #DATA LINK ESCAPE
0x0011, // #DEVICE CONTROL ONE
0x0012, // #DEVICE CONTROL TWO
0x0013, // #DEVICE CONTROL THREE
0x0014, // #DEVICE CONTROL FOUR
0x0015, // #NEGATIVE ACKNOWLEDGE
0x0016, // #SYNCHRONOUS IDLE
0x0017, // #END OF TRANSMISSION BLOCK
0x0018, // #CANCEL
0x0019, // #END OF MEDIUM
0x001a, // #SUBSTITUTE
0x001b, // #ESCAPE
0x001c, // #FILE SEPARATOR
0x001d, // #GROUP SEPARATOR
0x001e, // #RECORD SEPARATOR
0x001f, // #UNIT SEPARATOR
0x0020, // #SPACE
0x0021, // #EXCLAMATION MARK
0x0022, // #QUOTATION MARK
0x0023, // #NUMBER SIGN
0x0024, // #DOLLAR SIGN
0x0025, // #PERCENT SIGN
0x0026, // #AMPERSAND
0x0027, // #APOSTROPHE
0x0028, // #LEFT PARENTHESIS
0x0029, // #RIGHT PARENTHESIS
0x002a, // #ASTERISK
0x002b, // #PLUS SIGN
0x002c, // #COMMA
0x002d, // #HYPHEN-MINUS
0x002e, // #FULL STOP
0x002f, // #SOLIDUS
0x0030, // #DIGIT ZERO
0x0031, // #DIGIT ONE
0x0032, // #DIGIT TWO
0x0033, // #DIGIT THREE
0x0034, // #DIGIT FOUR
0x0035, // #DIGIT FIVE
0x0036, // #DIGIT SIX
0x0037, // #DIGIT SEVEN
0x0038, // #DIGIT EIGHT
0x0039, // #DIGIT NINE
0x003a, // #COLON
0x003b, // #SEMICOLON
0x003c, // #LESS-THAN SIGN
0x003d, // #EQUALS SIGN
0x003e, // #GREATER-THAN SIGN
0x003f, // #QUESTION MARK
0x0040, // #COMMERCIAL AT
0x0041, // #LATIN CAPITAL LETTER A
0x0042, // #LATIN CAPITAL LETTER B
0x0043, // #LATIN CAPITAL LETTER C
0x0044, // #LATIN CAPITAL LETTER D
0x0045, // #LATIN CAPITAL LETTER E
0x0046, // #LATIN CAPITAL LETTER F
0x0047, // #LATIN CAPITAL LETTER G
0x0048, // #LATIN CAPITAL LETTER H
0x0049, // #LATIN CAPITAL LETTER I
0x004a, // #LATIN CAPITAL LETTER J
0x004b, // #LATIN CAPITAL LETTER K
0x004c, // #LATIN CAPITAL LETTER L
0x004d, // #LATIN CAPITAL LETTER M
0x004e, // #LATIN CAPITAL LETTER N
0x004f, // #LATIN CAPITAL LETTER O
0x0050, // #LATIN CAPITAL LETTER P
0x0051, // #LATIN CAPITAL LETTER Q
0x0052, // #LATIN CAPITAL LETTER R
0x0053, // #LATIN CAPITAL LETTER S
0x0054, // #LATIN CAPITAL LETTER T
0x0055, // #LATIN CAPITAL LETTER U
0x0056, // #LATIN CAPITAL LETTER V
0x0057, // #LATIN CAPITAL LETTER W
0x0058, // #LATIN CAPITAL LETTER X
0x0059, // #LATIN CAPITAL LETTER Y
0x005a, // #LATIN CAPITAL LETTER Z
0x005b, // #LEFT SQUARE BRACKET
0x005c, // #REVERSE SOLIDUS
0x005d, // #RIGHT SQUARE BRACKET
0x005e, // #CIRCUMFLEX ACCENT
0x005f, // #LOW LINE
0x0060, // #GRAVE ACCENT
0x0061, // #LATIN SMALL LETTER A
0x0062, // #LATIN SMALL LETTER B
0x0063, // #LATIN SMALL LETTER C
0x0064, // #LATIN SMALL LETTER D
0x0065, // #LATIN SMALL LETTER E
0x0066, // #LATIN SMALL LETTER F
0x0067, // #LATIN SMALL LETTER G
0x0068, // #LATIN SMALL LETTER H
0x0069, // #LATIN SMALL LETTER I
0x006a, // #LATIN SMALL LETTER J
0x006b, // #LATIN SMALL LETTER K
0x006c, // #LATIN SMALL LETTER L
0x006d, // #LATIN SMALL LETTER M
0x006e, // #LATIN SMALL LETTER N
0x006f, // #LATIN SMALL LETTER O
0x0070, // #LATIN SMALL LETTER P
0x0071, // #LATIN SMALL LETTER Q
0x0072, // #LATIN SMALL LETTER R
0x0073, // #LATIN SMALL LETTER S
0x0074, // #LATIN SMALL LETTER T
0x0075, // #LATIN SMALL LETTER U
0x0076, // #LATIN SMALL LETTER V
0x0077, // #LATIN SMALL LETTER W
0x0078, // #LATIN SMALL LETTER X
0x0079, // #LATIN SMALL LETTER Y
0x007a, // #LATIN SMALL LETTER Z
0x007b, // #LEFT CURLY BRACKET
0x007c, // #VERTICAL LINE
0x007d, // #RIGHT CURLY BRACKET
0x007e, // #TILDE
0x007f, // #DELETE
0x00c7, // #LATIN CAPITAL LETTER C WITH CEDILLA
0x00fc, // #LATIN SMALL LETTER U WITH DIAERESIS
0x00e9, // #LATIN SMALL LETTER E WITH ACUTE
0x00e2, // #LATIN SMALL LETTER A WITH CIRCUMFLEX
0x00e4, // #LATIN SMALL LETTER A WITH DIAERESIS
0x00e0, // #LATIN SMALL LETTER A WITH GRAVE
0x00e5, // #LATIN SMALL LETTER A WITH RING ABOVE
0x00e7, // #LATIN SMALL LETTER C WITH CEDILLA
0x00ea, // #LATIN SMALL LETTER E WITH CIRCUMFLEX
0x00eb, // #LATIN SMALL LETTER E WITH DIAERESIS
0x00e8, // #LATIN SMALL LETTER E WITH GRAVE
0x00ef, // #LATIN SMALL LETTER I WITH DIAERESIS
0x00ee, // #LATIN SMALL LETTER I WITH CIRCUMFLEX
0x00ec, // #LATIN SMALL LETTER I WITH GRAVE
0x00c4, // #LATIN CAPITAL LETTER A WITH DIAERESIS
0x00c5, // #LATIN CAPITAL LETTER A WITH RING ABOVE
0x00c9, // #LATIN CAPITAL LETTER E WITH ACUTE
0x00e6, // #LATIN SMALL LIGATURE AE
0x00c6, // #LATIN CAPITAL LIGATURE AE
0x00f4, // #LATIN SMALL LETTER O WITH CIRCUMFLEX
0x00f6, // #LATIN SMALL LETTER O WITH DIAERESIS
0x00f2, // #LATIN SMALL LETTER O WITH GRAVE
0x00fb, // #LATIN SMALL LETTER U WITH CIRCUMFLEX
0x00f9, // #LATIN SMALL LETTER U WITH GRAVE
0x00ff, // #LATIN SMALL LETTER Y WITH DIAERESIS
0x00d6, // #LATIN CAPITAL LETTER O WITH DIAERESIS
0x00dc, // #LATIN CAPITAL LETTER U WITH DIAERESIS
0x00a2, // #CENT SIGN
0x00a3, // #POUND SIGN
0x00a5, // #YEN SIGN
0x20a7, // #PESETA SIGN
0x0192, // #LATIN SMALL LETTER F WITH HOOK
0x00e1, // #LATIN SMALL LETTER A WITH ACUTE
0x00ed, // #LATIN SMALL LETTER I WITH ACUTE
0x00f3, // #LATIN SMALL LETTER O WITH ACUTE
0x00fa, // #LATIN SMALL LETTER U WITH ACUTE
0x00f1, // #LATIN SMALL LETTER N WITH TILDE
0x00d1, // #LATIN CAPITAL LETTER N WITH TILDE
0x00aa, // #FEMININE ORDINAL INDICATOR
0x00ba, // #MASCULINE ORDINAL INDICATOR
0x00bf, // #INVERTED QUESTION MARK
0x2310, // #REVERSED NOT SIGN
0x00ac, // #NOT SIGN
0x00bd, // #VULGAR FRACTION ONE HALF
0x00bc, // #VULGAR FRACTION ONE QUARTER
0x00a1, // #INVERTED EXCLAMATION MARK
0x00ab, // #LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00bb, // #RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x2591, // #LIGHT SHADE
0x2592, // #MEDIUM SHADE
0x2593, // #DARK SHADE
0x2502, // #BOX DRAWINGS LIGHT VERTICAL
0x2524, // #BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x2561, // #BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x2562, // #BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x2556, // #BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x2555, // #BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x2563, // #BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x2551, // #BOX DRAWINGS DOUBLE VERTICAL
0x2557, // #BOX DRAWINGS DOUBLE DOWN AND LEFT
0x255d, // #BOX DRAWINGS DOUBLE UP AND LEFT
0x255c, // #BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x255b, // #BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x2510, // #BOX DRAWINGS LIGHT DOWN AND LEFT
0x2514, // #BOX DRAWINGS LIGHT UP AND RIGHT
0x2534, // #BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x252c, // #BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x251c, // #BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x2500, // #BOX DRAWINGS LIGHT HORIZONTAL
0x253c, // #BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x255e, // #BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x255f, // #BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x255a, // #BOX DRAWINGS DOUBLE UP AND RIGHT
0x2554, // #BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x2569, // #BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x2566, // #BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x2560, // #BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x2550, // #BOX DRAWINGS DOUBLE HORIZONTAL
0x256c, // #BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x2567, // #BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x2568, // #BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x2564, // #BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x2565, // #BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x2559, // #BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x2558, // #BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x2552, // #BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x2553, // #BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x256b, // #BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x256a, // #BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x2518, // #BOX DRAWINGS LIGHT UP AND LEFT
0x250c, // #BOX DRAWINGS LIGHT DOWN AND RIGHT
0x2588, // #FULL BLOCK
0x2584, // #LOWER HALF BLOCK
0x258c, // #LEFT HALF BLOCK
0x2590, // #RIGHT HALF BLOCK
0x2580, // #UPPER HALF BLOCK
0x03b1, // #GREEK SMALL LETTER ALPHA
0x00df, // #LATIN SMALL LETTER SHARP S
0x0393, // #GREEK CAPITAL LETTER GAMMA
0x03c0, // #GREEK SMALL LETTER PI
0x03a3, // #GREEK CAPITAL LETTER SIGMA
0x03c3, // #GREEK SMALL LETTER SIGMA
0x00b5, // #MICRO SIGN
0x03c4, // #GREEK SMALL LETTER TAU
0x03a6, // #GREEK CAPITAL LETTER PHI
0x0398, // #GREEK CAPITAL LETTER THETA
0x03a9, // #GREEK CAPITAL LETTER OMEGA
0x03b4, // #GREEK SMALL LETTER DELTA
0x221e, // #INFINITY
0x03c6, // #GREEK SMALL LETTER PHI
0x03b5, // #GREEK SMALL LETTER EPSILON
0x2229, // #INTERSECTION
0x2261, // #IDENTICAL TO
0x00b1, // #PLUS-MINUS SIGN
0x2265, // #GREATER-THAN OR EQUAL TO
0x2264, // #LESS-THAN OR EQUAL TO
0x2320, // #TOP HALF INTEGRAL
0x2321, // #BOTTOM HALF INTEGRAL
0x00f7, // #DIVISION SIGN
0x2248, // #ALMOST EQUAL TO
0x00b0, // #DEGREE SIGN
0x2219, // #BULLET OPERATOR
0x00b7, // #MIDDLE DOT
0x221a, // #SQUARE ROOT
0x207f, // #SUPERSCRIPT LATIN SMALL LETTER N
0x00b2, // #SUPERSCRIPT TWO
0x25a0, // #BLACK SQUARE
0x00a0, // #NO-BREAK SPACE
};
public char map_cp850_unicode(char x) {
if (x >= 0x100)
return x;
return unimap[x];
}
private void _SetCursor(int row, int col) {
int maxr = height - 1;
int tm = getTopMargin();
R = (row < 0)?0: row;
C = (col < 0)?0: (col >= width) ? width - 1 : col;
if (!moveoutsidemargins) {
R += tm;
maxr = getBottomMargin();
}
if (R > maxr) R = maxr;
}
private void putChar(char c, boolean isWide, boolean doshowcursor) {
int rows = this.height; //statusline
int columns = this.width;
// byte msg[];
// if (debug > 4) {
// debugStr.append("putChar(")
// .append(c)
// .append(" [")
// .append((int) c)
// .append("]) at R=")
// .append(R)
// .append(" , C=")
// .append(C)
// .append(", columns=")
// .append(columns)
// .append(", rows=")
// .append(rows);
// debug(debugStr.toString());
// debugStr.setLength(0);
// }
// markLine(R, 1);
// if (c > 255) {
// if (debug > 0)
// debug("char > 255:" + (int) c);
// //return;
// }
switch (term_state) {
case TSTATE_DATA:
/* FIXME: we shouldn't use chars with bit 8 set if ibmcharset.
* probably... but some BBS do anyway...
*/
if (!useibmcharset) {
boolean doneflag = true;
switch (c) {
case OSC:
osc = "";
term_state = TSTATE_OSC;
break;
case RI:
if (R > getTopMargin())
R--;
else
insertLine(R, 1, SCROLL_DOWN);
if (debug > 1)
debug("RI");
break;
case IND:
if (debug > 2) {
debugStr.append("IND at ")
.append(R)
.append(", tm is ")
.append(getTopMargin())
.append(", bm is ")
.append(getBottomMargin());
debug(debugStr.toString());
debugStr.setLength(0);
}
if (R == getBottomMargin() || R == rows - 1)
insertLine(R, 1, SCROLL_UP);
else
R++;
if (debug > 1)
debug("IND (at " + R + " )");
break;
case NEL:
if (R == getBottomMargin() || R == rows - 1)
insertLine(R, 1, SCROLL_UP);
else
R++;
C = 0;
if (debug > 1)
debug("NEL (at " + R + " )");
break;
case HTS:
Tabs[C] = 1;
if (debug > 1)
debug("HTS");
break;
case DCS:
dcs = "";
term_state = TSTATE_DCS;
break;
default:
doneflag = false;
break;
}
if (doneflag) break;
}
switch (c) {
case SS3:
onegl = 3;
break;
case SS2:
onegl = 2;
break;
case CSI: // should be in the 8bit section, but some BBS use this
DCEvar = 0;
DCEvars[0] = 0;
DCEvars[1] = 0;
DCEvars[2] = 0;
DCEvars[3] = 0;
term_state = TSTATE_CSI;
break;
case ESC:
term_state = TSTATE_ESC;
lastwaslf = 0;
break;
case 5: /* ENQ */
write(answerBack, false);
break;
case 12:
/* FormFeed, Home for the BBS world */
deleteArea(0, 0, columns, rows, attributes);
C = R = 0;
break;
case '\b': /* 8 */
C--;
if (C < 0)
C = 0;
lastwaslf = 0;
break;
case '\t':
do {
// Don't overwrite or insert! TABS are not destructive, but movement!
C++;
} while (C < columns && (Tabs[C] == 0));
lastwaslf = 0;
break;
case '\r': // 13 CR
C = 0;
break;
case '\n': // 10 LF
if (debug > 3)
debug("R= " + R + ", bm " + getBottomMargin() + ", tm=" + getTopMargin() + ", rows=" + rows);
if (!vms) {
if (lastwaslf != 0 && lastwaslf != c) // Ray: I do not understand this logic.
break;
lastwaslf = c;
/*C = 0;*/
}
if (R == getBottomMargin() || R >= rows - 1)
insertLine(R, 1, SCROLL_UP);
else
R++;
break;
case 7:
beep();
break;
case '\016': /* SMACS , as */
/* ^N, Shift out - Put G1 into GL */
gl = 1;
usedcharsets = true;
break;
case '\017': /* RMACS , ae */
/* ^O, Shift in - Put G0 into GL */
gl = 0;
usedcharsets = true;
break;
default:
{
int thisgl = gl;
if (onegl >= 0) {
thisgl = onegl;
onegl = -1;
}
lastwaslf = 0;
if (c < 32) {
if (c != 0)
if (debug > 0)
debug("TSTATE_DATA char: " + ((int) c));
/*break; some BBS really want those characters, like hearst etc. */
if (c == 0) /* print 0 ... you bet */
break;
}
if (C >= columns) {
if (wraparound) {
int bot = rows;
// If we're in the scroll region, check against the bottom margin
if (R <= getBottomMargin() && R >= getTopMargin())
bot = getBottomMargin() + 1;
if (R < bot - 1)
R++;
else {
if (debug > 3) debug("scrolling due to wrap at " + R);
insertLine(R, 1, SCROLL_UP);
}
C = 0;
} else {
// cursor stays on last character.
C = columns - 1;
}
}
boolean mapped = false;
// Mapping if DEC Special is chosen charset
if (usedcharsets) {
if (c >= '\u0020' && c <= '\u007f') {
switch (gx[thisgl]) {
case '0':
// Remap SCOANSI line drawing to VT100 line drawing chars
// for our SCO using customers.
if (terminalID.equals("scoansi") || terminalID.equals("ansi")) {
for (int i = 0; i < scoansi_acs.length(); i += 2) {
if (c == scoansi_acs.charAt(i)) {
c = scoansi_acs.charAt(i + 1);
break;
}
}
}
if (c >= '\u005f' && c <= '\u007e') {
c = DECSPECIAL[(short) c - 0x5f];
mapped = true;
}
break;
case '<': // 'user preferred' is currently 'ISO Latin-1 suppl
c = (char) ((c & 0x7f) | 0x80);
mapped = true;
break;
case 'A':
case 'B': // Latin-1 , ASCII -> fall through
mapped = true;
break;
default:
debug("Unsupported GL mapping: " + gx[thisgl]);
break;
}
}
if (!mapped && (c >= '\u0080' && c <= '\u00ff')) {
switch (gx[gr]) {
case '0':
if (c >= '\u00df' && c <= '\u00fe') {
c = DECSPECIAL[c - '\u00df'];
mapped = true;
}
break;
case '<':
case 'A':
case 'B':
mapped = true;
break;
default:
debug("Unsupported GR mapping: " + gx[gr]);
break;
}
}
}
if (!mapped && useibmcharset)
c = map_cp850_unicode(c);
/*if(true || (statusmode == 0)) { */
if (isWide) {
if (C >= columns - 1) {
if (wraparound) {
int bot = rows;
// If we're in the scroll region, check against the bottom margin
if (R <= getBottomMargin() && R >= getTopMargin())
bot = getBottomMargin() + 1;
if (R < bot - 1)
R++;
else {
if (debug > 3) debug("scrolling due to wrap at " + R);
insertLine(R, 1, SCROLL_UP);
}
C = 0;
} else {
// cursor stays on last wide character.
C = columns - 2;
}
}
}
if (insertmode == 1) {
if (isWide) {
insertChar(C++, R, c, attributes | FULLWIDTH);
insertChar(C, R, ' ', attributes | FULLWIDTH);
} else
insertChar(C, R, c, attributes);
} else {
if (isWide) {
putChar(C++, R, c, attributes | FULLWIDTH);
putChar(C, R, ' ', attributes | FULLWIDTH);
} else
putChar(C, R, c, attributes);
}
/*
} else {
if (insertmode==1) {
insertChar(C, rows, c, attributes);
} else {
putChar(C, rows, c, attributes);
}
}
*/
C++;
break;
}
} /* switch(c) */
break;
case TSTATE_OSC:
if ((c < 0x20) && (c != ESC)) {// NP - No printing character
handle_osc(osc);
term_state = TSTATE_DATA;
break;
}
//but check for vt102 ESC \
if (c == '\\' && osc.charAt(osc.length() - 1) == ESC) {
handle_osc(osc);
term_state = TSTATE_DATA;
break;
}
osc = osc + c;
break;
case TSTATE_ESCSPACE:
term_state = TSTATE_DATA;
switch (c) {
case 'F': /* S7C1T, Disable output of 8-bit controls, use 7-bit */
output8bit = false;
break;
case 'G': /* S8C1T, Enable output of 8-bit control codes*/
output8bit = true;
break;
default:
debug("ESC <space> " + c + " unhandled.");
}
break;
case TSTATE_ESC:
term_state = TSTATE_DATA;
switch (c) {
case ' ':
term_state = TSTATE_ESCSPACE;
break;
case '#':
term_state = TSTATE_ESCSQUARE;
break;
case 'c':
/* Hard terminal reset */
reset();
break;
case '[':
DCEvar = 0;
DCEvars[0] = 0;
DCEvars[1] = 0;
DCEvars[2] = 0;
DCEvars[3] = 0;
term_state = TSTATE_CSI;
break;
case ']':
osc = "";
term_state = TSTATE_OSC;
break;
case 'P':
dcs = "";
term_state = TSTATE_DCS;
break;
case 'A': /* CUU */
R--;
if (R < 0) R = 0;
break;
case 'B': /* CUD */
R++;
if (R >= rows) R = rows - 1;
break;
case 'C':
C++;
if (C >= columns) C = columns - 1;
break;
case 'I': // RI
insertLine(R, 1, SCROLL_DOWN);
break;
case 'E': /* NEL */
if (R == getBottomMargin() || R == rows - 1)
insertLine(R, 1, SCROLL_UP);
else
R++;
C = 0;
if (debug > 1)
debug("ESC E (at " + R + ")");
break;
case 'D': /* IND */
if (R == getBottomMargin() || R == rows - 1)
insertLine(R, 1, SCROLL_UP);
else
R++;
if (debug > 1)
debug("ESC D (at " + R + " )");
break;
case 'J': /* erase to end of screen */
if (R < rows - 1)
deleteArea(0, R + 1, columns, rows - R - 1, attributes);
if (C < columns - 1)
deleteArea(C, R, columns - C, 1, attributes);
break;
case 'K':
if (C < columns - 1)
deleteArea(C, R, columns - C, 1, attributes);
break;
case 'M': // RI
debug("ESC M : R is "+R+", tm is "+getTopMargin()+", bm is "+getBottomMargin());
if (R > getTopMargin()) { // just go up 1 line.
R--;
} else { // scroll down
insertLine(R, 1, SCROLL_DOWN);
}
/* else do nothing ; */
if (debug > 2)
debug("ESC M ");
break;
case 'H':
if (debug > 1)
debug("ESC H at " + C);
/* right border probably ...*/
if (C >= columns)
C = columns - 1;
Tabs[C] = 1;
break;
case 'N': // SS2
onegl = 2;
break;
case 'O': // SS3
onegl = 3;
break;
case '=':
/*application keypad*/
if (debug > 0)
debug("ESC =");
keypadmode = true;
break;
case '<': /* vt52 mode off */
vt52mode = false;
break;
case '>': /*normal keypad*/
if (debug > 0)
debug("ESC >");
keypadmode = false;
break;
case '7': /* DECSC: save cursor, attributes */
Sc = C;
Sr = R;
Sgl = gl;
Sgr = gr;
Sa = attributes;
Sgx = new char[4];
for (int i = 0; i < 4; i++) Sgx[i] = gx[i];
if (debug > 1)
debug("ESC 7");
break;
case '8': /* DECRC: restore cursor, attributes */
C = Sc;
R = Sr;
gl = Sgl;
gr = Sgr;
if (Sgx != null)
for (int i = 0; i < 4; i++) gx[i] = Sgx[i];
attributes = Sa;
if (debug > 1)
debug("ESC 8");
break;
case '(': /* Designate G0 Character set (ISO 2022) */
term_state = TSTATE_SETG0;
usedcharsets = true;
break;
case ')': /* Designate G1 character set (ISO 2022) */
term_state = TSTATE_SETG1;
usedcharsets = true;
break;
case '*': /* Designate G2 Character set (ISO 2022) */
term_state = TSTATE_SETG2;
usedcharsets = true;
break;
case '+': /* Designate G3 Character set (ISO 2022) */
term_state = TSTATE_SETG3;
usedcharsets = true;
break;
case '~': /* Locking Shift 1, right */
gr = 1;
usedcharsets = true;
break;
case 'n': /* Locking Shift 2 */
gl = 2;
usedcharsets = true;
break;
case '}': /* Locking Shift 2, right */
gr = 2;
usedcharsets = true;
break;
case 'o': /* Locking Shift 3 */
gl = 3;
usedcharsets = true;
break;
case '|': /* Locking Shift 3, right */
gr = 3;
usedcharsets = true;
break;
case 'Y': /* vt52 cursor address mode , next chars are x,y */
term_state = TSTATE_VT52Y;
break;
case '_':
term_state = TSTATE_TITLE;
break;
case '\\':
// TODO save title
term_state = TSTATE_DATA;
break;
default:
debug("ESC unknown letter: " + c + " (" + ((int) c) + ")");
break;
}
break;
case TSTATE_VT52X:
C = c - 37;
if (C < 0)
C = 0;
else if (C >= width)
C = width - 1;
term_state = TSTATE_VT52Y;
break;
case TSTATE_VT52Y:
R = c - 37;
if (R < 0)
R = 0;
else if (R >= height)
R = height - 1;
term_state = TSTATE_DATA;
break;
case TSTATE_SETG0:
if (c != '0' && c != 'A' && c != 'B' && c != '<')
debug("ESC ( " + c + ": G0 char set? (" + ((int) c) + ")");
else {
if (debug > 2) debug("ESC ( : G0 char set (" + c + " " + ((int) c) + ")");
gx[0] = c;
}
term_state = TSTATE_DATA;
break;
case TSTATE_SETG1:
if (c != '0' && c != 'A' && c != 'B' && c != '<') {
debug("ESC ) " + c + " (" + ((int) c) + ") :G1 char set?");
} else {
if (debug > 2) debug("ESC ) :G1 char set (" + c + " " + ((int) c) + ")");
gx[1] = c;
}
term_state = TSTATE_DATA;
break;
case TSTATE_SETG2:
if (c != '0' && c != 'A' && c != 'B' && c != '<')
debug("ESC*:G2 char set? (" + ((int) c) + ")");
else {
if (debug > 2) debug("ESC*:G2 char set (" + c + " " + ((int) c) + ")");
gx[2] = c;
}
term_state = TSTATE_DATA;
break;
case TSTATE_SETG3:
if (c != '0' && c != 'A' && c != 'B' && c != '<')
debug("ESC+:G3 char set? (" + ((int) c) + ")");
else {
if (debug > 2) debug("ESC+:G3 char set (" + c + " " + ((int) c) + ")");
gx[3] = c;
}
term_state = TSTATE_DATA;
break;
case TSTATE_ESCSQUARE:
switch (c) {
case '8':
for (int i = 0; i < columns; i++)
for (int j = 0; j < rows; j++)
putChar(i, j, 'E', 0);
break;
default:
debug("ESC # " + c + " not supported.");
break;
}
term_state = TSTATE_DATA;
break;
case TSTATE_DCS:
if (c == '\\' && dcs.charAt(dcs.length() - 1) == ESC) {
handle_dcs(dcs);
term_state = TSTATE_DATA;
break;
}
dcs = dcs + c;
break;
case TSTATE_DCEQ:
term_state = TSTATE_DATA;
switch (c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
DCEvars[DCEvar] = DCEvars[DCEvar] * 10 + (c) - 48;
term_state = TSTATE_DCEQ;
break;
case ';':
DCEvar++;
DCEvars[DCEvar] = 0;
term_state = TSTATE_DCEQ;
break;
case 's': // XTERM_SAVE missing!
if (true || debug > 1)
debug("ESC [ ? " + DCEvars[0] + " s unimplemented!");
break;
case 'r': // XTERM_RESTORE
if (true || debug > 1)
debug("ESC [ ? " + DCEvars[0] + " r");
/* DEC Mode reset */
for (int i = 0; i <= DCEvar; i++) {
switch (DCEvars[i]) {
case 3: /* 80 columns*/
setScreenSize(80, height, true);
break;
case 4: /* scrolling mode, smooth */
break;
case 5: /* light background */
break;
case 6: /* DECOM (Origin Mode) move inside margins. */
moveoutsidemargins = true;
break;
case 7: /* DECAWM: Autowrap Mode */
wraparound = false;
break;
case 12:/* local echo off */
break;
case 9: /* X10 mouse */
case 1000: /* xterm style mouse report on */
case 1001:
case 1002:
case 1003:
mouserpt = DCEvars[i];
break;
default:
debug("ESC [ ? " + DCEvars[0] + " r, unimplemented!");
}
}
break;
case 'h': // DECSET
if (debug > 0)
debug("ESC [ ? " + DCEvars[0] + " h");
/* DEC Mode set */
for (int i = 0; i <= DCEvar; i++) {
switch (DCEvars[i]) {
case 1: /* Application cursor keys */
KeyUp[0] = "\u001bOA";
KeyDown[0] = "\u001bOB";
KeyRight[0] = "\u001bOC";
KeyLeft[0] = "\u001bOD";
break;
case 2: /* DECANM */
vt52mode = false;
break;
case 3: /* 132 columns*/
setScreenSize(132, height, true);
break;
case 6: /* DECOM: move inside margins. */
moveoutsidemargins = false;
break;
case 7: /* DECAWM: Autowrap Mode */
wraparound = true;
break;
case 25: /* turn cursor on */
showCursor(true);
break;
case 9: /* X10 mouse */
case 1000: /* xterm style mouse report on */
case 1001:
case 1002:
case 1003:
mouserpt = DCEvars[i];
break;
/* unimplemented stuff, fall through */
/* 4 - scrolling mode, smooth */
/* 5 - light background */
/* 12 - local echo off */
/* 18 - DECPFF - Printer Form Feed Mode -> On */
/* 19 - DECPEX - Printer Extent Mode -> Screen */
default:
debug("ESC [ ? " + DCEvars[0] + " h, unsupported.");
break;
}
}
break;
case 'i': // DEC Printer Control, autoprint, echo screenchars to printer
// This is different to CSI i!
// Also: "Autoprint prints a final display line only when the
// cursor is moved off the line by an autowrap or LF, FF, or
// VT (otherwise do not print the line)."
switch (DCEvars[0]) {
case 1:
if (debug > 1)
debug("CSI ? 1 i : Print line containing cursor");
break;
case 4:
if (debug > 1)
debug("CSI ? 4 i : Start passthrough printing");
break;
case 5:
if (debug > 1)
debug("CSI ? 4 i : Stop passthrough printing");
break;
}
break;
case 'l': //DECRST
/* DEC Mode reset */
if (debug > 0)
debug("ESC [ ? " + DCEvars[0] + " l");
for (int i = 0; i <= DCEvar; i++) {
switch (DCEvars[i]) {
case 1: /* Application cursor keys */
KeyUp[0] = "\u001b[A";
KeyDown[0] = "\u001b[B";
KeyRight[0] = "\u001b[C";
KeyLeft[0] = "\u001b[D";
break;
case 2: /* DECANM */
vt52mode = true;
break;
case 3: /* 80 columns*/
setScreenSize(80, height, true);
break;
case 6: /* DECOM: move outside margins. */
moveoutsidemargins = true;
break;
case 7: /* DECAWM: Autowrap Mode OFF */
wraparound = false;
break;
case 25: /* turn cursor off */
showCursor(false);
break;
/* Unimplemented stuff: */
/* 4 - scrolling mode, jump */
/* 5 - dark background */
/* 7 - DECAWM - no wrap around mode */
/* 12 - local echo on */
/* 18 - DECPFF - Printer Form Feed Mode -> Off*/
/* 19 - DECPEX - Printer Extent Mode -> Scrolling Region */
case 9: /* X10 mouse */
case 1000: /* xterm style mouse report OFF */
case 1001:
case 1002:
case 1003:
mouserpt = 0;
break;
default:
debug("ESC [ ? " + DCEvars[0] + " l, unsupported.");
break;
}
}
break;
case 'n':
if (debug > 0)
debug("ESC [ ? " + DCEvars[0] + " n");
switch (DCEvars[0]) {
case 15:
/* printer? no printer. */
write((ESC) + "[?13n", false);
debug("ESC[5n");
break;
default:
debug("ESC [ ? " + DCEvars[0] + " n, unsupported.");
break;
}
break;
default:
debug("ESC [ ? " + DCEvars[0] + " " + c + ", unsupported.");
break;
}
break;
case TSTATE_CSI_EX:
term_state = TSTATE_DATA;
switch (c) {
case ESC:
term_state = TSTATE_ESC;
break;
default:
debug("Unknown character ESC[! character is " + (int) c);
break;
}
break;
case TSTATE_CSI_TICKS:
term_state = TSTATE_DATA;
switch (c) {
case 'p':
debug("Conformance level: " + DCEvars[0] + " (unsupported)," + DCEvars[1]);
if (DCEvars[0] == 61) {
output8bit = false;
break;
}
if (DCEvars[1] == 1) {
output8bit = false;
} else {
output8bit = true; /* 0 or 2 */
}
break;
default:
debug("Unknown ESC [... \"" + c);
break;
}
break;
case TSTATE_CSI_EQUAL:
term_state = TSTATE_DATA;
switch (c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
DCEvars[DCEvar] = DCEvars[DCEvar] * 10 + (c) - 48;
term_state = TSTATE_CSI_EQUAL;
break;
case ';':
DCEvar++;
DCEvars[DCEvar] = 0;
term_state = TSTATE_CSI_EQUAL;
break;
case 'F': /* SCO ANSI foreground */
{
int newcolor;
debug("ESC [ = "+DCEvars[0]+" F");
attributes &= ~COLOR_FG;
newcolor = ((DCEvars[0] & 1) << 2) |
(DCEvars[0] & 2) |
((DCEvars[0] & 4) >> 2) ;
attributes |= (newcolor+1) << COLOR_FG_SHIFT;
break;
}
case 'G': /* SCO ANSI background */
{
int newcolor;
debug("ESC [ = "+DCEvars[0]+" G");
attributes &= ~COLOR_BG;
newcolor = ((DCEvars[0] & 1) << 2) |
(DCEvars[0] & 2) |
((DCEvars[0] & 4) >> 2) ;
attributes |= (newcolor+1) << COLOR_BG_SHIFT;
break;
}
default:
debugStr.append("Unknown ESC [ = ");
for (int i=0;i<=DCEvar;i++) {
debugStr.append(DCEvars[i])
.append(',');
}
debugStr.append(c);
debug(debugStr.toString());
debugStr.setLength(0);
break;
}
break;
case TSTATE_CSI_DOLLAR:
term_state = TSTATE_DATA;
switch (c) {
case '}':
debug("Active Status Display now " + DCEvars[0]);
statusmode = DCEvars[0];
break;
/* bad documentation?
case '-':
debug("Set Status Display now "+DCEvars[0]);
break;
*/
case '~':
debug("Status Line mode now " + DCEvars[0]);
break;
default:
debug("UNKNOWN Status Display code " + c + ", with Pn=" + DCEvars[0]);
break;
}
break;
case TSTATE_CSI:
term_state = TSTATE_DATA;
switch (c) {
case '"':
term_state = TSTATE_CSI_TICKS;
break;
case '$':
term_state = TSTATE_CSI_DOLLAR;
break;
case '=':
term_state = TSTATE_CSI_EQUAL;
break;
case '!':
term_state = TSTATE_CSI_EX;
break;
case '?':
DCEvar = 0;
DCEvars[0] = 0;
term_state = TSTATE_DCEQ;
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
DCEvars[DCEvar] = DCEvars[DCEvar] * 10 + (c) - 48;
term_state = TSTATE_CSI;
break;
case ';':
DCEvar++;
DCEvars[DCEvar] = 0;
term_state = TSTATE_CSI;
break;
case 'c':/* send primary device attributes */
/* send (ESC[?61c) */
String subcode = "";
if (terminalID.equals("vt320")) subcode = "63;";
if (terminalID.equals("vt220")) subcode = "62;";
if (terminalID.equals("vt100")) subcode = "61;";
write((ESC) + "[?" + subcode + "1;2c", false);
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " c");
break;
case 'q':
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " q");
break;
case 'g':
/* used for tabsets */
switch (DCEvars[0]) {
case 3:/* clear them */
Tabs = new byte[width];
break;
case 0:
Tabs[C] = 0;
break;
}
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " g");
break;
case 'h':
switch (DCEvars[0]) {
case 4:
insertmode = 1;
break;
case 20:
debug("Setting CRLF to TRUE");
sendcrlf = true;
break;
default:
debug("unsupported: ESC [ " + DCEvars[0] + " h");
break;
}
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " h");
break;
case 'i': // Printer Controller mode.
// "Transparent printing sends all output, except the CSI 4 i
// termination string, to the printer and not the screen,
// uses an 8-bit channel if no parity so NUL and DEL will be
// seen by the printer and by the termination recognizer code,
// and all translation and character set selections are
// bypassed."
switch (DCEvars[0]) {
case 0:
if (debug > 1)
debug("CSI 0 i: Print Screen, not implemented.");
break;
case 4:
if (debug > 1)
debug("CSI 4 i: Enable Transparent Printing, not implemented.");
break;
case 5:
if (debug > 1)
debug("CSI 4/5 i: Disable Transparent Printing, not implemented.");
break;
default:
debug("ESC [ " + DCEvars[0] + " i, unimplemented!");
}
break;
case 'l':
switch (DCEvars[0]) {
case 4:
insertmode = 0;
break;
case 20:
debug("Setting CRLF to FALSE");
sendcrlf = false;
break;
default:
debug("ESC [ " + DCEvars[0] + " l, unimplemented!");
break;
}
break;
case 'A': // CUU
{
int limit;
/* FIXME: xterm only cares about 0 and topmargin */
if (R >= getTopMargin()) {
limit = getTopMargin();
} else
limit = 0;
if (DCEvars[0] == 0)
R--;
else
R -= DCEvars[0];
if (R < limit)
R = limit;
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " A");
break;
}
case 'B': // CUD
/* cursor down n (1) times */
{
int limit;
if (R <= getBottomMargin()) {
limit = getBottomMargin();
} else
limit = rows - 1;
if (DCEvars[0] == 0)
R++;
else
R += DCEvars[0];
if (R > limit)
R = limit;
else {
if (debug > 2) debug("Not limited.");
}
if (debug > 2) debug("to: " + R);
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " B (at C=" + C + ")");
break;
}
case 'C':
if (DCEvars[0] == 0)
DCEvars[0] = 1;
while (DCEvars[0]-- > 0) {
C++;
}
if (C >= columns)
C = columns - 1;
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " C");
break;
case 'd': // CVA
R = DCEvars[0];
if (R < 0)
R = 0;
else if (R >= height)
R = height - 1;
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " d");
break;
case 'D':
if (DCEvars[0] == 0)
DCEvars[0] = 1;
while (DCEvars[0]-- > 0) {
C--;
}
if (C < 0) C = 0;
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " D");
break;
case 'r': // DECSTBM
if (DCEvar > 0) // Ray: Any argument is optional
{
R = DCEvars[1] - 1;
if (R < 0)
R = rows - 1;
else if (R >= rows) {
R = rows - 1;
}
} else
R = rows - 1;
int bot = R;
if (R >= DCEvars[0]) {
R = DCEvars[0] - 1;
if (R < 0)
R = 0;
}
setMargins(R, bot);
_SetCursor(0, 0);
if (debug > 1)
debug("ESC [" + DCEvars[0] + " ; " + DCEvars[1] + " r");
break;
case 'G': /* CUP / cursor absolute column */
C = DCEvars[0];
if (C < 0)
C = 0;
else if (C >= width)
C = width - 1;
if (debug > 1) debug("ESC [ " + DCEvars[0] + " G");
break;
case 'H': /* CUP / cursor position */
/* gets 2 arguments */
_SetCursor(DCEvars[0] - 1, DCEvars[1] - 1);
if (debug > 2) {
debug("ESC [ " + DCEvars[0] + ";" + DCEvars[1] + " H, moveoutsidemargins " + moveoutsidemargins);
debug(" -> R now " + R + ", C now " + C);
}
break;
case 'f': /* move cursor 2 */
/* gets 2 arguments */
R = DCEvars[0] - 1;
C = DCEvars[1] - 1;
if (C < 0)
C = 0;
else if (C >= width)
C = width - 1;
if (R < 0)
R = 0;
else if (R >= height)
R = height - 1;
if (debug > 2)
debug("ESC [ " + DCEvars[0] + ";" + DCEvars[1] + " f");
break;
case 'S': /* ind aka 'scroll forward' */
if (DCEvars[0] == 0)
insertLine(rows - 1, SCROLL_UP);
else
insertLine(rows - 1, DCEvars[0], SCROLL_UP);
break;
case 'L':
/* insert n lines */
if (DCEvars[0] == 0)
insertLine(R, SCROLL_DOWN);
else
insertLine(R, DCEvars[0], SCROLL_DOWN);
if (debug > 1)
debug("ESC [ " + DCEvars[0] + "" + (c) + " (at R " + R + ")");
break;
case 'T': /* 'ri' aka scroll backward */
if (DCEvars[0] == 0)
insertLine(0, SCROLL_DOWN);
else
insertLine(0, DCEvars[0], SCROLL_DOWN);
break;
case 'M':
if (debug > 1)
debug("ESC [ " + DCEvars[0] + "" + (c) + " at R=" + R);
if (DCEvars[0] == 0)
deleteLine(R);
else
for (int i = 0; i < DCEvars[0]; i++)
deleteLine(R);
break;
case 'K':
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " K");
/* clear in line */
switch (DCEvars[0]) {
case 6: /* 97801 uses ESC[6K for delete to end of line */
case 0:/*clear to right*/
if (C < columns - 1)
deleteArea(C, R, columns - C, 1, attributes);
break;
case 1:/*clear to the left, including this */
if (C > 0)
deleteArea(0, R, C + 1, 1, attributes);
break;
case 2:/*clear whole line */
deleteArea(0, R, columns, 1, attributes);
break;
}
break;
case 'J':
/* clear below current line */
switch (DCEvars[0]) {
case 0:
if (R < rows - 1)
deleteArea(0, R + 1, columns, rows - R - 1, attributes);
if (C < columns - 1)
deleteArea(C, R, columns - C, 1, attributes);
break;
case 1:
if (R > 0)
deleteArea(0, 0, columns, R, attributes);
if (C > 0)
deleteArea(0, R, C + 1, 1, attributes);// include up to and including current
break;
case 2:
deleteArea(0, 0, columns, rows, attributes);
break;
}
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " J");
break;
case '@':
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " @");
for (int i = 0; i < DCEvars[0]; i++)
insertChar(C, R, ' ', attributes);
break;
case 'X':
{
int toerase = DCEvars[0];
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " X, C=" + C + ",R=" + R);
if (toerase == 0)
toerase = 1;
if (toerase + C > columns)
toerase = columns - C;
deleteArea(C, R, toerase, 1, attributes);
// does not change cursor position
break;
}
case 'P':
if (debug > 1)
debug("ESC [ " + DCEvars[0] + " P, C=" + C + ",R=" + R);
if (DCEvars[0] == 0) DCEvars[0] = 1;
for (int i = 0; i < DCEvars[0]; i++)
deleteChar(C, R);
break;
case 'n':
switch (DCEvars[0]) {
case 5: /* malfunction? No malfunction. */
writeSpecial((ESC) + "[0n");
if (debug > 1)
debug("ESC[5n");
break;
case 6:
// DO NOT offset R and C by 1! (checked against /usr/X11R6/bin/resize
// FIXME check again.
// FIXME: but vttest thinks different???
writeSpecial((ESC) + "[" + R + ";" + C + "R");
if (debug > 1)
debug("ESC[6n");
break;
default:
if (debug > 0)
debug("ESC [ " + DCEvars[0] + " n??");
break;
}
break;
case 's': /* DECSC - save cursor */
Sc = C;
Sr = R;
Sa = attributes;
if (debug > 3)
debug("ESC[s");
break;
case 'u': /* DECRC - restore cursor */
C = Sc;
R = Sr;
attributes = Sa;
if (debug > 3)
debug("ESC[u");
break;
case 'm': /* attributes as color, bold , blink,*/
if (debug > 3)
debug("ESC [ ");
if (DCEvar == 0 && DCEvars[0] == 0)
attributes = 0;
for (int i = 0; i <= DCEvar; i++) {
switch (DCEvars[i]) {
case 0:
if (DCEvar > 0) {
if (terminalID.equals("scoansi")) {
attributes &= COLOR; /* Keeps color. Strange but true. */
} else {
attributes = 0;
}
}
break;
case 1:
attributes |= BOLD;
attributes &= ~LOW;
break;
case 2:
/* SCO color hack mode */
if (terminalID.equals("scoansi") && ((DCEvar - i) >= 2)) {
int ncolor;
attributes &= ~(COLOR | BOLD);
ncolor = DCEvars[i + 1];
if ((ncolor & 8) == 8)
attributes |= BOLD;
ncolor = ((ncolor & 1) << 2) | (ncolor & 2) | ((ncolor & 4) >> 2);
attributes |= ((ncolor) + 1) << COLOR_FG_SHIFT;
ncolor = DCEvars[i + 2];
ncolor = ((ncolor & 1) << 2) | (ncolor & 2) | ((ncolor & 4) >> 2);
attributes |= ((ncolor) + 1) << COLOR_BG_SHIFT;
i += 2;
} else {
attributes |= LOW;
}
break;
case 3: /* italics */
attributes |= INVERT;
break;
case 4:
attributes |= UNDERLINE;
break;
case 7:
attributes |= INVERT;
break;
case 8:
attributes |= INVISIBLE;
break;
case 5: /* blink on */
break;
/* 10 - ANSI X3.64-1979, select primary font, don't display control
* chars, don't set bit 8 on output */
case 10:
gl = 0;
usedcharsets = true;
break;
/* 11 - ANSI X3.64-1979, select second alt. font, display control
* chars, set bit 8 on output */
case 11: /* SMACS , as */
case 12:
gl = 1;
usedcharsets = true;
break;
case 21: /* normal intensity */
attributes &= ~(LOW | BOLD);
break;
case 23: /* italics off */
attributes &= ~INVERT;
break;
case 25: /* blinking off */
break;
case 27:
attributes &= ~INVERT;
break;
case 28:
attributes &= ~INVISIBLE;
break;
case 24:
attributes &= ~UNDERLINE;
break;
case 22:
attributes &= ~BOLD;
break;
case 30:
case 31:
case 32:
case 33:
case 34:
case 35:
case 36:
case 37:
attributes &= ~COLOR_FG;
attributes |= ((DCEvars[i] - 30) + 1)<< COLOR_FG_SHIFT;
break;
case 38:
if (DCEvars[i+1] == 5) {
attributes &= ~COLOR_FG;
attributes |= ((DCEvars[i + 2]) + 1) << COLOR_FG_SHIFT;
i += 2;
}
break;
case 39:
attributes &= ~COLOR_FG;
break;
case 40:
case 41:
case 42:
case 43:
case 44:
case 45:
case 46:
case 47:
attributes &= ~COLOR_BG;
attributes |= ((DCEvars[i] - 40) + 1) << COLOR_BG_SHIFT;
break;
case 48:
if (DCEvars[i+1] == 5) {
attributes &= ~COLOR_BG;
attributes |= (DCEvars[i + 2] + 1) << COLOR_BG_SHIFT;
i += 2;
}
break;
case 49:
attributes &= ~COLOR_BG;
break;
case 90:
case 91:
case 92:
case 93:
case 94:
case 95:
case 96:
case 97:
attributes &= ~COLOR_FG;
attributes |= ((DCEvars[i] - 82) + 1) << COLOR_FG_SHIFT;
break;
case 100:
case 101:
case 102:
case 103:
case 104:
case 105:
case 106:
case 107:
attributes &= ~COLOR_BG;
attributes |= ((DCEvars[i] - 92) + 1) << COLOR_BG_SHIFT;
break;
default:
debugStr.append("ESC [ ")
.append(DCEvars[i])
.append(" m unknown...");
debug(debugStr.toString());
debugStr.setLength(0);
break;
}
if (debug > 3) {
debugStr.append(DCEvars[i])
.append(';');
debug(debugStr.toString());
debugStr.setLength(0);
}
}
if (debug > 3) {
debugStr.append(" (attributes = ")
.append(attributes)
.append(")m");
debug(debugStr.toString());
debugStr.setLength(0);
}
break;
default:
debugStr.append("ESC [ unknown letter: ")
.append(c)
.append(" (")
.append((int)c)
.append(')');
debug(debugStr.toString());
debugStr.setLength(0);
break;
}
break;
case TSTATE_TITLE:
switch (c) {
case ESC:
term_state = TSTATE_ESC;
break;
default:
// TODO save title
break;
}
break;
default:
term_state = TSTATE_DATA;
break;
}
setCursorPosition(C, R);
}
/* hard reset the terminal */
public void reset() {
gx[0] = 'B';
gx[1] = 'B';
gx[2] = 'B';
gx[3] = 'B';
gl = 0; // default GL to G0
gr = 2; // default GR to G2
onegl = -1; // Single shift override
/* reset tabs */
int nw = width;
if (nw < 132) nw = 132;
Tabs = new byte[nw];
for (int i = 0; i < nw; i += 8) {
Tabs[i] = 1;
}
deleteArea(0, 0, width, height, attributes);
setMargins(0, height);
C = R = 0;
_SetCursor(0, 0);
if (display != null)
display.resetColors();
showCursor(true);
/*FIXME:*/
term_state = TSTATE_DATA;
}
}
| Java |
/*
* 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 de.mud.terminal;
/**
* @author Kenny Root
* This data was taken from xterm's precompose.c
*/
public class Precomposer {
public final static char precompositions[][] = {
{ 0x226E, 0x003C, 0x0338},
{ 0x2260, 0x003D, 0x0338},
{ 0x226F, 0x003E, 0x0338},
{ 0x00C0, 0x0041, 0x0300},
{ 0x00C1, 0x0041, 0x0301},
{ 0x00C2, 0x0041, 0x0302},
{ 0x00C3, 0x0041, 0x0303},
{ 0x0100, 0x0041, 0x0304},
{ 0x0102, 0x0041, 0x0306},
{ 0x0226, 0x0041, 0x0307},
{ 0x00C4, 0x0041, 0x0308},
{ 0x1EA2, 0x0041, 0x0309},
{ 0x00C5, 0x0041, 0x030A},
{ 0x01CD, 0x0041, 0x030C},
{ 0x0200, 0x0041, 0x030F},
{ 0x0202, 0x0041, 0x0311},
{ 0x1EA0, 0x0041, 0x0323},
{ 0x1E00, 0x0041, 0x0325},
{ 0x0104, 0x0041, 0x0328},
{ 0x1E02, 0x0042, 0x0307},
{ 0x1E04, 0x0042, 0x0323},
{ 0x1E06, 0x0042, 0x0331},
{ 0x0106, 0x0043, 0x0301},
{ 0x0108, 0x0043, 0x0302},
{ 0x010A, 0x0043, 0x0307},
{ 0x010C, 0x0043, 0x030C},
{ 0x00C7, 0x0043, 0x0327},
{ 0x1E0A, 0x0044, 0x0307},
{ 0x010E, 0x0044, 0x030C},
{ 0x1E0C, 0x0044, 0x0323},
{ 0x1E10, 0x0044, 0x0327},
{ 0x1E12, 0x0044, 0x032D},
{ 0x1E0E, 0x0044, 0x0331},
{ 0x00C8, 0x0045, 0x0300},
{ 0x00C9, 0x0045, 0x0301},
{ 0x00CA, 0x0045, 0x0302},
{ 0x1EBC, 0x0045, 0x0303},
{ 0x0112, 0x0045, 0x0304},
{ 0x0114, 0x0045, 0x0306},
{ 0x0116, 0x0045, 0x0307},
{ 0x00CB, 0x0045, 0x0308},
{ 0x1EBA, 0x0045, 0x0309},
{ 0x011A, 0x0045, 0x030C},
{ 0x0204, 0x0045, 0x030F},
{ 0x0206, 0x0045, 0x0311},
{ 0x1EB8, 0x0045, 0x0323},
{ 0x0228, 0x0045, 0x0327},
{ 0x0118, 0x0045, 0x0328},
{ 0x1E18, 0x0045, 0x032D},
{ 0x1E1A, 0x0045, 0x0330},
{ 0x1E1E, 0x0046, 0x0307},
{ 0x01F4, 0x0047, 0x0301},
{ 0x011C, 0x0047, 0x0302},
{ 0x1E20, 0x0047, 0x0304},
{ 0x011E, 0x0047, 0x0306},
{ 0x0120, 0x0047, 0x0307},
{ 0x01E6, 0x0047, 0x030C},
{ 0x0122, 0x0047, 0x0327},
{ 0x0124, 0x0048, 0x0302},
{ 0x1E22, 0x0048, 0x0307},
{ 0x1E26, 0x0048, 0x0308},
{ 0x021E, 0x0048, 0x030C},
{ 0x1E24, 0x0048, 0x0323},
{ 0x1E28, 0x0048, 0x0327},
{ 0x1E2A, 0x0048, 0x032E},
{ 0x00CC, 0x0049, 0x0300},
{ 0x00CD, 0x0049, 0x0301},
{ 0x00CE, 0x0049, 0x0302},
{ 0x0128, 0x0049, 0x0303},
{ 0x012A, 0x0049, 0x0304},
{ 0x012C, 0x0049, 0x0306},
{ 0x0130, 0x0049, 0x0307},
{ 0x00CF, 0x0049, 0x0308},
{ 0x1EC8, 0x0049, 0x0309},
{ 0x01CF, 0x0049, 0x030C},
{ 0x0208, 0x0049, 0x030F},
{ 0x020A, 0x0049, 0x0311},
{ 0x1ECA, 0x0049, 0x0323},
{ 0x012E, 0x0049, 0x0328},
{ 0x1E2C, 0x0049, 0x0330},
{ 0x0134, 0x004A, 0x0302},
{ 0x1E30, 0x004B, 0x0301},
{ 0x01E8, 0x004B, 0x030C},
{ 0x1E32, 0x004B, 0x0323},
{ 0x0136, 0x004B, 0x0327},
{ 0x1E34, 0x004B, 0x0331},
{ 0x0139, 0x004C, 0x0301},
{ 0x013D, 0x004C, 0x030C},
{ 0x1E36, 0x004C, 0x0323},
{ 0x013B, 0x004C, 0x0327},
{ 0x1E3C, 0x004C, 0x032D},
{ 0x1E3A, 0x004C, 0x0331},
{ 0x1E3E, 0x004D, 0x0301},
{ 0x1E40, 0x004D, 0x0307},
{ 0x1E42, 0x004D, 0x0323},
{ 0x01F8, 0x004E, 0x0300},
{ 0x0143, 0x004E, 0x0301},
{ 0x00D1, 0x004E, 0x0303},
{ 0x1E44, 0x004E, 0x0307},
{ 0x0147, 0x004E, 0x030C},
{ 0x1E46, 0x004E, 0x0323},
{ 0x0145, 0x004E, 0x0327},
{ 0x1E4A, 0x004E, 0x032D},
{ 0x1E48, 0x004E, 0x0331},
{ 0x00D2, 0x004F, 0x0300},
{ 0x00D3, 0x004F, 0x0301},
{ 0x00D4, 0x004F, 0x0302},
{ 0x00D5, 0x004F, 0x0303},
{ 0x014C, 0x004F, 0x0304},
{ 0x014E, 0x004F, 0x0306},
{ 0x022E, 0x004F, 0x0307},
{ 0x00D6, 0x004F, 0x0308},
{ 0x1ECE, 0x004F, 0x0309},
{ 0x0150, 0x004F, 0x030B},
{ 0x01D1, 0x004F, 0x030C},
{ 0x020C, 0x004F, 0x030F},
{ 0x020E, 0x004F, 0x0311},
{ 0x01A0, 0x004F, 0x031B},
{ 0x1ECC, 0x004F, 0x0323},
{ 0x01EA, 0x004F, 0x0328},
{ 0x1E54, 0x0050, 0x0301},
{ 0x1E56, 0x0050, 0x0307},
{ 0x0154, 0x0052, 0x0301},
{ 0x1E58, 0x0052, 0x0307},
{ 0x0158, 0x0052, 0x030C},
{ 0x0210, 0x0052, 0x030F},
{ 0x0212, 0x0052, 0x0311},
{ 0x1E5A, 0x0052, 0x0323},
{ 0x0156, 0x0052, 0x0327},
{ 0x1E5E, 0x0052, 0x0331},
{ 0x015A, 0x0053, 0x0301},
{ 0x015C, 0x0053, 0x0302},
{ 0x1E60, 0x0053, 0x0307},
{ 0x0160, 0x0053, 0x030C},
{ 0x1E62, 0x0053, 0x0323},
{ 0x0218, 0x0053, 0x0326},
{ 0x015E, 0x0053, 0x0327},
{ 0x1E6A, 0x0054, 0x0307},
{ 0x0164, 0x0054, 0x030C},
{ 0x1E6C, 0x0054, 0x0323},
{ 0x021A, 0x0054, 0x0326},
{ 0x0162, 0x0054, 0x0327},
{ 0x1E70, 0x0054, 0x032D},
{ 0x1E6E, 0x0054, 0x0331},
{ 0x00D9, 0x0055, 0x0300},
{ 0x00DA, 0x0055, 0x0301},
{ 0x00DB, 0x0055, 0x0302},
{ 0x0168, 0x0055, 0x0303},
{ 0x016A, 0x0055, 0x0304},
{ 0x016C, 0x0055, 0x0306},
{ 0x00DC, 0x0055, 0x0308},
{ 0x1EE6, 0x0055, 0x0309},
{ 0x016E, 0x0055, 0x030A},
{ 0x0170, 0x0055, 0x030B},
{ 0x01D3, 0x0055, 0x030C},
{ 0x0214, 0x0055, 0x030F},
{ 0x0216, 0x0055, 0x0311},
{ 0x01AF, 0x0055, 0x031B},
{ 0x1EE4, 0x0055, 0x0323},
{ 0x1E72, 0x0055, 0x0324},
{ 0x0172, 0x0055, 0x0328},
{ 0x1E76, 0x0055, 0x032D},
{ 0x1E74, 0x0055, 0x0330},
{ 0x1E7C, 0x0056, 0x0303},
{ 0x1E7E, 0x0056, 0x0323},
{ 0x1E80, 0x0057, 0x0300},
{ 0x1E82, 0x0057, 0x0301},
{ 0x0174, 0x0057, 0x0302},
{ 0x1E86, 0x0057, 0x0307},
{ 0x1E84, 0x0057, 0x0308},
{ 0x1E88, 0x0057, 0x0323},
{ 0x1E8A, 0x0058, 0x0307},
{ 0x1E8C, 0x0058, 0x0308},
{ 0x1EF2, 0x0059, 0x0300},
{ 0x00DD, 0x0059, 0x0301},
{ 0x0176, 0x0059, 0x0302},
{ 0x1EF8, 0x0059, 0x0303},
{ 0x0232, 0x0059, 0x0304},
{ 0x1E8E, 0x0059, 0x0307},
{ 0x0178, 0x0059, 0x0308},
{ 0x1EF6, 0x0059, 0x0309},
{ 0x1EF4, 0x0059, 0x0323},
{ 0x0179, 0x005A, 0x0301},
{ 0x1E90, 0x005A, 0x0302},
{ 0x017B, 0x005A, 0x0307},
{ 0x017D, 0x005A, 0x030C},
{ 0x1E92, 0x005A, 0x0323},
{ 0x1E94, 0x005A, 0x0331},
{ 0x00E0, 0x0061, 0x0300},
{ 0x00E1, 0x0061, 0x0301},
{ 0x00E2, 0x0061, 0x0302},
{ 0x00E3, 0x0061, 0x0303},
{ 0x0101, 0x0061, 0x0304},
{ 0x0103, 0x0061, 0x0306},
{ 0x0227, 0x0061, 0x0307},
{ 0x00E4, 0x0061, 0x0308},
{ 0x1EA3, 0x0061, 0x0309},
{ 0x00E5, 0x0061, 0x030A},
{ 0x01CE, 0x0061, 0x030C},
{ 0x0201, 0x0061, 0x030F},
{ 0x0203, 0x0061, 0x0311},
{ 0x1EA1, 0x0061, 0x0323},
{ 0x1E01, 0x0061, 0x0325},
{ 0x0105, 0x0061, 0x0328},
{ 0x1E03, 0x0062, 0x0307},
{ 0x1E05, 0x0062, 0x0323},
{ 0x1E07, 0x0062, 0x0331},
{ 0x0107, 0x0063, 0x0301},
{ 0x0109, 0x0063, 0x0302},
{ 0x010B, 0x0063, 0x0307},
{ 0x010D, 0x0063, 0x030C},
{ 0x00E7, 0x0063, 0x0327},
{ 0x1E0B, 0x0064, 0x0307},
{ 0x010F, 0x0064, 0x030C},
{ 0x1E0D, 0x0064, 0x0323},
{ 0x1E11, 0x0064, 0x0327},
{ 0x1E13, 0x0064, 0x032D},
{ 0x1E0F, 0x0064, 0x0331},
{ 0x00E8, 0x0065, 0x0300},
{ 0x00E9, 0x0065, 0x0301},
{ 0x00EA, 0x0065, 0x0302},
{ 0x1EBD, 0x0065, 0x0303},
{ 0x0113, 0x0065, 0x0304},
{ 0x0115, 0x0065, 0x0306},
{ 0x0117, 0x0065, 0x0307},
{ 0x00EB, 0x0065, 0x0308},
{ 0x1EBB, 0x0065, 0x0309},
{ 0x011B, 0x0065, 0x030C},
{ 0x0205, 0x0065, 0x030F},
{ 0x0207, 0x0065, 0x0311},
{ 0x1EB9, 0x0065, 0x0323},
{ 0x0229, 0x0065, 0x0327},
{ 0x0119, 0x0065, 0x0328},
{ 0x1E19, 0x0065, 0x032D},
{ 0x1E1B, 0x0065, 0x0330},
{ 0x1E1F, 0x0066, 0x0307},
{ 0x01F5, 0x0067, 0x0301},
{ 0x011D, 0x0067, 0x0302},
{ 0x1E21, 0x0067, 0x0304},
{ 0x011F, 0x0067, 0x0306},
{ 0x0121, 0x0067, 0x0307},
{ 0x01E7, 0x0067, 0x030C},
{ 0x0123, 0x0067, 0x0327},
{ 0x0125, 0x0068, 0x0302},
{ 0x1E23, 0x0068, 0x0307},
{ 0x1E27, 0x0068, 0x0308},
{ 0x021F, 0x0068, 0x030C},
{ 0x1E25, 0x0068, 0x0323},
{ 0x1E29, 0x0068, 0x0327},
{ 0x1E2B, 0x0068, 0x032E},
{ 0x1E96, 0x0068, 0x0331},
{ 0x00EC, 0x0069, 0x0300},
{ 0x00ED, 0x0069, 0x0301},
{ 0x00EE, 0x0069, 0x0302},
{ 0x0129, 0x0069, 0x0303},
{ 0x012B, 0x0069, 0x0304},
{ 0x012D, 0x0069, 0x0306},
{ 0x00EF, 0x0069, 0x0308},
{ 0x1EC9, 0x0069, 0x0309},
{ 0x01D0, 0x0069, 0x030C},
{ 0x0209, 0x0069, 0x030F},
{ 0x020B, 0x0069, 0x0311},
{ 0x1ECB, 0x0069, 0x0323},
{ 0x012F, 0x0069, 0x0328},
{ 0x1E2D, 0x0069, 0x0330},
{ 0x0135, 0x006A, 0x0302},
{ 0x01F0, 0x006A, 0x030C},
{ 0x1E31, 0x006B, 0x0301},
{ 0x01E9, 0x006B, 0x030C},
{ 0x1E33, 0x006B, 0x0323},
{ 0x0137, 0x006B, 0x0327},
{ 0x1E35, 0x006B, 0x0331},
{ 0x013A, 0x006C, 0x0301},
{ 0x013E, 0x006C, 0x030C},
{ 0x1E37, 0x006C, 0x0323},
{ 0x013C, 0x006C, 0x0327},
{ 0x1E3D, 0x006C, 0x032D},
{ 0x1E3B, 0x006C, 0x0331},
{ 0x1E3F, 0x006D, 0x0301},
{ 0x1E41, 0x006D, 0x0307},
{ 0x1E43, 0x006D, 0x0323},
{ 0x01F9, 0x006E, 0x0300},
{ 0x0144, 0x006E, 0x0301},
{ 0x00F1, 0x006E, 0x0303},
{ 0x1E45, 0x006E, 0x0307},
{ 0x0148, 0x006E, 0x030C},
{ 0x1E47, 0x006E, 0x0323},
{ 0x0146, 0x006E, 0x0327},
{ 0x1E4B, 0x006E, 0x032D},
{ 0x1E49, 0x006E, 0x0331},
{ 0x00F2, 0x006F, 0x0300},
{ 0x00F3, 0x006F, 0x0301},
{ 0x00F4, 0x006F, 0x0302},
{ 0x00F5, 0x006F, 0x0303},
{ 0x014D, 0x006F, 0x0304},
{ 0x014F, 0x006F, 0x0306},
{ 0x022F, 0x006F, 0x0307},
{ 0x00F6, 0x006F, 0x0308},
{ 0x1ECF, 0x006F, 0x0309},
{ 0x0151, 0x006F, 0x030B},
{ 0x01D2, 0x006F, 0x030C},
{ 0x020D, 0x006F, 0x030F},
{ 0x020F, 0x006F, 0x0311},
{ 0x01A1, 0x006F, 0x031B},
{ 0x1ECD, 0x006F, 0x0323},
{ 0x01EB, 0x006F, 0x0328},
{ 0x1E55, 0x0070, 0x0301},
{ 0x1E57, 0x0070, 0x0307},
{ 0x0155, 0x0072, 0x0301},
{ 0x1E59, 0x0072, 0x0307},
{ 0x0159, 0x0072, 0x030C},
{ 0x0211, 0x0072, 0x030F},
{ 0x0213, 0x0072, 0x0311},
{ 0x1E5B, 0x0072, 0x0323},
{ 0x0157, 0x0072, 0x0327},
{ 0x1E5F, 0x0072, 0x0331},
{ 0x015B, 0x0073, 0x0301},
{ 0x015D, 0x0073, 0x0302},
{ 0x1E61, 0x0073, 0x0307},
{ 0x0161, 0x0073, 0x030C},
{ 0x1E63, 0x0073, 0x0323},
{ 0x0219, 0x0073, 0x0326},
{ 0x015F, 0x0073, 0x0327},
{ 0x1E6B, 0x0074, 0x0307},
{ 0x1E97, 0x0074, 0x0308},
{ 0x0165, 0x0074, 0x030C},
{ 0x1E6D, 0x0074, 0x0323},
{ 0x021B, 0x0074, 0x0326},
{ 0x0163, 0x0074, 0x0327},
{ 0x1E71, 0x0074, 0x032D},
{ 0x1E6F, 0x0074, 0x0331},
{ 0x00F9, 0x0075, 0x0300},
{ 0x00FA, 0x0075, 0x0301},
{ 0x00FB, 0x0075, 0x0302},
{ 0x0169, 0x0075, 0x0303},
{ 0x016B, 0x0075, 0x0304},
{ 0x016D, 0x0075, 0x0306},
{ 0x00FC, 0x0075, 0x0308},
{ 0x1EE7, 0x0075, 0x0309},
{ 0x016F, 0x0075, 0x030A},
{ 0x0171, 0x0075, 0x030B},
{ 0x01D4, 0x0075, 0x030C},
{ 0x0215, 0x0075, 0x030F},
{ 0x0217, 0x0075, 0x0311},
{ 0x01B0, 0x0075, 0x031B},
{ 0x1EE5, 0x0075, 0x0323},
{ 0x1E73, 0x0075, 0x0324},
{ 0x0173, 0x0075, 0x0328},
{ 0x1E77, 0x0075, 0x032D},
{ 0x1E75, 0x0075, 0x0330},
{ 0x1E7D, 0x0076, 0x0303},
{ 0x1E7F, 0x0076, 0x0323},
{ 0x1E81, 0x0077, 0x0300},
{ 0x1E83, 0x0077, 0x0301},
{ 0x0175, 0x0077, 0x0302},
{ 0x1E87, 0x0077, 0x0307},
{ 0x1E85, 0x0077, 0x0308},
{ 0x1E98, 0x0077, 0x030A},
{ 0x1E89, 0x0077, 0x0323},
{ 0x1E8B, 0x0078, 0x0307},
{ 0x1E8D, 0x0078, 0x0308},
{ 0x1EF3, 0x0079, 0x0300},
{ 0x00FD, 0x0079, 0x0301},
{ 0x0177, 0x0079, 0x0302},
{ 0x1EF9, 0x0079, 0x0303},
{ 0x0233, 0x0079, 0x0304},
{ 0x1E8F, 0x0079, 0x0307},
{ 0x00FF, 0x0079, 0x0308},
{ 0x1EF7, 0x0079, 0x0309},
{ 0x1E99, 0x0079, 0x030A},
{ 0x1EF5, 0x0079, 0x0323},
{ 0x017A, 0x007A, 0x0301},
{ 0x1E91, 0x007A, 0x0302},
{ 0x017C, 0x007A, 0x0307},
{ 0x017E, 0x007A, 0x030C},
{ 0x1E93, 0x007A, 0x0323},
{ 0x1E95, 0x007A, 0x0331},
{ 0x1FED, 0x00A8, 0x0300},
{ 0x0385, 0x00A8, 0x0301},
{ 0x1FC1, 0x00A8, 0x0342},
{ 0x1EA6, 0x00C2, 0x0300},
{ 0x1EA4, 0x00C2, 0x0301},
{ 0x1EAA, 0x00C2, 0x0303},
{ 0x1EA8, 0x00C2, 0x0309},
{ 0x01DE, 0x00C4, 0x0304},
{ 0x01FA, 0x00C5, 0x0301},
{ 0x01FC, 0x00C6, 0x0301},
{ 0x01E2, 0x00C6, 0x0304},
{ 0x1E08, 0x00C7, 0x0301},
{ 0x1EC0, 0x00CA, 0x0300},
{ 0x1EBE, 0x00CA, 0x0301},
{ 0x1EC4, 0x00CA, 0x0303},
{ 0x1EC2, 0x00CA, 0x0309},
{ 0x1E2E, 0x00CF, 0x0301},
{ 0x1ED2, 0x00D4, 0x0300},
{ 0x1ED0, 0x00D4, 0x0301},
{ 0x1ED6, 0x00D4, 0x0303},
{ 0x1ED4, 0x00D4, 0x0309},
{ 0x1E4C, 0x00D5, 0x0301},
{ 0x022C, 0x00D5, 0x0304},
{ 0x1E4E, 0x00D5, 0x0308},
{ 0x022A, 0x00D6, 0x0304},
{ 0x01FE, 0x00D8, 0x0301},
{ 0x01DB, 0x00DC, 0x0300},
{ 0x01D7, 0x00DC, 0x0301},
{ 0x01D5, 0x00DC, 0x0304},
{ 0x01D9, 0x00DC, 0x030C},
{ 0x1EA7, 0x00E2, 0x0300},
{ 0x1EA5, 0x00E2, 0x0301},
{ 0x1EAB, 0x00E2, 0x0303},
{ 0x1EA9, 0x00E2, 0x0309},
{ 0x01DF, 0x00E4, 0x0304},
{ 0x01FB, 0x00E5, 0x0301},
{ 0x01FD, 0x00E6, 0x0301},
{ 0x01E3, 0x00E6, 0x0304},
{ 0x1E09, 0x00E7, 0x0301},
{ 0x1EC1, 0x00EA, 0x0300},
{ 0x1EBF, 0x00EA, 0x0301},
{ 0x1EC5, 0x00EA, 0x0303},
{ 0x1EC3, 0x00EA, 0x0309},
{ 0x1E2F, 0x00EF, 0x0301},
{ 0x1ED3, 0x00F4, 0x0300},
{ 0x1ED1, 0x00F4, 0x0301},
{ 0x1ED7, 0x00F4, 0x0303},
{ 0x1ED5, 0x00F4, 0x0309},
{ 0x1E4D, 0x00F5, 0x0301},
{ 0x022D, 0x00F5, 0x0304},
{ 0x1E4F, 0x00F5, 0x0308},
{ 0x022B, 0x00F6, 0x0304},
{ 0x01FF, 0x00F8, 0x0301},
{ 0x01DC, 0x00FC, 0x0300},
{ 0x01D8, 0x00FC, 0x0301},
{ 0x01D6, 0x00FC, 0x0304},
{ 0x01DA, 0x00FC, 0x030C},
{ 0x1EB0, 0x0102, 0x0300},
{ 0x1EAE, 0x0102, 0x0301},
{ 0x1EB4, 0x0102, 0x0303},
{ 0x1EB2, 0x0102, 0x0309},
{ 0x1EB1, 0x0103, 0x0300},
{ 0x1EAF, 0x0103, 0x0301},
{ 0x1EB5, 0x0103, 0x0303},
{ 0x1EB3, 0x0103, 0x0309},
{ 0x1E14, 0x0112, 0x0300},
{ 0x1E16, 0x0112, 0x0301},
{ 0x1E15, 0x0113, 0x0300},
{ 0x1E17, 0x0113, 0x0301},
{ 0x1E50, 0x014C, 0x0300},
{ 0x1E52, 0x014C, 0x0301},
{ 0x1E51, 0x014D, 0x0300},
{ 0x1E53, 0x014D, 0x0301},
{ 0x1E64, 0x015A, 0x0307},
{ 0x1E65, 0x015B, 0x0307},
{ 0x1E66, 0x0160, 0x0307},
{ 0x1E67, 0x0161, 0x0307},
{ 0x1E78, 0x0168, 0x0301},
{ 0x1E79, 0x0169, 0x0301},
{ 0x1E7A, 0x016A, 0x0308},
{ 0x1E7B, 0x016B, 0x0308},
{ 0x1E9B, 0x017F, 0x0307},
{ 0x1EDC, 0x01A0, 0x0300},
{ 0x1EDA, 0x01A0, 0x0301},
{ 0x1EE0, 0x01A0, 0x0303},
{ 0x1EDE, 0x01A0, 0x0309},
{ 0x1EE2, 0x01A0, 0x0323},
{ 0x1EDD, 0x01A1, 0x0300},
{ 0x1EDB, 0x01A1, 0x0301},
{ 0x1EE1, 0x01A1, 0x0303},
{ 0x1EDF, 0x01A1, 0x0309},
{ 0x1EE3, 0x01A1, 0x0323},
{ 0x1EEA, 0x01AF, 0x0300},
{ 0x1EE8, 0x01AF, 0x0301},
{ 0x1EEE, 0x01AF, 0x0303},
{ 0x1EEC, 0x01AF, 0x0309},
{ 0x1EF0, 0x01AF, 0x0323},
{ 0x1EEB, 0x01B0, 0x0300},
{ 0x1EE9, 0x01B0, 0x0301},
{ 0x1EEF, 0x01B0, 0x0303},
{ 0x1EED, 0x01B0, 0x0309},
{ 0x1EF1, 0x01B0, 0x0323},
{ 0x01EE, 0x01B7, 0x030C},
{ 0x01EC, 0x01EA, 0x0304},
{ 0x01ED, 0x01EB, 0x0304},
{ 0x01E0, 0x0226, 0x0304},
{ 0x01E1, 0x0227, 0x0304},
{ 0x1E1C, 0x0228, 0x0306},
{ 0x1E1D, 0x0229, 0x0306},
{ 0x0230, 0x022E, 0x0304},
{ 0x0231, 0x022F, 0x0304},
{ 0x01EF, 0x0292, 0x030C},
{ 0x0344, 0x0308, 0x0301},
{ 0x1FBA, 0x0391, 0x0300},
{ 0x0386, 0x0391, 0x0301},
{ 0x1FB9, 0x0391, 0x0304},
{ 0x1FB8, 0x0391, 0x0306},
{ 0x1F08, 0x0391, 0x0313},
{ 0x1F09, 0x0391, 0x0314},
{ 0x1FBC, 0x0391, 0x0345},
{ 0x1FC8, 0x0395, 0x0300},
{ 0x0388, 0x0395, 0x0301},
{ 0x1F18, 0x0395, 0x0313},
{ 0x1F19, 0x0395, 0x0314},
{ 0x1FCA, 0x0397, 0x0300},
{ 0x0389, 0x0397, 0x0301},
{ 0x1F28, 0x0397, 0x0313},
{ 0x1F29, 0x0397, 0x0314},
{ 0x1FCC, 0x0397, 0x0345},
{ 0x1FDA, 0x0399, 0x0300},
{ 0x038A, 0x0399, 0x0301},
{ 0x1FD9, 0x0399, 0x0304},
{ 0x1FD8, 0x0399, 0x0306},
{ 0x03AA, 0x0399, 0x0308},
{ 0x1F38, 0x0399, 0x0313},
{ 0x1F39, 0x0399, 0x0314},
{ 0x1FF8, 0x039F, 0x0300},
{ 0x038C, 0x039F, 0x0301},
{ 0x1F48, 0x039F, 0x0313},
{ 0x1F49, 0x039F, 0x0314},
{ 0x1FEC, 0x03A1, 0x0314},
{ 0x1FEA, 0x03A5, 0x0300},
{ 0x038E, 0x03A5, 0x0301},
{ 0x1FE9, 0x03A5, 0x0304},
{ 0x1FE8, 0x03A5, 0x0306},
{ 0x03AB, 0x03A5, 0x0308},
{ 0x1F59, 0x03A5, 0x0314},
{ 0x1FFA, 0x03A9, 0x0300},
{ 0x038F, 0x03A9, 0x0301},
{ 0x1F68, 0x03A9, 0x0313},
{ 0x1F69, 0x03A9, 0x0314},
{ 0x1FFC, 0x03A9, 0x0345},
{ 0x1FB4, 0x03AC, 0x0345},
{ 0x1FC4, 0x03AE, 0x0345},
{ 0x1F70, 0x03B1, 0x0300},
{ 0x03AC, 0x03B1, 0x0301},
{ 0x1FB1, 0x03B1, 0x0304},
{ 0x1FB0, 0x03B1, 0x0306},
{ 0x1F00, 0x03B1, 0x0313},
{ 0x1F01, 0x03B1, 0x0314},
{ 0x1FB6, 0x03B1, 0x0342},
{ 0x1FB3, 0x03B1, 0x0345},
{ 0x1F72, 0x03B5, 0x0300},
{ 0x03AD, 0x03B5, 0x0301},
{ 0x1F10, 0x03B5, 0x0313},
{ 0x1F11, 0x03B5, 0x0314},
{ 0x1F74, 0x03B7, 0x0300},
{ 0x03AE, 0x03B7, 0x0301},
{ 0x1F20, 0x03B7, 0x0313},
{ 0x1F21, 0x03B7, 0x0314},
{ 0x1FC6, 0x03B7, 0x0342},
{ 0x1FC3, 0x03B7, 0x0345},
{ 0x1F76, 0x03B9, 0x0300},
{ 0x03AF, 0x03B9, 0x0301},
{ 0x1FD1, 0x03B9, 0x0304},
{ 0x1FD0, 0x03B9, 0x0306},
{ 0x03CA, 0x03B9, 0x0308},
{ 0x1F30, 0x03B9, 0x0313},
{ 0x1F31, 0x03B9, 0x0314},
{ 0x1FD6, 0x03B9, 0x0342},
{ 0x1F78, 0x03BF, 0x0300},
{ 0x03CC, 0x03BF, 0x0301},
{ 0x1F40, 0x03BF, 0x0313},
{ 0x1F41, 0x03BF, 0x0314},
{ 0x1FE4, 0x03C1, 0x0313},
{ 0x1FE5, 0x03C1, 0x0314},
{ 0x1F7A, 0x03C5, 0x0300},
{ 0x03CD, 0x03C5, 0x0301},
{ 0x1FE1, 0x03C5, 0x0304},
{ 0x1FE0, 0x03C5, 0x0306},
{ 0x03CB, 0x03C5, 0x0308},
{ 0x1F50, 0x03C5, 0x0313},
{ 0x1F51, 0x03C5, 0x0314},
{ 0x1FE6, 0x03C5, 0x0342},
{ 0x1F7C, 0x03C9, 0x0300},
{ 0x03CE, 0x03C9, 0x0301},
{ 0x1F60, 0x03C9, 0x0313},
{ 0x1F61, 0x03C9, 0x0314},
{ 0x1FF6, 0x03C9, 0x0342},
{ 0x1FF3, 0x03C9, 0x0345},
{ 0x1FD2, 0x03CA, 0x0300},
{ 0x0390, 0x03CA, 0x0301},
{ 0x1FD7, 0x03CA, 0x0342},
{ 0x1FE2, 0x03CB, 0x0300},
{ 0x03B0, 0x03CB, 0x0301},
{ 0x1FE7, 0x03CB, 0x0342},
{ 0x1FF4, 0x03CE, 0x0345},
{ 0x03D3, 0x03D2, 0x0301},
{ 0x03D4, 0x03D2, 0x0308},
{ 0x0407, 0x0406, 0x0308},
{ 0x04D0, 0x0410, 0x0306},
{ 0x04D2, 0x0410, 0x0308},
{ 0x0403, 0x0413, 0x0301},
{ 0x0400, 0x0415, 0x0300},
{ 0x04D6, 0x0415, 0x0306},
{ 0x0401, 0x0415, 0x0308},
{ 0x04C1, 0x0416, 0x0306},
{ 0x04DC, 0x0416, 0x0308},
{ 0x04DE, 0x0417, 0x0308},
{ 0x040D, 0x0418, 0x0300},
{ 0x04E2, 0x0418, 0x0304},
{ 0x0419, 0x0418, 0x0306},
{ 0x04E4, 0x0418, 0x0308},
{ 0x040C, 0x041A, 0x0301},
{ 0x04E6, 0x041E, 0x0308},
{ 0x04EE, 0x0423, 0x0304},
{ 0x040E, 0x0423, 0x0306},
{ 0x04F0, 0x0423, 0x0308},
{ 0x04F2, 0x0423, 0x030B},
{ 0x04F4, 0x0427, 0x0308},
{ 0x04F8, 0x042B, 0x0308},
{ 0x04EC, 0x042D, 0x0308},
{ 0x04D1, 0x0430, 0x0306},
{ 0x04D3, 0x0430, 0x0308},
{ 0x0453, 0x0433, 0x0301},
{ 0x0450, 0x0435, 0x0300},
{ 0x04D7, 0x0435, 0x0306},
{ 0x0451, 0x0435, 0x0308},
{ 0x04C2, 0x0436, 0x0306},
{ 0x04DD, 0x0436, 0x0308},
{ 0x04DF, 0x0437, 0x0308},
{ 0x045D, 0x0438, 0x0300},
{ 0x04E3, 0x0438, 0x0304},
{ 0x0439, 0x0438, 0x0306},
{ 0x04E5, 0x0438, 0x0308},
{ 0x045C, 0x043A, 0x0301},
{ 0x04E7, 0x043E, 0x0308},
{ 0x04EF, 0x0443, 0x0304},
{ 0x045E, 0x0443, 0x0306},
{ 0x04F1, 0x0443, 0x0308},
{ 0x04F3, 0x0443, 0x030B},
{ 0x04F5, 0x0447, 0x0308},
{ 0x04F9, 0x044B, 0x0308},
{ 0x04ED, 0x044D, 0x0308},
{ 0x0457, 0x0456, 0x0308},
{ 0x0476, 0x0474, 0x030F},
{ 0x0477, 0x0475, 0x030F},
{ 0x04DA, 0x04D8, 0x0308},
{ 0x04DB, 0x04D9, 0x0308},
{ 0x04EA, 0x04E8, 0x0308},
{ 0x04EB, 0x04E9, 0x0308},
{ 0xFB2E, 0x05D0, 0x05B7},
{ 0xFB2F, 0x05D0, 0x05B8},
{ 0xFB30, 0x05D0, 0x05BC},
{ 0xFB31, 0x05D1, 0x05BC},
{ 0xFB4C, 0x05D1, 0x05BF},
{ 0xFB32, 0x05D2, 0x05BC},
{ 0xFB33, 0x05D3, 0x05BC},
{ 0xFB34, 0x05D4, 0x05BC},
{ 0xFB4B, 0x05D5, 0x05B9},
{ 0xFB35, 0x05D5, 0x05BC},
{ 0xFB36, 0x05D6, 0x05BC},
{ 0xFB38, 0x05D8, 0x05BC},
{ 0xFB1D, 0x05D9, 0x05B4},
{ 0xFB39, 0x05D9, 0x05BC},
{ 0xFB3A, 0x05DA, 0x05BC},
{ 0xFB3B, 0x05DB, 0x05BC},
{ 0xFB4D, 0x05DB, 0x05BF},
{ 0xFB3C, 0x05DC, 0x05BC},
{ 0xFB3E, 0x05DE, 0x05BC},
{ 0xFB40, 0x05E0, 0x05BC},
{ 0xFB41, 0x05E1, 0x05BC},
{ 0xFB43, 0x05E3, 0x05BC},
{ 0xFB44, 0x05E4, 0x05BC},
{ 0xFB4E, 0x05E4, 0x05BF},
{ 0xFB46, 0x05E6, 0x05BC},
{ 0xFB47, 0x05E7, 0x05BC},
{ 0xFB48, 0x05E8, 0x05BC},
{ 0xFB49, 0x05E9, 0x05BC},
{ 0xFB2A, 0x05E9, 0x05C1},
{ 0xFB2B, 0x05E9, 0x05C2},
{ 0xFB4A, 0x05EA, 0x05BC},
{ 0xFB1F, 0x05F2, 0x05B7},
{ 0x0622, 0x0627, 0x0653},
{ 0x0623, 0x0627, 0x0654},
{ 0x0625, 0x0627, 0x0655},
{ 0x0624, 0x0648, 0x0654},
{ 0x0626, 0x064A, 0x0654},
{ 0x06C2, 0x06C1, 0x0654},
{ 0x06D3, 0x06D2, 0x0654},
{ 0x06C0, 0x06D5, 0x0654},
{ 0x0958, 0x0915, 0x093C},
{ 0x0959, 0x0916, 0x093C},
{ 0x095A, 0x0917, 0x093C},
{ 0x095B, 0x091C, 0x093C},
{ 0x095C, 0x0921, 0x093C},
{ 0x095D, 0x0922, 0x093C},
{ 0x0929, 0x0928, 0x093C},
{ 0x095E, 0x092B, 0x093C},
{ 0x095F, 0x092F, 0x093C},
{ 0x0931, 0x0930, 0x093C},
{ 0x0934, 0x0933, 0x093C},
{ 0x09DC, 0x09A1, 0x09BC},
{ 0x09DD, 0x09A2, 0x09BC},
{ 0x09DF, 0x09AF, 0x09BC},
{ 0x09CB, 0x09C7, 0x09BE},
{ 0x09CC, 0x09C7, 0x09D7},
{ 0x0A59, 0x0A16, 0x0A3C},
{ 0x0A5A, 0x0A17, 0x0A3C},
{ 0x0A5B, 0x0A1C, 0x0A3C},
{ 0x0A5E, 0x0A2B, 0x0A3C},
{ 0x0A33, 0x0A32, 0x0A3C},
{ 0x0A36, 0x0A38, 0x0A3C},
{ 0x0B5C, 0x0B21, 0x0B3C},
{ 0x0B5D, 0x0B22, 0x0B3C},
{ 0x0B4B, 0x0B47, 0x0B3E},
{ 0x0B48, 0x0B47, 0x0B56},
{ 0x0B4C, 0x0B47, 0x0B57},
{ 0x0B94, 0x0B92, 0x0BD7},
{ 0x0BCA, 0x0BC6, 0x0BBE},
{ 0x0BCC, 0x0BC6, 0x0BD7},
{ 0x0BCB, 0x0BC7, 0x0BBE},
{ 0x0C48, 0x0C46, 0x0C56},
{ 0x0CC0, 0x0CBF, 0x0CD5},
{ 0x0CCA, 0x0CC6, 0x0CC2},
{ 0x0CC7, 0x0CC6, 0x0CD5},
{ 0x0CC8, 0x0CC6, 0x0CD6},
{ 0x0CCB, 0x0CCA, 0x0CD5},
{ 0x0D4A, 0x0D46, 0x0D3E},
{ 0x0D4C, 0x0D46, 0x0D57},
{ 0x0D4B, 0x0D47, 0x0D3E},
{ 0x0DDA, 0x0DD9, 0x0DCA},
{ 0x0DDC, 0x0DD9, 0x0DCF},
{ 0x0DDE, 0x0DD9, 0x0DDF},
{ 0x0DDD, 0x0DDC, 0x0DCA},
{ 0x0F69, 0x0F40, 0x0FB5},
{ 0x0F43, 0x0F42, 0x0FB7},
{ 0x0F4D, 0x0F4C, 0x0FB7},
{ 0x0F52, 0x0F51, 0x0FB7},
{ 0x0F57, 0x0F56, 0x0FB7},
{ 0x0F5C, 0x0F5B, 0x0FB7},
{ 0x0F73, 0x0F71, 0x0F72},
{ 0x0F75, 0x0F71, 0x0F74},
{ 0x0F81, 0x0F71, 0x0F80},
{ 0x0FB9, 0x0F90, 0x0FB5},
{ 0x0F93, 0x0F92, 0x0FB7},
{ 0x0F9D, 0x0F9C, 0x0FB7},
{ 0x0FA2, 0x0FA1, 0x0FB7},
{ 0x0FA7, 0x0FA6, 0x0FB7},
{ 0x0FAC, 0x0FAB, 0x0FB7},
{ 0x0F76, 0x0FB2, 0x0F80},
{ 0x0F78, 0x0FB3, 0x0F80},
{ 0x1026, 0x1025, 0x102E},
{ 0x1B06, 0x1B05, 0x1B35},
{ 0x1B08, 0x1B07, 0x1B35},
{ 0x1B0A, 0x1B09, 0x1B35},
{ 0x1B0C, 0x1B0B, 0x1B35},
{ 0x1B0E, 0x1B0D, 0x1B35},
{ 0x1B12, 0x1B11, 0x1B35},
{ 0x1B3B, 0x1B3A, 0x1B35},
{ 0x1B3D, 0x1B3C, 0x1B35},
{ 0x1B40, 0x1B3E, 0x1B35},
{ 0x1B41, 0x1B3F, 0x1B35},
{ 0x1B43, 0x1B42, 0x1B35},
{ 0x1E38, 0x1E36, 0x0304},
{ 0x1E39, 0x1E37, 0x0304},
{ 0x1E5C, 0x1E5A, 0x0304},
{ 0x1E5D, 0x1E5B, 0x0304},
{ 0x1E68, 0x1E62, 0x0307},
{ 0x1E69, 0x1E63, 0x0307},
{ 0x1EAC, 0x1EA0, 0x0302},
{ 0x1EB6, 0x1EA0, 0x0306},
{ 0x1EAD, 0x1EA1, 0x0302},
{ 0x1EB7, 0x1EA1, 0x0306},
{ 0x1EC6, 0x1EB8, 0x0302},
{ 0x1EC7, 0x1EB9, 0x0302},
{ 0x1ED8, 0x1ECC, 0x0302},
{ 0x1ED9, 0x1ECD, 0x0302},
{ 0x1F02, 0x1F00, 0x0300},
{ 0x1F04, 0x1F00, 0x0301},
{ 0x1F06, 0x1F00, 0x0342},
{ 0x1F80, 0x1F00, 0x0345},
{ 0x1F03, 0x1F01, 0x0300},
{ 0x1F05, 0x1F01, 0x0301},
{ 0x1F07, 0x1F01, 0x0342},
{ 0x1F81, 0x1F01, 0x0345},
{ 0x1F82, 0x1F02, 0x0345},
{ 0x1F83, 0x1F03, 0x0345},
{ 0x1F84, 0x1F04, 0x0345},
{ 0x1F85, 0x1F05, 0x0345},
{ 0x1F86, 0x1F06, 0x0345},
{ 0x1F87, 0x1F07, 0x0345},
{ 0x1F0A, 0x1F08, 0x0300},
{ 0x1F0C, 0x1F08, 0x0301},
{ 0x1F0E, 0x1F08, 0x0342},
{ 0x1F88, 0x1F08, 0x0345},
{ 0x1F0B, 0x1F09, 0x0300},
{ 0x1F0D, 0x1F09, 0x0301},
{ 0x1F0F, 0x1F09, 0x0342},
{ 0x1F89, 0x1F09, 0x0345},
{ 0x1F8A, 0x1F0A, 0x0345},
{ 0x1F8B, 0x1F0B, 0x0345},
{ 0x1F8C, 0x1F0C, 0x0345},
{ 0x1F8D, 0x1F0D, 0x0345},
{ 0x1F8E, 0x1F0E, 0x0345},
{ 0x1F8F, 0x1F0F, 0x0345},
{ 0x1F12, 0x1F10, 0x0300},
{ 0x1F14, 0x1F10, 0x0301},
{ 0x1F13, 0x1F11, 0x0300},
{ 0x1F15, 0x1F11, 0x0301},
{ 0x1F1A, 0x1F18, 0x0300},
{ 0x1F1C, 0x1F18, 0x0301},
{ 0x1F1B, 0x1F19, 0x0300},
{ 0x1F1D, 0x1F19, 0x0301},
{ 0x1F22, 0x1F20, 0x0300},
{ 0x1F24, 0x1F20, 0x0301},
{ 0x1F26, 0x1F20, 0x0342},
{ 0x1F90, 0x1F20, 0x0345},
{ 0x1F23, 0x1F21, 0x0300},
{ 0x1F25, 0x1F21, 0x0301},
{ 0x1F27, 0x1F21, 0x0342},
{ 0x1F91, 0x1F21, 0x0345},
{ 0x1F92, 0x1F22, 0x0345},
{ 0x1F93, 0x1F23, 0x0345},
{ 0x1F94, 0x1F24, 0x0345},
{ 0x1F95, 0x1F25, 0x0345},
{ 0x1F96, 0x1F26, 0x0345},
{ 0x1F97, 0x1F27, 0x0345},
{ 0x1F2A, 0x1F28, 0x0300},
{ 0x1F2C, 0x1F28, 0x0301},
{ 0x1F2E, 0x1F28, 0x0342},
{ 0x1F98, 0x1F28, 0x0345},
{ 0x1F2B, 0x1F29, 0x0300},
{ 0x1F2D, 0x1F29, 0x0301},
{ 0x1F2F, 0x1F29, 0x0342},
{ 0x1F99, 0x1F29, 0x0345},
{ 0x1F9A, 0x1F2A, 0x0345},
{ 0x1F9B, 0x1F2B, 0x0345},
{ 0x1F9C, 0x1F2C, 0x0345},
{ 0x1F9D, 0x1F2D, 0x0345},
{ 0x1F9E, 0x1F2E, 0x0345},
{ 0x1F9F, 0x1F2F, 0x0345},
{ 0x1F32, 0x1F30, 0x0300},
{ 0x1F34, 0x1F30, 0x0301},
{ 0x1F36, 0x1F30, 0x0342},
{ 0x1F33, 0x1F31, 0x0300},
{ 0x1F35, 0x1F31, 0x0301},
{ 0x1F37, 0x1F31, 0x0342},
{ 0x1F3A, 0x1F38, 0x0300},
{ 0x1F3C, 0x1F38, 0x0301},
{ 0x1F3E, 0x1F38, 0x0342},
{ 0x1F3B, 0x1F39, 0x0300},
{ 0x1F3D, 0x1F39, 0x0301},
{ 0x1F3F, 0x1F39, 0x0342},
{ 0x1F42, 0x1F40, 0x0300},
{ 0x1F44, 0x1F40, 0x0301},
{ 0x1F43, 0x1F41, 0x0300},
{ 0x1F45, 0x1F41, 0x0301},
{ 0x1F4A, 0x1F48, 0x0300},
{ 0x1F4C, 0x1F48, 0x0301},
{ 0x1F4B, 0x1F49, 0x0300},
{ 0x1F4D, 0x1F49, 0x0301},
{ 0x1F52, 0x1F50, 0x0300},
{ 0x1F54, 0x1F50, 0x0301},
{ 0x1F56, 0x1F50, 0x0342},
{ 0x1F53, 0x1F51, 0x0300},
{ 0x1F55, 0x1F51, 0x0301},
{ 0x1F57, 0x1F51, 0x0342},
{ 0x1F5B, 0x1F59, 0x0300},
{ 0x1F5D, 0x1F59, 0x0301},
{ 0x1F5F, 0x1F59, 0x0342},
{ 0x1F62, 0x1F60, 0x0300},
{ 0x1F64, 0x1F60, 0x0301},
{ 0x1F66, 0x1F60, 0x0342},
{ 0x1FA0, 0x1F60, 0x0345},
{ 0x1F63, 0x1F61, 0x0300},
{ 0x1F65, 0x1F61, 0x0301},
{ 0x1F67, 0x1F61, 0x0342},
{ 0x1FA1, 0x1F61, 0x0345},
{ 0x1FA2, 0x1F62, 0x0345},
{ 0x1FA3, 0x1F63, 0x0345},
{ 0x1FA4, 0x1F64, 0x0345},
{ 0x1FA5, 0x1F65, 0x0345},
{ 0x1FA6, 0x1F66, 0x0345},
{ 0x1FA7, 0x1F67, 0x0345},
{ 0x1F6A, 0x1F68, 0x0300},
{ 0x1F6C, 0x1F68, 0x0301},
{ 0x1F6E, 0x1F68, 0x0342},
{ 0x1FA8, 0x1F68, 0x0345},
{ 0x1F6B, 0x1F69, 0x0300},
{ 0x1F6D, 0x1F69, 0x0301},
{ 0x1F6F, 0x1F69, 0x0342},
{ 0x1FA9, 0x1F69, 0x0345},
{ 0x1FAA, 0x1F6A, 0x0345},
{ 0x1FAB, 0x1F6B, 0x0345},
{ 0x1FAC, 0x1F6C, 0x0345},
{ 0x1FAD, 0x1F6D, 0x0345},
{ 0x1FAE, 0x1F6E, 0x0345},
{ 0x1FAF, 0x1F6F, 0x0345},
{ 0x1FB2, 0x1F70, 0x0345},
{ 0x1FC2, 0x1F74, 0x0345},
{ 0x1FF2, 0x1F7C, 0x0345},
{ 0x1FB7, 0x1FB6, 0x0345},
{ 0x1FCD, 0x1FBF, 0x0300},
{ 0x1FCE, 0x1FBF, 0x0301},
{ 0x1FCF, 0x1FBF, 0x0342},
{ 0x1FC7, 0x1FC6, 0x0345},
{ 0x1FF7, 0x1FF6, 0x0345},
{ 0x1FDD, 0x1FFE, 0x0300},
{ 0x1FDE, 0x1FFE, 0x0301},
{ 0x1FDF, 0x1FFE, 0x0342},
{ 0x219A, 0x2190, 0x0338},
{ 0x219B, 0x2192, 0x0338},
{ 0x21AE, 0x2194, 0x0338},
{ 0x21CD, 0x21D0, 0x0338},
{ 0x21CF, 0x21D2, 0x0338},
{ 0x21CE, 0x21D4, 0x0338},
{ 0x2204, 0x2203, 0x0338},
{ 0x2209, 0x2208, 0x0338},
{ 0x220C, 0x220B, 0x0338},
{ 0x2224, 0x2223, 0x0338},
{ 0x2226, 0x2225, 0x0338},
{ 0x2241, 0x223C, 0x0338},
{ 0x2244, 0x2243, 0x0338},
{ 0x2247, 0x2245, 0x0338},
{ 0x2249, 0x2248, 0x0338},
{ 0x226D, 0x224D, 0x0338},
{ 0x2262, 0x2261, 0x0338},
{ 0x2270, 0x2264, 0x0338},
{ 0x2271, 0x2265, 0x0338},
{ 0x2274, 0x2272, 0x0338},
{ 0x2275, 0x2273, 0x0338},
{ 0x2278, 0x2276, 0x0338},
{ 0x2279, 0x2277, 0x0338},
{ 0x2280, 0x227A, 0x0338},
{ 0x2281, 0x227B, 0x0338},
{ 0x22E0, 0x227C, 0x0338},
{ 0x22E1, 0x227D, 0x0338},
{ 0x2284, 0x2282, 0x0338},
{ 0x2285, 0x2283, 0x0338},
{ 0x2288, 0x2286, 0x0338},
{ 0x2289, 0x2287, 0x0338},
{ 0x22E2, 0x2291, 0x0338},
{ 0x22E3, 0x2292, 0x0338},
{ 0x22AC, 0x22A2, 0x0338},
{ 0x22AD, 0x22A8, 0x0338},
{ 0x22AE, 0x22A9, 0x0338},
{ 0x22AF, 0x22AB, 0x0338},
{ 0x22EA, 0x22B2, 0x0338},
{ 0x22EB, 0x22B3, 0x0338},
{ 0x22EC, 0x22B4, 0x0338},
{ 0x22ED, 0x22B5, 0x0338},
{ 0x2ADC, 0x2ADD, 0x0338},
{ 0x3094, 0x3046, 0x3099},
{ 0x304C, 0x304B, 0x3099},
{ 0x304E, 0x304D, 0x3099},
{ 0x3050, 0x304F, 0x3099},
{ 0x3052, 0x3051, 0x3099},
{ 0x3054, 0x3053, 0x3099},
{ 0x3056, 0x3055, 0x3099},
{ 0x3058, 0x3057, 0x3099},
{ 0x305A, 0x3059, 0x3099},
{ 0x305C, 0x305B, 0x3099},
{ 0x305E, 0x305D, 0x3099},
{ 0x3060, 0x305F, 0x3099},
{ 0x3062, 0x3061, 0x3099},
{ 0x3065, 0x3064, 0x3099},
{ 0x3067, 0x3066, 0x3099},
{ 0x3069, 0x3068, 0x3099},
{ 0x3070, 0x306F, 0x3099},
{ 0x3071, 0x306F, 0x309A},
{ 0x3073, 0x3072, 0x3099},
{ 0x3074, 0x3072, 0x309A},
{ 0x3076, 0x3075, 0x3099},
{ 0x3077, 0x3075, 0x309A},
{ 0x3079, 0x3078, 0x3099},
{ 0x307A, 0x3078, 0x309A},
{ 0x307C, 0x307B, 0x3099},
{ 0x307D, 0x307B, 0x309A},
{ 0x309E, 0x309D, 0x3099},
{ 0x30F4, 0x30A6, 0x3099},
{ 0x30AC, 0x30AB, 0x3099},
{ 0x30AE, 0x30AD, 0x3099},
{ 0x30B0, 0x30AF, 0x3099},
{ 0x30B2, 0x30B1, 0x3099},
{ 0x30B4, 0x30B3, 0x3099},
{ 0x30B6, 0x30B5, 0x3099},
{ 0x30B8, 0x30B7, 0x3099},
{ 0x30BA, 0x30B9, 0x3099},
{ 0x30BC, 0x30BB, 0x3099},
{ 0x30BE, 0x30BD, 0x3099},
{ 0x30C0, 0x30BF, 0x3099},
{ 0x30C2, 0x30C1, 0x3099},
{ 0x30C5, 0x30C4, 0x3099},
{ 0x30C7, 0x30C6, 0x3099},
{ 0x30C9, 0x30C8, 0x3099},
{ 0x30D0, 0x30CF, 0x3099},
{ 0x30D1, 0x30CF, 0x309A},
{ 0x30D3, 0x30D2, 0x3099},
{ 0x30D4, 0x30D2, 0x309A},
{ 0x30D6, 0x30D5, 0x3099},
{ 0x30D7, 0x30D5, 0x309A},
{ 0x30D9, 0x30D8, 0x3099},
{ 0x30DA, 0x30D8, 0x309A},
{ 0x30DC, 0x30DB, 0x3099},
{ 0x30DD, 0x30DB, 0x309A},
{ 0x30F7, 0x30EF, 0x3099},
{ 0x30F8, 0x30F0, 0x3099},
{ 0x30F9, 0x30F1, 0x3099},
{ 0x30FA, 0x30F2, 0x3099},
{ 0x30FE, 0x30FD, 0x3099},
{ 0xFB2C, 0xFB49, 0x05C1},
{ 0xFB2D, 0xFB49, 0x05C2},
};
private static final int UNICODE_SHIFT = 21;
public static char precompose(char base, char comb) {
int min = 0;
int max = precompositions.length - 1;
int mid;
long sought = base << UNICODE_SHIFT | comb;
long that;
while (max >= min) {
mid = (min + max) / 2;
that = precompositions[mid][1] << UNICODE_SHIFT | precompositions[mid][2];
if (that < sought)
min = mid + 1;
else if (that > sought)
max = mid - 1;
else
return precompositions[mid][0];
}
// No match; return character without combiner
return base;
}
}
| Java |
/*
* This file is part of "JTA - Telnet/SSH for the JAVA(tm) platform".
*
* (c) Matthias L. Jugel, Marcus Meißner 1996-2005. All Rights Reserved.
*
* Please visit http://javatelnet.org/ for updates and contact.
*
* --LICENSE NOTICE--
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* --LICENSE NOTICE--
*
*/
package de.mud.terminal;
import java.util.Properties;
/**
* An interface for a terminal that accepts input from keyboard and mouse.
*
* @author Matthias L. Jugel, Marcus Meißner
* @version $Id: VDUInput.java 499 2005-09-29 08:24:54Z leo $
*/
public interface VDUInput {
public final static int KEY_CONTROL = 0x01;
public final static int KEY_SHIFT = 0x02;
public final static int KEY_ALT = 0x04;
public final static int KEY_ACTION = 0x08;
/**
* Direct access to writing data ...
* @param b
*/
void write(byte b[]);
/**
* Terminal is mouse-aware and requires (x,y) coordinates of
* on the terminal (character coordinates) and the button clicked.
* @param x
* @param y
* @param modifiers
*/
void mousePressed(int x, int y, int modifiers);
/**
* Terminal is mouse-aware and requires the coordinates and button
* of the release.
* @param x
* @param y
* @param modifiers
*/
void mouseReleased(int x, int y, int modifiers);
/**
* Override the standard key codes used by the terminal emulation.
* @param codes a properties object containing key code definitions
*/
void setKeyCodes(Properties codes);
/**
* main keytyping event handler...
* @param keyCode the key code
* @param keyChar the character represented by the key
* @param modifiers shift/alt/control modifiers
*/
void keyPressed(int keyCode, char keyChar, int modifiers);
/**
* Handle key Typed events for the terminal, this will get
* all normal key types, but no shift/alt/control/numlock.
* @param keyCode the key code
* @param keyChar the character represented by the key
* @param modifiers shift/alt/control modifiers
*/
void keyTyped(int keyCode, char keyChar, int modifiers);
}
| Java |
/*
* This file is part of "JTA - Telnet/SSH for the JAVA(tm) platform".
*
* (c) Matthias L. Jugel, Marcus Meißner 1996-2005. All Rights Reserved.
*
* Please visit http://javatelnet.org/ for updates and contact.
*
* --LICENSE NOTICE--
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
* --LICENSE NOTICE--
*
*/
package de.mud.telnet;
import java.io.IOException;
/**
* This is a telnet protocol handler. The handler needs implementations
* for several methods to handle the telnet options and to be able to
* read and write the buffer.
* <P>
* <B>Maintainer:</B> Marcus Meissner
*
* @version $Id: TelnetProtocolHandler.java 503 2005-10-24 07:34:13Z marcus $
* @author Matthias L. Jugel, Marcus Meissner
*/
public abstract class TelnetProtocolHandler {
/** contains the current revision id */
public final static String ID = "$Id: TelnetProtocolHandler.java 503 2005-10-24 07:34:13Z marcus $";
/** debug level */
private final static int debug = 0;
/** temporary buffer for data-telnetstuff-data transformation */
private byte[] tempbuf = new byte[0];
/** the data sent on pressing <RETURN> \n */
private byte[] crlf = new byte[2];
/** the data sent on pressing <LineFeed> \r */
private byte[] cr = new byte[2];
/**
* Create a new telnet protocol handler.
*/
public TelnetProtocolHandler() {
reset();
crlf[0] = 13; crlf[1] = 10;
cr[0] = 13; cr[1] = 0;
}
/**
* Get the current terminal type for TTYPE telnet option.
* @return the string id of the terminal
*/
protected abstract String getTerminalType();
/**
* Get the current window size of the terminal for the
* NAWS telnet option.
* @return the size of the terminal as Dimension
*/
protected abstract int[] getWindowSize();
/**
* Set the local echo option of telnet.
* @param echo true for local echo, false for no local echo
*/
protected abstract void setLocalEcho(boolean echo);
/**
* Generate an EOR (end of record) request. For use by prompt displaying.
*/
protected abstract void notifyEndOfRecord();
/**
* Send data to the remote host.
* @param b array of bytes to send
*/
protected abstract void write(byte[] b) throws IOException;
/**
* Read the charset name from terminal.
*/
protected abstract String getCharsetName();
/**
* Send one byte to the remote host.
* @param b the byte to be sent
* @see #write(byte[] b)
*/
private static byte[] one = new byte[1];
private void write(byte b) throws IOException {
one[0] = b;
write(one);
}
/**
* Reset the protocol handler. This may be necessary after the
* connection was closed or some other problem occured.
*/
public void reset() {
neg_state = 0;
receivedDX = new byte[256];
sentDX = new byte[256];
receivedWX = new byte[256];
sentWX = new byte[256];
}
// ===================================================================
// the actual negotiation handling for the telnet protocol follows:
// ===================================================================
/** state variable for telnet negotiation reader */
private byte neg_state = 0;
/** constants for the negotiation state */
private final static byte STATE_DATA = 0;
private final static byte STATE_IAC = 1;
private final static byte STATE_IACSB = 2;
private final static byte STATE_IACWILL = 3;
private final static byte STATE_IACDO = 4;
private final static byte STATE_IACWONT = 5;
private final static byte STATE_IACDONT = 6;
private final static byte STATE_IACSBIAC = 7;
private final static byte STATE_IACSBDATA = 8;
private final static byte STATE_IACSBDATAIAC = 9;
/** What IAC SB <xx> we are handling right now */
private byte current_sb;
/** current SB negotiation buffer */
private byte[] sbbuf;
/** IAC - init sequence for telnet negotiation. */
private final static byte IAC = (byte)255;
/** [IAC] End Of Record */
private final static byte EOR = (byte)239;
/** [IAC] WILL */
private final static byte WILL = (byte)251;
/** [IAC] WONT */
private final static byte WONT = (byte)252;
/** [IAC] DO */
private final static byte DO = (byte)253;
/** [IAC] DONT */
private final static byte DONT = (byte)254;
/** [IAC] Sub Begin */
private final static byte SB = (byte)250;
/** [IAC] Sub End */
private final static byte SE = (byte)240;
/** Telnet option: binary mode */
private final static byte TELOPT_BINARY= (byte)0; /* binary mode */
/** Telnet option: echo text */
private final static byte TELOPT_ECHO = (byte)1; /* echo on/off */
/** Telnet option: sga */
private final static byte TELOPT_SGA = (byte)3; /* supress go ahead */
/** Telnet option: End Of Record */
private final static byte TELOPT_EOR = (byte)25; /* end of record */
/** Telnet option: Negotiate About Window Size */
private final static byte TELOPT_NAWS = (byte)31; /* NA-WindowSize*/
/** Telnet option: Terminal Type */
private final static byte TELOPT_TTYPE = (byte)24; /* terminal type */
/** Telnet option: CHARSET */
private final static byte TELOPT_CHARSET= (byte)42; /* charset */
private final static byte[] IACWILL = { IAC, WILL };
private final static byte[] IACWONT = { IAC, WONT };
private final static byte[] IACDO = { IAC, DO };
private final static byte[] IACDONT = { IAC, DONT };
private final static byte[] IACSB = { IAC, SB };
private final static byte[] IACSE = { IAC, SE };
private final static byte CHARSET_ACCEPTED = (byte)2;
private final static byte CHARSET_REJECTED = (byte)3;
/** Telnet option qualifier 'IS' */
private final static byte TELQUAL_IS = (byte)0;
/** Telnet option qualifier 'SEND' */
private final static byte TELQUAL_SEND = (byte)1;
/** What IAC DO(NT) request do we have received already ? */
private byte[] receivedDX;
/** What IAC WILL/WONT request do we have received already ? */
private byte[] receivedWX;
/** What IAC DO/DONT request do we have sent already ? */
private byte[] sentDX;
/** What IAC WILL/WONT request do we have sent already ? */
private byte[] sentWX;
/**
* Send a Telnet Escape character (IAC <code>)
*/
public void sendTelnetControl(byte code)
throws IOException {
byte[] b = new byte[2];
b[0] = IAC;
b[1] = code;
write(b);
}
/**
* Send the new Window Size (via NAWS)
*/
public void setWindowSize(int columns,int rows)
throws IOException {
if(debug > 2) System.err.println("sending NAWS");
if (receivedDX[TELOPT_NAWS] != DO) {
System.err.println("not allowed to send NAWS? (DONT NAWS)");
return;
}
write(IAC);write(SB);write(TELOPT_NAWS);
write((byte) (columns >> 8));
write((byte) (columns & 0xff));
write((byte) (rows >> 8));
write((byte) (rows & 0xff));
write(IAC);write(SE);
}
/**
* Handle an incoming IAC SB <type> <bytes> IAC SE
* @param type type of SB
* @param sbata byte array as <bytes>
*/
private void handle_sb(byte type, byte[] sbdata)
throws IOException {
if(debug > 1)
System.err.println("TelnetIO.handle_sb("+type+")");
switch (type) {
case TELOPT_TTYPE:
if (sbdata.length>0 && sbdata[0]==TELQUAL_SEND) {
write(IACSB);write(TELOPT_TTYPE);write(TELQUAL_IS);
/* FIXME: need more logic here if we use
* more than one terminal type
*/
String ttype = getTerminalType();
if(ttype == null) ttype = "dumb";
write(ttype.getBytes());
write(IACSE);
}
break;
case TELOPT_CHARSET:
System.out.println("Got SB CHARSET");
String charsetStr = new String(sbdata, "US-ASCII");
if (charsetStr.startsWith("TTABLE ")) {
charsetStr = charsetStr.substring(7);
}
String[] charsets = charsetStr.split(charsetStr.substring(0,0));
String myCharset = getCharsetName();
for (String charset : charsets) {
if (charset.equals(myCharset)) {
write(IACSB);write(TELOPT_CHARSET);write(CHARSET_ACCEPTED);
write(charset.getBytes());
write(IACSE);
System.out.println("Sent our charset!");
return;
}
}
write(IACSB);write(TELOPT_CHARSET);write(CHARSET_REJECTED);
write(IACSE);
break;
}
}
/**
* Do not send any notifications at startup. We do not know,
* whether the remote client understands telnet protocol handling,
* so we are silent.
* (This used to send IAC WILL SGA, but this is false for a compliant
* client.)
*/
public void startup() throws IOException {
}
/**
* Transpose special telnet codes like 0xff or newlines to values
* that are compliant to the protocol. This method will also send
* the buffer immediately after transposing the data.
* @param buf the data buffer to be sent
*/
public void transpose(byte[] buf) throws IOException {
int i;
byte[] nbuf,xbuf;
int nbufptr=0;
nbuf = new byte[buf.length*2]; // FIXME: buffer overflows possible
for (i = 0; i < buf.length ; i++) {
switch (buf[i]) {
// Escape IAC twice in stream ... to be telnet protocol compliant
// this is there in binary and non-binary mode.
case IAC:
nbuf[nbufptr++]=IAC;
nbuf[nbufptr++]=IAC;
break;
// We need to heed RFC 854. LF (\n) is 10, CR (\r) is 13
// we assume that the Terminal sends \n for lf+cr and \r for just cr
// linefeed+carriage return is CR LF */
case 10: // \n
if (receivedDX[TELOPT_BINARY + 128 ] != DO) {
while (nbuf.length - nbufptr < crlf.length) {
xbuf = new byte[nbuf.length*2];
System.arraycopy(nbuf,0,xbuf,0,nbufptr);
nbuf = xbuf;
}
for (int j=0;j<crlf.length;j++)
nbuf[nbufptr++]=crlf[j];
break;
} else {
// copy verbatim in binary mode.
nbuf[nbufptr++]=buf[i];
}
break;
// carriage return is CR NUL */
case 13: // \r
if (receivedDX[TELOPT_BINARY + 128 ] != DO) {
while (nbuf.length - nbufptr < cr.length) {
xbuf = new byte[nbuf.length*2];
System.arraycopy(nbuf,0,xbuf,0,nbufptr);
nbuf = xbuf;
}
for (int j=0;j<cr.length;j++)
nbuf[nbufptr++]=cr[j];
} else {
// copy verbatim in binary mode.
nbuf[nbufptr++]=buf[i];
}
break;
// all other characters are just copied
default:
nbuf[nbufptr++]=buf[i];
break;
}
}
xbuf = new byte[nbufptr];
System.arraycopy(nbuf,0,xbuf,0,nbufptr);
write(xbuf);
}
public void setCRLF(String xcrlf) { crlf = xcrlf.getBytes(); }
public void setCR(String xcr) { cr = xcr.getBytes(); }
/**
* Handle telnet protocol negotiation. The buffer will be parsed
* and necessary actions are taken according to the telnet protocol.
* See <A HREF="RFC-Telnet-URL">RFC-Telnet</A>
* @param nbuf the byte buffer put out after negotiation
* @return number of bytes processed, 0 for none, and -1 for end of buffer.
*/
public int negotiate(byte nbuf[], int offset)
throws IOException
{
int count = tempbuf.length;
byte[] buf = tempbuf;
byte sendbuf[] = new byte[3];
byte b,reply;
int boffset = 0, noffset = offset;
boolean dobreak = false;
if (count == 0) // buffer is empty.
return -1;
while(!dobreak && (boffset < count) && (noffset < nbuf.length)) {
b=buf[boffset++];
// of course, byte is a signed entity (-128 -> 127)
// but apparently the SGI Netscape 3.0 doesn't seem
// to care and provides happily values up to 255
if (b>=128)
b=(byte)(b-256);
if(debug > 2) {
Byte B = new Byte(b);
System.err.print("byte: " + B.intValue()+ " ");
}
switch (neg_state) {
case STATE_DATA:
if (b==IAC) {
neg_state = STATE_IAC;
dobreak = true; // leave the loop so we can sync.
} else
nbuf[noffset++]=b;
break;
case STATE_IAC:
switch (b) {
case IAC:
if(debug > 2) System.err.print("IAC ");
neg_state = STATE_DATA;
nbuf[noffset++]=IAC;
break;
case WILL:
if(debug > 2) System.err.print("WILL ");
neg_state = STATE_IACWILL;
break;
case WONT:
if(debug > 2) System.err.print("WONT ");
neg_state = STATE_IACWONT;
break;
case DONT:
if(debug > 2) System.err.print("DONT ");
neg_state = STATE_IACDONT;
break;
case DO:
if(debug > 2) System.err.print("DO ");
neg_state = STATE_IACDO;
break;
case EOR:
if(debug > 1) System.err.print("EOR ");
notifyEndOfRecord();
dobreak = true; // leave the loop so we can sync.
neg_state = STATE_DATA;
break;
case SB:
if(debug > 2) System.err.print("SB ");
neg_state = STATE_IACSB;
break;
default:
if(debug > 2) System.err.print("<UNKNOWN "+b+" > ");
neg_state = STATE_DATA;
break;
}
break;
case STATE_IACWILL:
switch(b) {
case TELOPT_ECHO:
if(debug > 2) System.err.println("ECHO");
reply = DO;
setLocalEcho(false);
break;
case TELOPT_SGA:
if(debug > 2) System.err.println("SGA");
reply = DO;
break;
case TELOPT_EOR:
if(debug > 2) System.err.println("EOR");
reply = DO;
break;
case TELOPT_BINARY:
if(debug > 2) System.err.println("BINARY");
reply = DO;
break;
default:
if(debug > 2) System.err.println("<UNKNOWN,"+b+">");
reply = DONT;
break;
}
if(debug > 1) System.err.println("<"+b+", WILL ="+WILL+">");
if (reply != sentDX[b+128] || WILL != receivedWX[b+128]) {
sendbuf[0]=IAC;
sendbuf[1]=reply;
sendbuf[2]=b;
write(sendbuf);
sentDX[b+128] = reply;
receivedWX[b+128] = WILL;
}
neg_state = STATE_DATA;
break;
case STATE_IACWONT:
switch(b) {
case TELOPT_ECHO:
if(debug > 2) System.err.println("ECHO");
setLocalEcho(true);
reply = DONT;
break;
case TELOPT_SGA:
if(debug > 2) System.err.println("SGA");
reply = DONT;
break;
case TELOPT_EOR:
if(debug > 2) System.err.println("EOR");
reply = DONT;
break;
case TELOPT_BINARY:
if(debug > 2) System.err.println("BINARY");
reply = DONT;
break;
default:
if(debug > 2) System.err.println("<UNKNOWN,"+b+">");
reply = DONT;
break;
}
if(reply != sentDX[b+128] || WONT != receivedWX[b+128]) {
sendbuf[0]=IAC;
sendbuf[1]=reply;
sendbuf[2]=b;
write(sendbuf);
sentDX[b+128] = reply;
receivedWX[b+128] = WILL;
}
neg_state = STATE_DATA;
break;
case STATE_IACDO:
switch (b) {
case TELOPT_ECHO:
if(debug > 2) System.err.println("ECHO");
reply = WILL;
setLocalEcho(true);
break;
case TELOPT_SGA:
if(debug > 2) System.err.println("SGA");
reply = WILL;
break;
case TELOPT_TTYPE:
if(debug > 2) System.err.println("TTYPE");
reply = WILL;
break;
case TELOPT_BINARY:
if(debug > 2) System.err.println("BINARY");
reply = WILL;
break;
case TELOPT_NAWS:
if(debug > 2) System.err.println("NAWS");
int[] size = getWindowSize();
receivedDX[b] = DO;
if(size == null) {
// this shouldn't happen
write(IAC);
write(WONT);
write(TELOPT_NAWS);
reply = WONT;
sentWX[b] = WONT;
break;
}
reply = WILL;
sentWX[b] = WILL;
sendbuf[0]=IAC;
sendbuf[1]=WILL;
sendbuf[2]=TELOPT_NAWS;
write(sendbuf);
write(IAC);write(SB);write(TELOPT_NAWS);
write((byte) (size[0] >> 8));
write((byte) (size[0] & 0xff));
write((byte) (size[1] >> 8));
write((byte) (size[1] & 0xff));
write(IAC);write(SE);
break;
default:
if(debug > 2) System.err.println("<UNKNOWN,"+b+">");
reply = WONT;
break;
}
if(reply != sentWX[128+b] || DO != receivedDX[128+b]) {
sendbuf[0]=IAC;
sendbuf[1]=reply;
sendbuf[2]=b;
write(sendbuf);
sentWX[b+128] = reply;
receivedDX[b+128] = DO;
}
neg_state = STATE_DATA;
break;
case STATE_IACDONT:
switch (b) {
case TELOPT_ECHO:
if(debug > 2) System.err.println("ECHO");
reply = WONT;
setLocalEcho(false);
break;
case TELOPT_SGA:
if(debug > 2) System.err.println("SGA");
reply = WONT;
break;
case TELOPT_NAWS:
if(debug > 2) System.err.println("NAWS");
reply = WONT;
break;
case TELOPT_BINARY:
if(debug > 2) System.err.println("BINARY");
reply = WONT;
break;
default:
if(debug > 2) System.err.println("<UNKNOWN,"+b+">");
reply = WONT;
break;
}
if(reply != sentWX[b+128] || DONT != receivedDX[b+128]) {
write(IAC);write(reply);write(b);
sentWX[b+128] = reply;
receivedDX[b+128] = DONT;
}
neg_state = STATE_DATA;
break;
case STATE_IACSBIAC:
if(debug > 2) System.err.println(""+b+" ");
if (b == IAC) {
sbbuf = new byte[0];
current_sb = b;
neg_state = STATE_IACSBDATA;
} else {
System.err.println("(bad) "+b+" ");
neg_state = STATE_DATA;
}
break;
case STATE_IACSB:
if(debug > 2) System.err.println(""+b+" ");
switch (b) {
case IAC:
neg_state = STATE_IACSBIAC;
break;
default:
current_sb = b;
sbbuf = new byte[0];
neg_state = STATE_IACSBDATA;
break;
}
break;
case STATE_IACSBDATA:
if (debug > 2) System.err.println(""+b+" ");
switch (b) {
case IAC:
neg_state = STATE_IACSBDATAIAC;
break;
default:
byte[] xsb = new byte[sbbuf.length+1];
System.arraycopy(sbbuf,0,xsb,0,sbbuf.length);
sbbuf = xsb;
sbbuf[sbbuf.length-1] = b;
break;
}
break;
case STATE_IACSBDATAIAC:
if (debug > 2) System.err.println(""+b+" ");
switch (b) {
case IAC:
neg_state = STATE_IACSBDATA;
byte[] xsb = new byte[sbbuf.length+1];
System.arraycopy(sbbuf,0,xsb,0,sbbuf.length);
sbbuf = xsb;
sbbuf[sbbuf.length-1] = IAC;
break;
case SE:
handle_sb(current_sb,sbbuf);
current_sb = 0;
neg_state = STATE_DATA;
break;
case SB:
handle_sb(current_sb,sbbuf);
neg_state = STATE_IACSB;
break;
default:
neg_state = STATE_DATA;
break;
}
break;
default:
if (debug > 1)
System.err.println("This should not happen: "+neg_state+" ");
neg_state = STATE_DATA;
break;
}
}
// shrink tempbuf to new processed size.
byte[] xb = new byte[count-boffset];
System.arraycopy(tempbuf,boffset,xb,0,count-boffset);
tempbuf = xb;
return noffset - offset;
}
public void inputfeed(byte[] b, int offset, int len) {
byte[] xb = new byte[tempbuf.length+len];
System.arraycopy(tempbuf,0,xb,0,tempbuf.length);
System.arraycopy(b,offset,xb,tempbuf.length,len);
tempbuf = xb;
}
}
| Java |
/*
* Copyright (C) 2008 OpenIntents.org
*
* 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.openintents.intents;
// Version Dec 9, 2008
/**
* Provides OpenIntents actions, extras, and categories used by providers.
* <p>These specifiers extend the standard Android specifiers.</p>
*/
public final class FileManagerIntents {
/**
* Activity Action: Pick a file through the file manager, or let user
* specify a custom file name.
* Data is the current file name or file name suggestion.
* Returns a new file name as file URI in data.
*
* <p>Constant Value: "org.openintents.action.PICK_FILE"</p>
*/
public static final String ACTION_PICK_FILE = "org.openintents.action.PICK_FILE";
/**
* Activity Action: Pick a directory through the file manager, or let user
* specify a custom file name.
* Data is the current directory name or directory name suggestion.
* Returns a new directory name as file URI in data.
*
* <p>Constant Value: "org.openintents.action.PICK_DIRECTORY"</p>
*/
public static final String ACTION_PICK_DIRECTORY = "org.openintents.action.PICK_DIRECTORY";
/**
* The title to display.
*
* <p>This is shown in the title bar of the file manager.</p>
*
* <p>Constant Value: "org.openintents.extra.TITLE"</p>
*/
public static final String EXTRA_TITLE = "org.openintents.extra.TITLE";
/**
* The text on the button to display.
*
* <p>Depending on the use, it makes sense to set this to "Open" or "Save".</p>
*
* <p>Constant Value: "org.openintents.extra.BUTTON_TEXT"</p>
*/
public static final String EXTRA_BUTTON_TEXT = "org.openintents.extra.BUTTON_TEXT";
}
| Java |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.harmony.niochar.charset.additional;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
/* TODO: support direct byte buffers
import org.apache.harmony.nio.AddressUtil;
import org.apache.harmony.niochar.CharsetProviderImpl;
*/
public class IBM437 extends Charset {
public IBM437(String csName, String[] aliases) {
super(csName, aliases);
}
public boolean contains(Charset cs) {
return cs.name().equalsIgnoreCase("IBM367") || cs.name().equalsIgnoreCase("IBM437") || cs.name().equalsIgnoreCase("US-ASCII") ;
}
public CharsetDecoder newDecoder() {
return new Decoder(this);
}
public CharsetEncoder newEncoder() {
return new Encoder(this);
}
private static final class Decoder extends CharsetDecoder{
private Decoder(Charset cs){
super(cs, 1, 1);
}
private native int nDecode(char[] array, int arrPosition, int remaining, long outAddr, int absolutePos);
protected CoderResult decodeLoop(ByteBuffer bb, CharBuffer cb){
int cbRemaining = cb.remaining();
/* TODO: support direct byte buffers
if(CharsetProviderImpl.hasLoadedNatives() && bb.isDirect() && bb.hasRemaining() && cb.hasArray()){
int toProceed = bb.remaining();
int cbPos = cb.position();
int bbPos = bb.position();
boolean throwOverflow = false;
if( cbRemaining < toProceed ) {
toProceed = cbRemaining;
throwOverflow = true;
}
int res = nDecode(cb.array(), cb.arrayOffset()+cbPos, toProceed, AddressUtil.getDirectBufferAddress(bb), bbPos);
bb.position(bbPos+res);
cb.position(cbPos+res);
if(throwOverflow) return CoderResult.OVERFLOW;
}else{
*/
if(bb.hasArray() && cb.hasArray()) {
int rem = bb.remaining();
rem = cbRemaining >= rem ? rem : cbRemaining;
byte[] bArr = bb.array();
char[] cArr = cb.array();
int bStart = bb.position();
int cStart = cb.position();
int i;
for(i=bStart; i<bStart+rem; i++) {
char in = (char)(bArr[i] & 0xFF);
if(in >= 26){
int index = (int)in - 26;
cArr[cStart++] = (char)arr[index];
}else {
cArr[cStart++] = (char)(in & 0xFF);
}
}
bb.position(i);
cb.position(cStart);
if(rem == cbRemaining && bb.hasRemaining()) return CoderResult.OVERFLOW;
} else {
while(bb.hasRemaining()){
if( cbRemaining == 0 ) return CoderResult.OVERFLOW;
char in = (char)(bb.get() & 0xFF);
if(in >= 26){
int index = (int)in - 26;
cb.put(arr[index]);
}else {
cb.put((char)(in & 0xFF));
}
cbRemaining--;
}
/*
}
*/
}
return CoderResult.UNDERFLOW;
}
final static char[] arr = {
0x001C,0x001B,0x007F,0x001D,0x001E,0x001F,
0x0020,0x0021,0x0022,0x0023,0x0024,0x0025,0x0026,0x0027,
0x0028,0x0029,0x002A,0x002B,0x002C,0x002D,0x002E,0x002F,
0x0030,0x0031,0x0032,0x0033,0x0034,0x0035,0x0036,0x0037,
0x0038,0x0039,0x003A,0x003B,0x003C,0x003D,0x003E,0x003F,
0x0040,0x0041,0x0042,0x0043,0x0044,0x0045,0x0046,0x0047,
0x0048,0x0049,0x004A,0x004B,0x004C,0x004D,0x004E,0x004F,
0x0050,0x0051,0x0052,0x0053,0x0054,0x0055,0x0056,0x0057,
0x0058,0x0059,0x005A,0x005B,0x005C,0x005D,0x005E,0x005F,
0x0060,0x0061,0x0062,0x0063,0x0064,0x0065,0x0066,0x0067,
0x0068,0x0069,0x006A,0x006B,0x006C,0x006D,0x006E,0x006F,
0x0070,0x0071,0x0072,0x0073,0x0074,0x0075,0x0076,0x0077,
0x0078,0x0079,0x007A,0x007B,0x007C,0x007D,0x007E,0x001A,
0x00C7,0x00FC,0x00E9,0x00E2,0x00E4,0x00E0,0x00E5,0x00E7,
0x00EA,0x00EB,0x00E8,0x00EF,0x00EE,0x00EC,0x00C4,0x00C5,
0x00C9,0x00E6,0x00C6,0x00F4,0x00F6,0x00F2,0x00FB,0x00F9,
0x00FF,0x00D6,0x00DC,0x00A2,0x00A3,0x00A5,0x20A7,0x0192,
0x00E1,0x00ED,0x00F3,0x00FA,0x00F1,0x00D1,0x00AA,0x00BA,
0x00BF,0x2310,0x00AC,0x00BD,0x00BC,0x00A1,0x00AB,0x00BB,
0x2591,0x2592,0x2593,0x2502,0x2524,0x2561,0x2562,0x2556,
0x2555,0x2563,0x2551,0x2557,0x255D,0x255C,0x255B,0x2510,
0x2514,0x2534,0x252C,0x251C,0x2500,0x253C,0x255E,0x255F,
0x255A,0x2554,0x2569,0x2566,0x2560,0x2550,0x256C,0x2567,
0x2568,0x2564,0x2565,0x2559,0x2558,0x2552,0x2553,0x256B,
0x256A,0x2518,0x250C,0x2588,0x2584,0x258C,0x2590,0x2580,
0x03B1,0x00DF,0x0393,0x03C0,0x03A3,0x03C3,0x03BC,0x03C4,
0x03A6,0x0398,0x03A9,0x03B4,0x221E,0x03C6,0x03B5,0x2229,
0x2261,0x00B1,0x2265,0x2264,0x2320,0x2321,0x00F7,0x2248,
0x00B0,0x2219,0x00B7,0x221A,0x207F,0x00B2,0x25A0,0x00A0
};
}
private static final class Encoder extends CharsetEncoder{
private Encoder(Charset cs){
super(cs, 1, 1);
}
private native void nEncode(long outAddr, int absolutePos, char[] array, int arrPosition, int[] res);
protected CoderResult encodeLoop(CharBuffer cb, ByteBuffer bb){
int bbRemaining = bb.remaining();
/* TODO: support direct byte buffers
if(CharsetProviderImpl.hasLoadedNatives() && bb.isDirect() && cb.hasRemaining() && cb.hasArray()){
int toProceed = cb.remaining();
int cbPos = cb.position();
int bbPos = bb.position();
boolean throwOverflow = false;
if( bbRemaining < toProceed ) {
toProceed = bbRemaining;
throwOverflow = true;
}
int[] res = {toProceed, 0};
nEncode(AddressUtil.getDirectBufferAddress(bb), bbPos, cb.array(), cb.arrayOffset()+cbPos, res);
if( res[0] <= 0 ) {
bb.position(bbPos-res[0]);
cb.position(cbPos-res[0]);
if(res[1]!=0) {
if(res[1] < 0)
return CoderResult.malformedForLength(-res[1]);
else
return CoderResult.unmappableForLength(res[1]);
}
}else{
bb.position(bbPos+res[0]);
cb.position(cbPos+res[0]);
if(throwOverflow) return CoderResult.OVERFLOW;
}
}else{
*/
if(bb.hasArray() && cb.hasArray()) {
byte[] byteArr = bb.array();
char[] charArr = cb.array();
int rem = cb.remaining();
int byteArrStart = bb.position();
rem = bbRemaining <= rem ? bbRemaining : rem;
int x;
for(x = cb.position(); x < cb.position()+rem; x++) {
char c = charArr[x];
if(c > (char)0x25A0){
if (c >= 0xD800 && c <= 0xDFFF) {
if(x+1 < cb.limit()) {
char c1 = charArr[x+1];
if(c1 >= 0xD800 && c1 <= 0xDFFF) {
cb.position(x); bb.position(byteArrStart);
return CoderResult.unmappableForLength(2);
}
} else {
cb.position(x); bb.position(byteArrStart);
return CoderResult.UNDERFLOW;
}
cb.position(x); bb.position(byteArrStart);
return CoderResult.malformedForLength(1);
}
cb.position(x); bb.position(byteArrStart);
return CoderResult.unmappableForLength(1);
}else{
if(c < 0x1A) {
byteArr[byteArrStart++] = (byte)c;
} else {
int index = (int)c >> 8;
index = encodeIndex[index];
if(index < 0) {
cb.position(x); bb.position(byteArrStart);
return CoderResult.unmappableForLength(1);
}
index <<= 8;
index += (int)c & 0xFF;
if((byte)arr[index] != 0){
byteArr[byteArrStart++] = (byte)arr[index];
}else{
cb.position(x); bb.position(byteArrStart);
return CoderResult.unmappableForLength(1);
}
}
}
}
cb.position(x);
bb.position(byteArrStart);
if(rem == bbRemaining && cb.hasRemaining()) {
return CoderResult.OVERFLOW;
}
} else {
while(cb.hasRemaining()){
if( bbRemaining == 0 ) return CoderResult.OVERFLOW;
char c = cb.get();
if(c > (char)0x25A0){
if (c >= 0xD800 && c <= 0xDFFF) {
if(cb.hasRemaining()) {
char c1 = cb.get();
if(c1 >= 0xD800 && c1 <= 0xDFFF) {
cb.position(cb.position()-2);
return CoderResult.unmappableForLength(2);
} else {
cb.position(cb.position()-1);
}
} else {
cb.position(cb.position()-1);
return CoderResult.UNDERFLOW;
}
cb.position(cb.position()-1);
return CoderResult.malformedForLength(1);
}
cb.position(cb.position()-1);
return CoderResult.unmappableForLength(1);
}else{
if(c < 0x1A) {
bb.put((byte)c);
} else {
int index = (int)c >> 8;
index = encodeIndex[index];
if(index < 0) {
cb.position(cb.position()-1);
return CoderResult.unmappableForLength(1);
}
index <<= 8;
index += (int)c & 0xFF;
if((byte)arr[index] != 0){
bb.put((byte)arr[index]);
}else{
cb.position(cb.position()-1);
return CoderResult.unmappableForLength(1);
}
}
bbRemaining--;
}
}
/* TODO: support direct byte buffers
}
*/
}
return CoderResult.UNDERFLOW;
}
final static char arr[] = {
0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F,
0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x7F,0x1B,0x1A,0x1D,0x1E,0x1F,
0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F,
0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,0x3E,0x3F,
0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F,
0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x5B,0x5C,0x5D,0x5E,0x5F,
0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F,
0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x7B,0x7C,0x7D,0x7E,0x1C,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xFF,0xAD,0x9B,0x9C,0x00,0x9D,0x00,0x00,0x00,0x00,0xA6,0xAE,0xAA,0x00,0x00,0x00,
0xF8,0xF1,0xFD,0x00,0x00,0x00,0x00,0xFA,0x00,0x00,0xA7,0xAF,0xAC,0xAB,0x00,0xA8,
0x00,0x00,0x00,0x00,0x8E,0x8F,0x92,0x80,0x00,0x90,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0xA5,0x00,0x00,0x00,0x00,0x99,0x00,0x00,0x00,0x00,0x00,0x9A,0x00,0x00,0xE1,
0x85,0xA0,0x83,0x00,0x84,0x86,0x91,0x87,0x8A,0x82,0x88,0x89,0x8D,0xA1,0x8C,0x8B,
0x00,0xA4,0x95,0xA2,0x93,0x00,0x94,0xF6,0x00,0x97,0xA3,0x96,0x81,0x00,0x00,0x98,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x9F,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0xE2,0x00,0x00,0x00,0x00,0xE9,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0xE4,0x00,0x00,0xE8,0x00,0x00,0xEA,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0xE0,0x00,0x00,0xEB,0xEE,0x00,0x00,0x00,0x00,0x00,0x00,0xE6,0x00,0x00,0x00,
0xE3,0x00,0x00,0xE5,0xE7,0x00,0xED,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xFC,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x9E,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF9,0xFB,0x00,0x00,0x00,0xEC,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xEF,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF7,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0xF0,0x00,0x00,0xF3,0xF2,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xA9,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xF4,0xF5,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xC4,0x00,0xB3,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xDA,0x00,0x00,0x00,
0xBF,0x00,0x00,0x00,0xC0,0x00,0x00,0x00,0xD9,0x00,0x00,0x00,0xC3,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xB4,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xC2,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0xC1,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xC5,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xCD,0xBA,0xD5,0xD6,0xC9,0xB8,0xB7,0xBB,0xD4,0xD3,0xC8,0xBE,0xBD,0xBC,0xC6,0xC7,
0xCC,0xB5,0xB6,0xB9,0xD1,0xD2,0xCB,0xCF,0xD0,0xCA,0xD8,0xD7,0xCE,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xDF,0x00,0x00,0x00,0xDC,0x00,0x00,0x00,0xDB,0x00,0x00,0x00,0xDD,0x00,0x00,0x00,
0xDE,0xB0,0xB1,0xB2,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0xFE,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00
};
final static int[] encodeIndex = {
0,1,-1,2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
3,-1,4,5,-1,6,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
};
}
}
| Java |
/*
* 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.util.Arrays;
import java.util.List;
import org.connectbot.util.Colors;
import org.connectbot.util.HostDatabase;
import org.connectbot.util.UberColorPickerDialog;
import org.connectbot.util.UberColorPickerDialog.OnColorChangedListener;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
/**
* @author Kenny Root
*
*/
public class ColorsActivity extends Activity implements OnItemClickListener, OnColorChangedListener, OnItemSelectedListener {
private GridView mColorGrid;
private Spinner mFgSpinner;
private Spinner mBgSpinner;
private int mColorScheme;
private List<Integer> mColorList;
private HostDatabase hostdb;
private int mCurrentColor = 0;
private int[] mDefaultColors;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_colors);
this.setTitle(String.format("%s: %s",
getResources().getText(R.string.app_name),
getResources().getText(R.string.title_colors)));
mColorScheme = HostDatabase.DEFAULT_COLOR_SCHEME;
hostdb = new HostDatabase(this);
mColorList = Arrays.asList(hostdb.getColorsForScheme(mColorScheme));
mDefaultColors = hostdb.getDefaultColorsForScheme(mColorScheme);
mColorGrid = (GridView) findViewById(R.id.color_grid);
mColorGrid.setAdapter(new ColorsAdapter(true));
mColorGrid.setOnItemClickListener(this);
mColorGrid.setSelection(0);
mFgSpinner = (Spinner) findViewById(R.id.fg);
mFgSpinner.setAdapter(new ColorsAdapter(false));
mFgSpinner.setSelection(mDefaultColors[0]);
mFgSpinner.setOnItemSelectedListener(this);
mBgSpinner = (Spinner) findViewById(R.id.bg);
mBgSpinner.setAdapter(new ColorsAdapter(false));
mBgSpinner.setSelection(mDefaultColors[1]);
mBgSpinner.setOnItemSelectedListener(this);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (hostdb != null) {
hostdb.close();
hostdb = null;
}
}
@Override
protected void onResume() {
super.onResume();
if (hostdb == null)
hostdb = new HostDatabase(this);
}
private class ColorsAdapter extends BaseAdapter {
private boolean mSquareViews;
public ColorsAdapter(boolean squareViews) {
mSquareViews = squareViews;
}
public View getView(int position, View convertView, ViewGroup parent) {
ColorView c;
if (convertView == null) {
c = new ColorView(ColorsActivity.this, mSquareViews);
} else {
c = (ColorView) convertView;
}
c.setColor(mColorList.get(position));
c.setNumber(position + 1);
return c;
}
public int getCount() {
return mColorList.size();
}
public Object getItem(int position) {
return mColorList.get(position);
}
public long getItemId(int position) {
return position;
}
}
private class ColorView extends View {
private boolean mSquare;
private Paint mTextPaint;
private Paint mShadowPaint;
// Things we paint
private int mBackgroundColor;
private String mText;
private int mAscent;
private int mWidthCenter;
private int mHeightCenter;
public ColorView(Context context, boolean square) {
super(context);
mSquare = square;
mTextPaint = new Paint();
mTextPaint.setAntiAlias(true);
mTextPaint.setTextSize(16);
mTextPaint.setColor(0xFFFFFFFF);
mTextPaint.setTextAlign(Paint.Align.CENTER);
mShadowPaint = new Paint(mTextPaint);
mShadowPaint.setStyle(Paint.Style.STROKE);
mShadowPaint.setStrokeCap(Paint.Cap.ROUND);
mShadowPaint.setStrokeJoin(Paint.Join.ROUND);
mShadowPaint.setStrokeWidth(4f);
mShadowPaint.setColor(0xFF000000);
setPadding(10, 10, 10, 10);
}
public void setColor(int color) {
mBackgroundColor = color;
}
public void setNumber(int number) {
mText = Integer.toString(number);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = measureWidth(widthMeasureSpec);
int height;
if (mSquare)
height = width;
else
height = measureHeight(heightMeasureSpec);
mAscent = (int) mTextPaint.ascent();
mWidthCenter = width / 2;
mHeightCenter = height / 2 - mAscent / 2;
setMeasuredDimension(width, height);
}
private int measureWidth(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
// Measure the text
result = (int) mTextPaint.measureText(mText) + getPaddingLeft()
+ getPaddingRight();
if (specMode == MeasureSpec.AT_MOST) {
// Respect AT_MOST value if that was what is called for by
// measureSpec
result = Math.min(result, specSize);
}
}
return result;
}
private int measureHeight(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
mAscent = (int) mTextPaint.ascent();
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
// Measure the text (beware: ascent is a negative number)
result = (int) (-mAscent + mTextPaint.descent())
+ getPaddingTop() + getPaddingBottom();
if (specMode == MeasureSpec.AT_MOST) {
// Respect AT_MOST value if that was what is called for by
// measureSpec
result = Math.min(result, specSize);
}
}
return result;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(mBackgroundColor);
canvas.drawText(mText, mWidthCenter, mHeightCenter, mShadowPaint);
canvas.drawText(mText, mWidthCenter, mHeightCenter, mTextPaint);
}
}
private void editColor(int colorNumber) {
mCurrentColor = colorNumber;
new UberColorPickerDialog(this, this, mColorList.get(colorNumber)).show();
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
editColor(position);
}
public void onNothingSelected(AdapterView<?> arg0) { }
public void colorChanged(int value) {
hostdb.setGlobalColor(mCurrentColor, value);
mColorList.set(mCurrentColor, value);
mColorGrid.invalidateViews();
}
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
boolean needUpdate = false;
if (parent == mFgSpinner) {
if (position != mDefaultColors[0]) {
mDefaultColors[0] = position;
needUpdate = true;
}
} else if (parent == mBgSpinner) {
if (position != mDefaultColors[1]) {
mDefaultColors[1] = position;
needUpdate = true;
}
}
if (needUpdate)
hostdb.setDefaultColorsForScheme(mColorScheme, mDefaultColors[0], mDefaultColors[1]);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem reset = menu.add(R.string.menu_colors_reset);
reset.setAlphabeticShortcut('r');
reset.setNumericShortcut('1');
reset.setIcon(android.R.drawable.ic_menu_revert);
reset.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem arg0) {
// Reset each individual color to defaults.
for (int i = 0; i < Colors.defaults.length; i++) {
if (mColorList.get(i) != Colors.defaults[i]) {
hostdb.setGlobalColor(i, Colors.defaults[i]);
mColorList.set(i, Colors.defaults[i]);
}
}
mColorGrid.invalidateViews();
// Reset the default FG/BG colors as well.
mFgSpinner.setSelection(HostDatabase.DEFAULT_FG_COLOR);
mBgSpinner.setSelection(HostDatabase.DEFAULT_BG_COLOR);
hostdb.setDefaultColorsForScheme(HostDatabase.DEFAULT_COLOR_SCHEME,
HostDatabase.DEFAULT_FG_COLOR, HostDatabase.DEFAULT_BG_COLOR);
return true;
}
});
return true;
}
}
| Java |
/*
* 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.service;
public interface BridgeDisconnectedListener {
public void onDisconnected(TerminalBridge bridge);
}
| Java |
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2010 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.service;
import org.connectbot.util.PreferenceConstants;
import android.app.backup.BackupManager;
import android.content.Context;
/**
* @author kroot
*
*/
public abstract class BackupWrapper {
public static BackupWrapper getInstance() {
if (PreferenceConstants.PRE_FROYO)
return PreFroyo.Holder.sInstance;
else
return FroyoAndBeyond.Holder.sInstance;
}
public abstract void onDataChanged(Context context);
private static class PreFroyo extends BackupWrapper {
private static class Holder {
private static final PreFroyo sInstance = new PreFroyo();
}
@Override
public void onDataChanged(Context context) {
// do nothing for now
}
}
private static class FroyoAndBeyond extends BackupWrapper {
private static class Holder {
private static final FroyoAndBeyond sInstance = new FroyoAndBeyond();
}
private static BackupManager mBackupManager;
@Override
public void onDataChanged(Context context) {
checkBackupManager(context);
if (mBackupManager != null) {
mBackupManager.dataChanged();
}
}
private void checkBackupManager(Context context) {
if (mBackupManager == null) {
mBackupManager = new BackupManager(context);
}
}
}
}
| Java |
/*
* 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.service;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
import org.apache.harmony.niochar.charset.additional.IBM437;
import org.connectbot.transport.AbsTransport;
import org.connectbot.util.EastAsianWidth;
import android.util.Log;
import de.mud.terminal.vt320;
/**
* @author Kenny Root
*/
public class Relay implements Runnable {
private static final String TAG = "ConnectBot.Relay";
private static final int BUFFER_SIZE = 4096;
private TerminalBridge bridge;
private Charset currentCharset;
private CharsetDecoder decoder;
private AbsTransport transport;
private vt320 buffer;
private ByteBuffer byteBuffer;
private CharBuffer charBuffer;
private byte[] byteArray;
private char[] charArray;
public Relay(TerminalBridge bridge, AbsTransport transport, vt320 buffer, String encoding) {
setCharset(encoding);
this.bridge = bridge;
this.transport = transport;
this.buffer = buffer;
}
public void setCharset(String encoding) {
Log.d("ConnectBot.Relay", "changing charset to " + encoding);
Charset charset;
if (encoding.equals("CP437"))
charset = new IBM437("IBM437",
new String[] { "IBM437", "CP437" });
else
charset = Charset.forName(encoding);
if (charset == currentCharset || charset == null)
return;
CharsetDecoder newCd = charset.newDecoder();
newCd.onUnmappableCharacter(CodingErrorAction.REPLACE);
newCd.onMalformedInput(CodingErrorAction.REPLACE);
currentCharset = charset;
synchronized (this) {
decoder = newCd;
}
}
public Charset getCharset() {
return currentCharset;
}
public void run() {
byteBuffer = ByteBuffer.allocate(BUFFER_SIZE);
charBuffer = CharBuffer.allocate(BUFFER_SIZE);
/* for East Asian character widths */
byte[] wideAttribute = new byte[BUFFER_SIZE];
byteArray = byteBuffer.array();
charArray = charBuffer.array();
CoderResult result;
int bytesRead = 0;
byteBuffer.limit(0);
int bytesToRead;
int offset;
int charWidth;
EastAsianWidth measurer = EastAsianWidth.getInstance();
try {
while (true) {
charWidth = bridge.charWidth;
bytesToRead = byteBuffer.capacity() - byteBuffer.limit();
offset = byteBuffer.arrayOffset() + byteBuffer.limit();
bytesRead = transport.read(byteArray, offset, bytesToRead);
if (bytesRead > 0) {
byteBuffer.limit(byteBuffer.limit() + bytesRead);
synchronized (this) {
result = decoder.decode(byteBuffer, charBuffer, false);
}
if (result.isUnderflow() &&
byteBuffer.limit() == byteBuffer.capacity()) {
byteBuffer.compact();
byteBuffer.limit(byteBuffer.position());
byteBuffer.position(0);
}
offset = charBuffer.position();
measurer.measure(charArray, 0, offset, wideAttribute, bridge.defaultPaint, charWidth);
buffer.putString(charArray, wideAttribute, 0, charBuffer.position());
bridge.propagateConsoleText(charArray, charBuffer.position());
charBuffer.clear();
bridge.redraw();
}
}
} catch (IOException e) {
Log.e(TAG, "Problem while handling incoming data in relay thread", e);
}
}
}
| Java |
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2010 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.service;
import java.io.IOException;
import org.connectbot.util.HostDatabase;
import org.connectbot.util.PreferenceConstants;
import org.connectbot.util.PubkeyDatabase;
import android.app.backup.BackupAgentHelper;
import android.app.backup.BackupDataInput;
import android.app.backup.BackupDataOutput;
import android.app.backup.FileBackupHelper;
import android.app.backup.SharedPreferencesBackupHelper;
import android.os.ParcelFileDescriptor;
import android.util.Log;
/**
* @author kroot
*
*/
public class BackupAgent extends BackupAgentHelper {
@Override
public void onCreate() {
Log.d("ConnectBot.BackupAgent", "onCreate called");
SharedPreferencesBackupHelper prefs = new SharedPreferencesBackupHelper(this, getPackageName() + "_preferences");
addHelper(PreferenceConstants.BACKUP_PREF_KEY, prefs);
FileBackupHelper hosts = new FileBackupHelper(this, "../databases/" + HostDatabase.DB_NAME);
addHelper(HostDatabase.DB_NAME, hosts);
FileBackupHelper pubkeys = new FileBackupHelper(this, "../databases/" + PubkeyDatabase.DB_NAME);
addHelper(PubkeyDatabase.DB_NAME, pubkeys);
}
@Override
public void onBackup(ParcelFileDescriptor oldState, BackupDataOutput data,
ParcelFileDescriptor newState) throws IOException {
synchronized (HostDatabase.dbLock) {
super.onBackup(oldState, data, newState);
}
}
@Override
public void onRestore(BackupDataInput data, int appVersionCode,
ParcelFileDescriptor newState) throws IOException {
Log.d("ConnectBot.BackupAgent", "onRestore called");
synchronized (HostDatabase.dbLock) {
Log.d("ConnectBot.BackupAgent", "onRestore in-lock");
super.onRestore(data, appVersionCode, newState);
}
}
}
| Java |
/*
* 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.service;
/**
* @author Kenny Root
*
*/
public interface FontSizeChangedListener {
/**
* @param size
* new font size
*/
void onFontSizeChanged(float size);
}
| Java |
/*
* 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.service;
import java.util.concurrent.Semaphore;
import android.os.Handler;
import android.os.Message;
/**
* Helps provide a relay for prompts and responses between a possible user
* interface and some underlying service.
*
* @author jsharkey
*/
public class PromptHelper {
private final Object tag;
private Handler handler = null;
private Semaphore promptToken;
private Semaphore promptResponse;
public String promptInstructions = null;
public String promptHint = null;
public Object promptRequested = null;
private Object response = null;
public PromptHelper(Object tag) {
this.tag = tag;
// Threads must acquire this before they can send a prompt.
promptToken = new Semaphore(1);
// Responses will release this semaphore.
promptResponse = new Semaphore(0);
}
/**
* Register a user interface handler, if available.
*/
public void setHandler(Handler handler) {
this.handler = handler;
}
/**
* Set an incoming value from an above user interface. Will automatically
* notify any waiting requests.
*/
public void setResponse(Object value) {
response = value;
promptRequested = null;
promptInstructions = null;
promptHint = null;
promptResponse.release();
}
/**
* Return the internal response value just before erasing and returning it.
*/
protected Object popResponse() {
Object value = response;
response = null;
return value;
}
/**
* Request a prompt response from parent. This is a blocking call until user
* interface returns a value.
* Only one thread can call this at a time. cancelPrompt() will force this to
* immediately return.
*/
private Object requestPrompt(String instructions, String hint, Object type) throws InterruptedException {
Object response = null;
promptToken.acquire();
try {
promptInstructions = instructions;
promptHint = hint;
promptRequested = type;
// notify any parent watching for live events
if (handler != null)
Message.obtain(handler, -1, tag).sendToTarget();
// acquire lock until user passes back value
promptResponse.acquire();
response = popResponse();
} finally {
promptToken.release();
}
return response;
}
/**
* Request a string response from parent. This is a blocking call until user
* interface returns a value.
* @param hint prompt hint for user to answer
* @return string user has entered
*/
public String requestStringPrompt(String instructions, String hint) {
String value = null;
try {
value = (String)this.requestPrompt(instructions, hint, String.class);
} catch(Exception e) {
}
return value;
}
/**
* Request a boolean response from parent. This is a blocking call until user
* interface returns a value.
* @param hint prompt hint for user to answer
* @return choice user has made (yes/no)
*/
public Boolean requestBooleanPrompt(String instructions, String hint) {
Boolean value = null;
try {
value = (Boolean)this.requestPrompt(instructions, hint, Boolean.class);
} catch(Exception e) {
}
return value;
}
/**
* Cancel an in-progress prompt.
*/
public void cancelPrompt() {
if (!promptToken.tryAcquire()) {
// A thread has the token, so try to interrupt it
response = null;
promptResponse.release();
} else {
// No threads have acquired the token
promptToken.release();
}
}
}
| Java |
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2010 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.service;
import java.io.IOException;
import org.connectbot.TerminalView;
import org.connectbot.bean.SelectionArea;
import org.connectbot.util.PreferenceConstants;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.Configuration;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import de.mud.terminal.VDUBuffer;
import de.mud.terminal.vt320;
/**
* @author kenny
*
*/
@SuppressWarnings("deprecation") // for ClipboardManager
public class TerminalKeyListener implements OnKeyListener, OnSharedPreferenceChangeListener {
private static final String TAG = "ConnectBot.OnKeyListener";
public final static int META_CTRL_ON = 0x01;
public final static int META_CTRL_LOCK = 0x02;
public final static int META_ALT_ON = 0x04;
public final static int META_ALT_LOCK = 0x08;
public final static int META_SHIFT_ON = 0x10;
public final static int META_SHIFT_LOCK = 0x20;
public final static int META_SLASH = 0x40;
public final static int META_TAB = 0x80;
// The bit mask of momentary and lock states for each
public final static int META_CTRL_MASK = META_CTRL_ON | META_CTRL_LOCK;
public final static int META_ALT_MASK = META_ALT_ON | META_ALT_LOCK;
public final static int META_SHIFT_MASK = META_SHIFT_ON | META_SHIFT_LOCK;
// backport constants from api level 11
public final static int KEYCODE_ESCAPE = 111;
public final static int HC_META_CTRL_ON = 4096;
// All the transient key codes
public final static int META_TRANSIENT = META_CTRL_ON | META_ALT_ON
| META_SHIFT_ON;
private final TerminalManager manager;
private final TerminalBridge bridge;
private final VDUBuffer buffer;
private String keymode = null;
private boolean hardKeyboard = false;
private int metaState = 0;
private int mDeadKey = 0;
// TODO add support for the new API.
private ClipboardManager clipboard = null;
private boolean selectingForCopy = false;
private final SelectionArea selectionArea;
private String encoding;
private final SharedPreferences prefs;
public TerminalKeyListener(TerminalManager manager,
TerminalBridge bridge,
VDUBuffer buffer,
String encoding) {
this.manager = manager;
this.bridge = bridge;
this.buffer = buffer;
this.encoding = encoding;
selectionArea = new SelectionArea();
prefs = PreferenceManager.getDefaultSharedPreferences(manager);
prefs.registerOnSharedPreferenceChangeListener(this);
hardKeyboard = (manager.res.getConfiguration().keyboard
== Configuration.KEYBOARD_QWERTY);
updateKeymode();
}
/**
* Handle onKey() events coming down from a {@link TerminalView} above us.
* Modify the keys to make more sense to a host then pass it to the transport.
*/
public boolean onKey(View v, int keyCode, KeyEvent event) {
try {
final boolean hardKeyboardHidden = manager.hardKeyboardHidden;
// Ignore all key-up events except for the special keys
if (event.getAction() == KeyEvent.ACTION_UP) {
// There's nothing here for virtual keyboard users.
if (!hardKeyboard || (hardKeyboard && hardKeyboardHidden))
return false;
// skip keys if we aren't connected yet or have been disconnected
if (bridge.isDisconnected() || bridge.transport == null)
return false;
if (PreferenceConstants.KEYMODE_RIGHT.equals(keymode)) {
if (keyCode == KeyEvent.KEYCODE_ALT_RIGHT
&& (metaState & META_SLASH) != 0) {
metaState &= ~(META_SLASH | META_TRANSIENT);
bridge.transport.write('/');
return true;
} else if (keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT
&& (metaState & META_TAB) != 0) {
metaState &= ~(META_TAB | META_TRANSIENT);
bridge.transport.write(0x09);
return true;
}
} else if (PreferenceConstants.KEYMODE_LEFT.equals(keymode)) {
if (keyCode == KeyEvent.KEYCODE_ALT_LEFT
&& (metaState & META_SLASH) != 0) {
metaState &= ~(META_SLASH | META_TRANSIENT);
bridge.transport.write('/');
return true;
} else if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
&& (metaState & META_TAB) != 0) {
metaState &= ~(META_TAB | META_TRANSIENT);
bridge.transport.write(0x09);
return true;
}
}
return false;
}
// check for terminal resizing keys
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
bridge.increaseFontSize();
return true;
} else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
bridge.decreaseFontSize();
return true;
}
// skip keys if we aren't connected yet or have been disconnected
if (bridge.isDisconnected() || bridge.transport == null)
return false;
bridge.resetScrollPosition();
if (keyCode == KeyEvent.KEYCODE_UNKNOWN &&
event.getAction() == KeyEvent.ACTION_MULTIPLE) {
byte[] input = event.getCharacters().getBytes(encoding);
bridge.transport.write(input);
return true;
}
int curMetaState = event.getMetaState();
final int orgMetaState = curMetaState;
if ((metaState & META_SHIFT_MASK) != 0) {
curMetaState |= KeyEvent.META_SHIFT_ON;
}
if ((metaState & META_ALT_MASK) != 0) {
curMetaState |= KeyEvent.META_ALT_ON;
}
int key = event.getUnicodeChar(curMetaState);
// no hard keyboard? ALT-k should pass through to below
if ((orgMetaState & KeyEvent.META_ALT_ON) != 0 &&
(!hardKeyboard || hardKeyboardHidden)) {
key = 0;
}
if ((key & KeyCharacterMap.COMBINING_ACCENT) != 0) {
mDeadKey = key & KeyCharacterMap.COMBINING_ACCENT_MASK;
return true;
}
if (mDeadKey != 0) {
key = KeyCharacterMap.getDeadChar(mDeadKey, keyCode);
mDeadKey = 0;
}
final boolean printing = (key != 0);
// otherwise pass through to existing session
// print normal keys
if (printing) {
metaState &= ~(META_SLASH | META_TAB);
// Remove shift and alt modifiers
final int lastMetaState = metaState;
metaState &= ~(META_SHIFT_ON | META_ALT_ON);
if (metaState != lastMetaState) {
bridge.redraw();
}
if ((metaState & META_CTRL_MASK) != 0) {
metaState &= ~META_CTRL_ON;
bridge.redraw();
// If there is no hard keyboard or there is a hard keyboard currently hidden,
// CTRL-1 through CTRL-9 will send F1 through F9
if ((!hardKeyboard || (hardKeyboard && hardKeyboardHidden))
&& sendFunctionKey(keyCode))
return true;
key = keyAsControl(key);
}
// handle pressing f-keys
if ((hardKeyboard && !hardKeyboardHidden)
&& (curMetaState & KeyEvent.META_SHIFT_ON) != 0
&& sendFunctionKey(keyCode))
return true;
if (key < 0x80)
bridge.transport.write(key);
else
// TODO write encoding routine that doesn't allocate each time
bridge.transport.write(new String(Character.toChars(key))
.getBytes(encoding));
return true;
}
// send ctrl and meta-keys as appropriate
if (!hardKeyboard || hardKeyboardHidden) {
int k = event.getUnicodeChar(0);
int k0 = k;
boolean sendCtrl = false;
boolean sendMeta = false;
if (k != 0) {
if ((orgMetaState & HC_META_CTRL_ON) != 0) {
k = keyAsControl(k);
if (k != k0)
sendCtrl = true;
// send F1-F10 via CTRL-1 through CTRL-0
if (!sendCtrl && sendFunctionKey(keyCode))
return true;
} else if ((orgMetaState & KeyEvent.META_ALT_ON) != 0) {
sendMeta = true;
sendEscape();
}
if (sendMeta || sendCtrl) {
bridge.transport.write(k);
return true;
}
}
}
// try handling keymode shortcuts
if (hardKeyboard && !hardKeyboardHidden &&
event.getRepeatCount() == 0) {
if (PreferenceConstants.KEYMODE_RIGHT.equals(keymode)) {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_RIGHT:
metaState |= META_SLASH;
return true;
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaState |= META_TAB;
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
metaPress(META_SHIFT_ON);
return true;
case KeyEvent.KEYCODE_ALT_LEFT:
metaPress(META_ALT_ON);
return true;
}
} else if (PreferenceConstants.KEYMODE_LEFT.equals(keymode)) {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_LEFT:
metaState |= META_SLASH;
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
metaState |= META_TAB;
return true;
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaPress(META_SHIFT_ON);
return true;
case KeyEvent.KEYCODE_ALT_RIGHT:
metaPress(META_ALT_ON);
return true;
}
} else {
switch (keyCode) {
case KeyEvent.KEYCODE_ALT_LEFT:
case KeyEvent.KEYCODE_ALT_RIGHT:
metaPress(META_ALT_ON);
return true;
case KeyEvent.KEYCODE_SHIFT_LEFT:
case KeyEvent.KEYCODE_SHIFT_RIGHT:
metaPress(META_SHIFT_ON);
return true;
}
}
}
// look for special chars
switch(keyCode) {
case KEYCODE_ESCAPE:
sendEscape();
return true;
case KeyEvent.KEYCODE_TAB:
bridge.transport.write(0x09);
return true;
case KeyEvent.KEYCODE_CAMERA:
// check to see which shortcut the camera button triggers
String camera = manager.prefs.getString(
PreferenceConstants.CAMERA,
PreferenceConstants.CAMERA_CTRLA_SPACE);
if(PreferenceConstants.CAMERA_CTRLA_SPACE.equals(camera)) {
bridge.transport.write(0x01);
bridge.transport.write(' ');
} else if(PreferenceConstants.CAMERA_CTRLA.equals(camera)) {
bridge.transport.write(0x01);
} else if(PreferenceConstants.CAMERA_ESC.equals(camera)) {
((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0);
} else if(PreferenceConstants.CAMERA_ESC_A.equals(camera)) {
((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0);
bridge.transport.write('a');
}
break;
case KeyEvent.KEYCODE_DEL:
((vt320) buffer).keyPressed(vt320.KEY_BACK_SPACE, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
return true;
case KeyEvent.KEYCODE_ENTER:
((vt320)buffer).keyTyped(vt320.KEY_ENTER, ' ', 0);
metaState &= ~META_TRANSIENT;
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
if (selectingForCopy) {
selectionArea.decrementColumn();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_LEFT, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_UP:
if (selectingForCopy) {
selectionArea.decrementRow();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_UP, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (selectingForCopy) {
selectionArea.incrementRow();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_DOWN, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (selectingForCopy) {
selectionArea.incrementColumn();
bridge.redraw();
} else {
((vt320) buffer).keyPressed(vt320.KEY_RIGHT, ' ',
getStateForBuffer());
metaState &= ~META_TRANSIENT;
bridge.tryKeyVibrate();
}
return true;
case KeyEvent.KEYCODE_DPAD_CENTER:
if (selectingForCopy) {
if (selectionArea.isSelectingOrigin())
selectionArea.finishSelectingOrigin();
else {
if (clipboard != null) {
// copy selected area to clipboard
String copiedText = selectionArea.copyFrom(buffer);
clipboard.setText(copiedText);
// XXX STOPSHIP
// manager.notifyUser(manager.getString(
// R.string.console_copy_done,
// copiedText.length()));
selectingForCopy = false;
selectionArea.reset();
}
}
} else {
if ((metaState & META_CTRL_ON) != 0) {
sendEscape();
metaState &= ~META_CTRL_ON;
} else
metaPress(META_CTRL_ON);
}
bridge.redraw();
return true;
}
} catch (IOException e) {
Log.e(TAG, "Problem while trying to handle an onKey() event", e);
try {
bridge.transport.flush();
} catch (IOException ioe) {
Log.d(TAG, "Our transport was closed, dispatching disconnect event");
bridge.dispatchDisconnect(false);
}
} catch (NullPointerException npe) {
Log.d(TAG, "Input before connection established ignored.");
return true;
}
return false;
}
public int keyAsControl(int key) {
// Support CTRL-a through CTRL-z
if (key >= 0x61 && key <= 0x7A)
key -= 0x60;
// Support CTRL-A through CTRL-_
else if (key >= 0x41 && key <= 0x5F)
key -= 0x40;
// CTRL-space sends NULL
else if (key == 0x20)
key = 0x00;
// CTRL-? sends DEL
else if (key == 0x3F)
key = 0x7F;
return key;
}
public void sendEscape() {
((vt320)buffer).keyTyped(vt320.KEY_ESCAPE, ' ', 0);
}
/**
* @param key
* @return successful
*/
private boolean sendFunctionKey(int keyCode) {
switch (keyCode) {
case KeyEvent.KEYCODE_1:
((vt320) buffer).keyPressed(vt320.KEY_F1, ' ', 0);
return true;
case KeyEvent.KEYCODE_2:
((vt320) buffer).keyPressed(vt320.KEY_F2, ' ', 0);
return true;
case KeyEvent.KEYCODE_3:
((vt320) buffer).keyPressed(vt320.KEY_F3, ' ', 0);
return true;
case KeyEvent.KEYCODE_4:
((vt320) buffer).keyPressed(vt320.KEY_F4, ' ', 0);
return true;
case KeyEvent.KEYCODE_5:
((vt320) buffer).keyPressed(vt320.KEY_F5, ' ', 0);
return true;
case KeyEvent.KEYCODE_6:
((vt320) buffer).keyPressed(vt320.KEY_F6, ' ', 0);
return true;
case KeyEvent.KEYCODE_7:
((vt320) buffer).keyPressed(vt320.KEY_F7, ' ', 0);
return true;
case KeyEvent.KEYCODE_8:
((vt320) buffer).keyPressed(vt320.KEY_F8, ' ', 0);
return true;
case KeyEvent.KEYCODE_9:
((vt320) buffer).keyPressed(vt320.KEY_F9, ' ', 0);
return true;
case KeyEvent.KEYCODE_0:
((vt320) buffer).keyPressed(vt320.KEY_F10, ' ', 0);
return true;
default:
return false;
}
}
/**
* Handle meta key presses where the key can be locked on.
* <p>
* 1st press: next key to have meta state<br />
* 2nd press: meta state is locked on<br />
* 3rd press: disable meta state
*
* @param code
*/
public void metaPress(int code) {
if ((metaState & (code << 1)) != 0) {
metaState &= ~(code << 1);
} else if ((metaState & code) != 0) {
metaState &= ~code;
metaState |= code << 1;
} else
metaState |= code;
bridge.redraw();
}
public void setTerminalKeyMode(String keymode) {
this.keymode = keymode;
}
private int getStateForBuffer() {
int bufferState = 0;
if ((metaState & META_CTRL_MASK) != 0)
bufferState |= vt320.KEY_CONTROL;
if ((metaState & META_SHIFT_MASK) != 0)
bufferState |= vt320.KEY_SHIFT;
if ((metaState & META_ALT_MASK) != 0)
bufferState |= vt320.KEY_ALT;
return bufferState;
}
public int getMetaState() {
return metaState;
}
public int getDeadKey() {
return mDeadKey;
}
public void setClipboardManager(ClipboardManager clipboard) {
this.clipboard = clipboard;
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (PreferenceConstants.KEYMODE.equals(key)) {
updateKeymode();
}
}
private void updateKeymode() {
keymode = prefs.getString(PreferenceConstants.KEYMODE, PreferenceConstants.KEYMODE_RIGHT);
}
public void setCharset(String encoding) {
this.encoding = encoding;
}
}
| Java |
/*
* 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.service;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.security.PrivateKey;
import java.security.PublicKey;
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.Timer;
import java.util.TimerTask;
import org.connectbot.R;
import org.connectbot.bean.HostBean;
import org.connectbot.bean.PubkeyBean;
import org.connectbot.transport.TransportFactory;
import org.connectbot.util.HostDatabase;
import org.connectbot.util.PreferenceConstants;
import org.connectbot.util.PubkeyDatabase;
import org.connectbot.util.PubkeyUtils;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.res.AssetFileDescriptor;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
/**
* Manager for SSH connections that runs as a service. This service holds a list
* of currently connected SSH bridges that are ready for connection up to a GUI
* if needed.
*
* @author jsharkey
*/
public class TerminalManager extends Service implements BridgeDisconnectedListener, OnSharedPreferenceChangeListener {
public final static String TAG = "ConnectBot.TerminalManager";
public List<TerminalBridge> bridges = new LinkedList<TerminalBridge>();
public Map<HostBean, WeakReference<TerminalBridge>> mHostBridgeMap =
new HashMap<HostBean, WeakReference<TerminalBridge>>();
public Map<String, WeakReference<TerminalBridge>> mNicknameBridgeMap =
new HashMap<String, WeakReference<TerminalBridge>>();
public TerminalBridge defaultBridge = null;
public List<HostBean> disconnected = new LinkedList<HostBean>();
public Handler disconnectHandler = null;
public Map<String, KeyHolder> loadedKeypairs = new HashMap<String, KeyHolder>();
public Resources res;
public HostDatabase hostdb;
public PubkeyDatabase pubkeydb;
protected SharedPreferences prefs;
final private IBinder binder = new TerminalBinder();
private ConnectivityReceiver connectivityManager;
private MediaPlayer mediaPlayer;
private Timer pubkeyTimer;
private Timer idleTimer;
private final long IDLE_TIMEOUT = 300000; // 5 minutes
private Vibrator vibrator;
private volatile boolean wantKeyVibration;
public static final long VIBRATE_DURATION = 30;
private boolean wantBellVibration;
private boolean resizeAllowed = true;
private boolean savingKeys;
protected List<WeakReference<TerminalBridge>> mPendingReconnect
= new LinkedList<WeakReference<TerminalBridge>>();
public boolean hardKeyboardHidden;
@Override
public void onCreate() {
Log.i(TAG, "Starting service");
prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.registerOnSharedPreferenceChangeListener(this);
res = getResources();
pubkeyTimer = new Timer("pubkeyTimer", true);
hostdb = new HostDatabase(this);
pubkeydb = new PubkeyDatabase(this);
// load all marked pubkeys into memory
updateSavingKeys();
List<PubkeyBean> pubkeys = pubkeydb.getAllStartPubkeys();
for (PubkeyBean pubkey : pubkeys) {
try {
PrivateKey privKey = PubkeyUtils.decodePrivate(pubkey.getPrivateKey(), pubkey.getType());
PublicKey pubKey = pubkey.getPublicKey();
Object trileadKey = PubkeyUtils.convertToTrilead(privKey, pubKey);
addKey(pubkey, trileadKey);
} catch (Exception e) {
Log.d(TAG, String.format("Problem adding key '%s' to in-memory cache", pubkey.getNickname()), e);
}
}
vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
wantKeyVibration = prefs.getBoolean(PreferenceConstants.BUMPY_ARROWS, true);
wantBellVibration = prefs.getBoolean(PreferenceConstants.BELL_VIBRATE, true);
enableMediaPlayer();
hardKeyboardHidden = (res.getConfiguration().hardKeyboardHidden ==
Configuration.HARDKEYBOARDHIDDEN_YES);
final boolean lockingWifi = prefs.getBoolean(PreferenceConstants.WIFI_LOCK, true);
connectivityManager = new ConnectivityReceiver(this, lockingWifi);
}
private void updateSavingKeys() {
savingKeys = prefs.getBoolean(PreferenceConstants.MEMKEYS, true);
}
@Override
public void onDestroy() {
Log.i(TAG, "Destroying service");
disconnectAll(true);
if(hostdb != null) {
hostdb.close();
hostdb = null;
}
if(pubkeydb != null) {
pubkeydb.close();
pubkeydb = null;
}
synchronized (this) {
if (idleTimer != null)
idleTimer.cancel();
if (pubkeyTimer != null)
pubkeyTimer.cancel();
}
connectivityManager.cleanup();
ConnectionNotifier.getInstance().hideRunningNotification(this);
disableMediaPlayer();
}
/**
* Disconnect all currently connected bridges.
*/
private void disconnectAll(final boolean immediate) {
TerminalBridge[] tmpBridges = null;
synchronized (bridges) {
if (bridges.size() > 0) {
tmpBridges = bridges.toArray(new TerminalBridge[bridges.size()]);
}
}
if (tmpBridges != null) {
// disconnect and dispose of any existing bridges
for (int i = 0; i < tmpBridges.length; i++)
tmpBridges[i].dispatchDisconnect(immediate);
}
}
/**
* Open a new SSH session using the given parameters.
*/
private TerminalBridge openConnection(HostBean host) throws IllegalArgumentException, IOException {
// throw exception if terminal already open
if (getConnectedBridge(host) != null) {
throw new IllegalArgumentException("Connection already open for that nickname");
}
TerminalBridge bridge = new TerminalBridge(this, host);
bridge.setOnDisconnectedListener(this);
bridge.startConnection();
synchronized (bridges) {
bridges.add(bridge);
WeakReference<TerminalBridge> wr = new WeakReference<TerminalBridge>(bridge);
mHostBridgeMap.put(bridge.host, wr);
mNicknameBridgeMap.put(bridge.host.getNickname(), wr);
}
synchronized (disconnected) {
disconnected.remove(bridge.host);
}
if (bridge.isUsingNetwork()) {
connectivityManager.incRef();
}
if (prefs.getBoolean(PreferenceConstants.CONNECTION_PERSIST, true)) {
ConnectionNotifier.getInstance().showRunningNotification(this);
}
// also update database with new connected time
touchHost(host);
return bridge;
}
public String getEmulation() {
return prefs.getString(PreferenceConstants.EMULATION, "screen");
}
public int getScrollback() {
int scrollback = 140;
try {
scrollback = Integer.parseInt(prefs.getString(PreferenceConstants.SCROLLBACK, "140"));
} catch(Exception e) {
}
return scrollback;
}
/**
* Open a new connection by reading parameters from the given URI. Follows
* format specified by an individual transport.
*/
public TerminalBridge openConnection(Uri uri) throws Exception {
HostBean host = TransportFactory.findHost(hostdb, uri);
if (host == null)
host = TransportFactory.getTransport(uri.getScheme()).createHost(uri);
return openConnection(host);
}
/**
* Update the last-connected value for the given nickname by passing through
* to {@link HostDatabase}.
*/
private void touchHost(HostBean host) {
hostdb.touchHost(host);
}
/**
* Find a connected {@link TerminalBridge} with the given HostBean.
*
* @param host the HostBean to search for
* @return TerminalBridge that uses the HostBean
*/
public TerminalBridge getConnectedBridge(HostBean host) {
WeakReference<TerminalBridge> wr = mHostBridgeMap.get(host);
if (wr != null) {
return wr.get();
} else {
return null;
}
}
/**
* Find a connected {@link TerminalBridge} using its nickname.
*
* @param nickname
* @return TerminalBridge that matches nickname
*/
public TerminalBridge getConnectedBridge(final String nickname) {
if (nickname == null) {
return null;
}
WeakReference<TerminalBridge> wr = mNicknameBridgeMap.get(nickname);
if (wr != null) {
return wr.get();
} else {
return null;
}
}
/**
* Called by child bridge when somehow it's been disconnected.
*/
public void onDisconnected(TerminalBridge bridge) {
boolean shouldHideRunningNotification = false;
synchronized (bridges) {
// remove this bridge from our list
bridges.remove(bridge);
mHostBridgeMap.remove(bridge.host);
mNicknameBridgeMap.remove(bridge.host.getNickname());
if (bridge.isUsingNetwork()) {
connectivityManager.decRef();
}
if (bridges.size() == 0 &&
mPendingReconnect.size() == 0) {
shouldHideRunningNotification = true;
}
}
synchronized (disconnected) {
disconnected.add(bridge.host);
}
if (shouldHideRunningNotification) {
ConnectionNotifier.getInstance().hideRunningNotification(this);
}
// pass notification back up to gui
if (disconnectHandler != null)
Message.obtain(disconnectHandler, -1, bridge).sendToTarget();
}
public boolean isKeyLoaded(String nickname) {
return loadedKeypairs.containsKey(nickname);
}
public void addKey(PubkeyBean pubkey, Object trileadKey) {
addKey(pubkey, trileadKey, false);
}
public void addKey(PubkeyBean pubkey, Object trileadKey, boolean force) {
if (!savingKeys && !force)
return;
removeKey(pubkey.getNickname());
byte[] sshPubKey = PubkeyUtils.extractOpenSSHPublic(trileadKey);
KeyHolder keyHolder = new KeyHolder();
keyHolder.bean = pubkey;
keyHolder.trileadKey = trileadKey;
keyHolder.openSSHPubkey = sshPubKey;
loadedKeypairs.put(pubkey.getNickname(), keyHolder);
if (pubkey.getLifetime() > 0) {
final String nickname = pubkey.getNickname();
pubkeyTimer.schedule(new TimerTask() {
@Override
public void run() {
Log.d(TAG, "Unloading from memory key: " + nickname);
removeKey(nickname);
}
}, pubkey.getLifetime() * 1000);
}
Log.d(TAG, String.format("Added key '%s' to in-memory cache", pubkey.getNickname()));
}
public boolean removeKey(String nickname) {
Log.d(TAG, String.format("Removed key '%s' to in-memory cache", nickname));
return loadedKeypairs.remove(nickname) != null;
}
public boolean removeKey(byte[] publicKey) {
String nickname = null;
for (Entry<String,KeyHolder> entry : loadedKeypairs.entrySet()) {
if (Arrays.equals(entry.getValue().openSSHPubkey, publicKey)) {
nickname = entry.getKey();
break;
}
}
if (nickname != null) {
Log.d(TAG, String.format("Removed key '%s' to in-memory cache", nickname));
return removeKey(nickname);
} else
return false;
}
public Object getKey(String nickname) {
if (loadedKeypairs.containsKey(nickname)) {
KeyHolder keyHolder = loadedKeypairs.get(nickname);
return keyHolder.trileadKey;
} else
return null;
}
public Object getKey(byte[] publicKey) {
for (KeyHolder keyHolder : loadedKeypairs.values()) {
if (Arrays.equals(keyHolder.openSSHPubkey, publicKey))
return keyHolder.trileadKey;
}
return null;
}
public String getKeyNickname(byte[] publicKey) {
for (Entry<String,KeyHolder> entry : loadedKeypairs.entrySet()) {
if (Arrays.equals(entry.getValue().openSSHPubkey, publicKey))
return entry.getKey();
}
return null;
}
private void stopWithDelay() {
// TODO add in a way to check whether keys loaded are encrypted and only
// set timer when we have an encrypted key loaded
if (loadedKeypairs.size() > 0) {
synchronized (this) {
if (idleTimer == null)
idleTimer = new Timer("idleTimer", true);
idleTimer.schedule(new IdleTask(), IDLE_TIMEOUT);
}
} else {
Log.d(TAG, "Stopping service immediately");
stopSelf();
}
}
protected void stopNow() {
if (bridges.size() == 0) {
stopSelf();
}
}
private synchronized void stopIdleTimer() {
if (idleTimer != null) {
idleTimer.cancel();
idleTimer = null;
}
}
public class TerminalBinder extends Binder {
public TerminalManager getService() {
return TerminalManager.this;
}
}
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "Someone bound to TerminalManager");
setResizeAllowed(true);
stopIdleTimer();
// Make sure we stay running to maintain the bridges
startService(new Intent(this, TerminalManager.class));
return binder;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
/*
* We want this service to continue running until it is explicitly
* stopped, so return sticky.
*/
return START_STICKY;
}
@Override
public void onRebind(Intent intent) {
super.onRebind(intent);
setResizeAllowed(true);
Log.i(TAG, "Someone rebound to TerminalManager");
stopIdleTimer();
}
@Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "Someone unbound from TerminalManager");
setResizeAllowed(true);
if (bridges.size() == 0) {
stopWithDelay();
}
return true;
}
private class IdleTask extends TimerTask {
/* (non-Javadoc)
* @see java.util.TimerTask#run()
*/
@Override
public void run() {
Log.d(TAG, String.format("Stopping service after timeout of ~%d seconds", IDLE_TIMEOUT / 1000));
TerminalManager.this.stopNow();
}
}
public void tryKeyVibrate() {
if (wantKeyVibration)
vibrate();
}
private void vibrate() {
if (vibrator != null)
vibrator.vibrate(VIBRATE_DURATION);
}
private void enableMediaPlayer() {
mediaPlayer = new MediaPlayer();
float volume = prefs.getFloat(PreferenceConstants.BELL_VOLUME,
PreferenceConstants.DEFAULT_BELL_VOLUME);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_NOTIFICATION);
mediaPlayer.setOnCompletionListener(new BeepListener());
AssetFileDescriptor file = res.openRawResourceFd(R.raw.bell);
try {
mediaPlayer.setDataSource(file.getFileDescriptor(), file
.getStartOffset(), file.getLength());
file.close();
mediaPlayer.setVolume(volume, volume);
mediaPlayer.prepare();
} catch (IOException e) {
Log.e(TAG, "Error setting up bell media player", e);
}
}
private void disableMediaPlayer() {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
public void playBeep() {
if (mediaPlayer != null)
mediaPlayer.start();
if (wantBellVibration)
vibrate();
}
private static class BeepListener implements OnCompletionListener {
public void onCompletion(MediaPlayer mp) {
mp.seekTo(0);
}
}
/**
* Send system notification to user for a certain host. When user selects
* the notification, it will bring them directly to the ConsoleActivity
* displaying the host.
*
* @param host
*/
public void sendActivityNotification(HostBean host) {
if (!prefs.getBoolean(PreferenceConstants.BELL_NOTIFICATION, false))
return;
ConnectionNotifier.getInstance().showActivityNotification(this, host);
}
/* (non-Javadoc)
* @see android.content.SharedPreferences.OnSharedPreferenceChangeListener#onSharedPreferenceChanged(android.content.SharedPreferences, java.lang.String)
*/
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (PreferenceConstants.BELL.equals(key)) {
boolean wantAudible = sharedPreferences.getBoolean(
PreferenceConstants.BELL, true);
if (wantAudible && mediaPlayer == null)
enableMediaPlayer();
else if (!wantAudible && mediaPlayer != null)
disableMediaPlayer();
} else if (PreferenceConstants.BELL_VOLUME.equals(key)) {
if (mediaPlayer != null) {
float volume = sharedPreferences.getFloat(
PreferenceConstants.BELL_VOLUME,
PreferenceConstants.DEFAULT_BELL_VOLUME);
mediaPlayer.setVolume(volume, volume);
}
} else if (PreferenceConstants.BELL_VIBRATE.equals(key)) {
wantBellVibration = sharedPreferences.getBoolean(
PreferenceConstants.BELL_VIBRATE, true);
} else if (PreferenceConstants.BUMPY_ARROWS.equals(key)) {
wantKeyVibration = sharedPreferences.getBoolean(
PreferenceConstants.BUMPY_ARROWS, true);
} else if (PreferenceConstants.WIFI_LOCK.equals(key)) {
final boolean lockingWifi = prefs.getBoolean(PreferenceConstants.WIFI_LOCK, true);
connectivityManager.setWantWifiLock(lockingWifi);
} else if (PreferenceConstants.MEMKEYS.equals(key)) {
updateSavingKeys();
}
}
/**
* Allow {@link TerminalBridge} to resize when the parent has changed.
* @param resizeAllowed
*/
public void setResizeAllowed(boolean resizeAllowed) {
this.resizeAllowed = resizeAllowed;
}
public boolean isResizeAllowed() {
return resizeAllowed;
}
public static class KeyHolder {
public PubkeyBean bean;
public Object trileadKey;
public byte[] openSSHPubkey;
}
/**
* Called when connectivity to the network is lost and it doesn't appear
* we'll be getting a different connection any time soon.
*/
public void onConnectivityLost() {
final Thread t = new Thread() {
@Override
public void run() {
disconnectAll(false);
}
};
t.setName("Disconnector");
t.start();
}
/**
* Called when connectivity to the network is restored.
*/
public void onConnectivityRestored() {
final Thread t = new Thread() {
@Override
public void run() {
reconnectPending();
}
};
t.setName("Reconnector");
t.start();
}
/**
* Insert request into reconnect queue to be executed either immediately
* or later when connectivity is restored depending on whether we're
* currently connected.
*
* @param bridge the TerminalBridge to reconnect when possible
*/
public void requestReconnect(TerminalBridge bridge) {
synchronized (mPendingReconnect) {
mPendingReconnect.add(new WeakReference<TerminalBridge>(bridge));
if (!bridge.isUsingNetwork() ||
connectivityManager.isConnected()) {
reconnectPending();
}
}
}
/**
* Reconnect all bridges that were pending a reconnect when connectivity
* was lost.
*/
private void reconnectPending() {
synchronized (mPendingReconnect) {
for (WeakReference<TerminalBridge> ref : mPendingReconnect) {
TerminalBridge bridge = ref.get();
if (bridge == null) {
continue;
}
bridge.startConnection();
}
mPendingReconnect.clear();
}
}
}
| Java |
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2010 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.service;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.connectbot.ConsoleActivity;
import org.connectbot.R;
import org.connectbot.bean.HostBean;
import org.connectbot.util.HostDatabase;
import org.connectbot.util.PreferenceConstants;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
/**
* @author Kenny Root
*
* Based on the concept from jasta's blog post.
*/
public abstract class ConnectionNotifier {
private static final int ONLINE_NOTIFICATION = 1;
private static final int ACTIVITY_NOTIFICATION = 2;
public static ConnectionNotifier getInstance() {
if (PreferenceConstants.PRE_ECLAIR)
return PreEclair.Holder.sInstance;
else
return EclairAndBeyond.Holder.sInstance;
}
protected NotificationManager getNotificationManager(Context context) {
return (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
}
protected Notification newNotification(Context context) {
Notification notification = new Notification();
notification.icon = R.drawable.notification_icon;
notification.when = System.currentTimeMillis();
return notification;
}
protected Notification newActivityNotification(Context context, HostBean host) {
Notification notification = newNotification(context);
Resources res = context.getResources();
String contentText = res.getString(
R.string.notification_text, host.getNickname());
Intent notificationIntent = new Intent(context, ConsoleActivity.class);
notificationIntent.setAction("android.intent.action.VIEW");
notificationIntent.setData(host.getUri());
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, res.getString(R.string.app_name), contentText, contentIntent);
notification.flags = Notification.FLAG_AUTO_CANCEL;
notification.flags |= Notification.DEFAULT_LIGHTS;
if (HostDatabase.COLOR_RED.equals(host.getColor()))
notification.ledARGB = Color.RED;
else if (HostDatabase.COLOR_GREEN.equals(host.getColor()))
notification.ledARGB = Color.GREEN;
else if (HostDatabase.COLOR_BLUE.equals(host.getColor()))
notification.ledARGB = Color.BLUE;
else
notification.ledARGB = Color.WHITE;
notification.ledOnMS = 300;
notification.ledOffMS = 1000;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
return notification;
}
protected Notification newRunningNotification(Context context) {
Notification notification = newNotification(context);
notification.flags = Notification.FLAG_ONGOING_EVENT
| Notification.FLAG_NO_CLEAR;
notification.when = 0;
notification.contentIntent = PendingIntent.getActivity(context,
ONLINE_NOTIFICATION,
new Intent(context, ConsoleActivity.class), 0);
Resources res = context.getResources();
notification.setLatestEventInfo(context,
res.getString(R.string.app_name),
res.getString(R.string.app_is_running),
notification.contentIntent);
return notification;
}
public void showActivityNotification(Service context, HostBean host) {
getNotificationManager(context).notify(ACTIVITY_NOTIFICATION, newActivityNotification(context, host));
}
public void hideActivityNotification(Service context) {
getNotificationManager(context).cancel(ACTIVITY_NOTIFICATION);
}
public abstract void showRunningNotification(Service context);
public abstract void hideRunningNotification(Service context);
private static class PreEclair extends ConnectionNotifier {
private static final Class<?>[] setForegroundSignature = new Class[] {boolean.class};
private Method setForeground = null;
private static class Holder {
private static final PreEclair sInstance = new PreEclair();
}
public PreEclair() {
try {
setForeground = Service.class.getMethod("setForeground", setForegroundSignature);
} catch (Exception e) {
}
}
@Override
public void showRunningNotification(Service context) {
if (setForeground != null) {
Object[] setForegroundArgs = new Object[1];
setForegroundArgs[0] = Boolean.TRUE;
try {
setForeground.invoke(context, setForegroundArgs);
} catch (InvocationTargetException e) {
} catch (IllegalAccessException e) {
}
getNotificationManager(context).notify(ONLINE_NOTIFICATION, newRunningNotification(context));
}
}
@Override
public void hideRunningNotification(Service context) {
if (setForeground != null) {
Object[] setForegroundArgs = new Object[1];
setForegroundArgs[0] = Boolean.FALSE;
try {
setForeground.invoke(context, setForegroundArgs);
} catch (InvocationTargetException e) {
} catch (IllegalAccessException e) {
}
getNotificationManager(context).cancel(ONLINE_NOTIFICATION);
}
}
}
private static class EclairAndBeyond extends ConnectionNotifier {
private static class Holder {
private static final EclairAndBeyond sInstance = new EclairAndBeyond();
}
@Override
public void showRunningNotification(Service context) {
context.startForeground(ONLINE_NOTIFICATION, newRunningNotification(context));
}
@Override
public void hideRunningNotification(Service context) {
context.stopForeground(true);
}
}
}
| Java |
/*
* 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.service;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.connectbot.R;
import org.connectbot.TerminalView;
import org.connectbot.bean.HostBean;
import org.connectbot.bean.PortForwardBean;
import org.connectbot.bean.SelectionArea;
import org.connectbot.transport.AbsTransport;
import org.connectbot.transport.TransportFactory;
import org.connectbot.util.HostDatabase;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.graphics.Typeface;
import android.text.ClipboardManager;
import android.util.Log;
import de.mud.terminal.VDUBuffer;
import de.mud.terminal.VDUDisplay;
import de.mud.terminal.vt320;
/**
* Provides a bridge between a MUD terminal buffer and a possible TerminalView.
* This separation allows us to keep the TerminalBridge running in a background
* service. A TerminalView shares down a bitmap that we can use for rendering
* when available.
*
* This class also provides SSH hostkey verification prompting, and password
* prompting.
*/
@SuppressWarnings("deprecation") // for ClipboardManager
public class TerminalBridge implements VDUDisplay {
public final static String TAG = "ConnectBot.TerminalBridge";
public final static int DEFAULT_FONT_SIZE = 10;
private final static int FONT_SIZE_STEP = 2;
public Integer[] color;
public int defaultFg = HostDatabase.DEFAULT_FG_COLOR;
public int defaultBg = HostDatabase.DEFAULT_BG_COLOR;
protected final TerminalManager manager;
public HostBean host;
/* package */ AbsTransport transport;
final Paint defaultPaint;
private Relay relay;
private final String emulation;
private final int scrollback;
public Bitmap bitmap = null;
public VDUBuffer buffer = null;
private TerminalView parent = null;
private final Canvas canvas = new Canvas();
private boolean disconnected = false;
private boolean awaitingClose = false;
private boolean forcedSize = false;
private int columns;
private int rows;
/* package */ final TerminalKeyListener keyListener;
private boolean selectingForCopy = false;
private final SelectionArea selectionArea;
// TODO add support for the new clipboard API
private ClipboardManager clipboard;
public int charWidth = -1;
public int charHeight = -1;
private int charTop = -1;
private float fontSize = -1;
private final List<FontSizeChangedListener> fontSizeChangedListeners;
private final List<String> localOutput;
/**
* Flag indicating if we should perform a full-screen redraw during our next
* rendering pass.
*/
private boolean fullRedraw = false;
public PromptHelper promptHelper;
protected BridgeDisconnectedListener disconnectListener = null;
/**
* Create a new terminal bridge suitable for unit testing.
*/
public TerminalBridge() {
buffer = new vt320() {
@Override
public void write(byte[] b) {}
@Override
public void write(int b) {}
@Override
public void sendTelnetCommand(byte cmd) {}
@Override
public void setWindowSize(int c, int r) {}
@Override
public void debug(String s) {}
};
emulation = null;
manager = null;
defaultPaint = new Paint();
selectionArea = new SelectionArea();
scrollback = 1;
localOutput = new LinkedList<String>();
fontSizeChangedListeners = new LinkedList<FontSizeChangedListener>();
transport = null;
keyListener = new TerminalKeyListener(manager, this, buffer, null);
}
/**
* Create new terminal bridge with following parameters. We will immediately
* launch thread to start SSH connection and handle any hostkey verification
* and password authentication.
*/
public TerminalBridge(final TerminalManager manager, final HostBean host) throws IOException {
this.manager = manager;
this.host = host;
emulation = manager.getEmulation();
scrollback = manager.getScrollback();
// create prompt helper to relay password and hostkey requests up to gui
promptHelper = new PromptHelper(this);
// create our default paint
defaultPaint = new Paint();
defaultPaint.setAntiAlias(true);
defaultPaint.setTypeface(Typeface.MONOSPACE);
defaultPaint.setFakeBoldText(true); // more readable?
localOutput = new LinkedList<String>();
fontSizeChangedListeners = new LinkedList<FontSizeChangedListener>();
int hostFontSize = host.getFontSize();
if (hostFontSize <= 0)
hostFontSize = DEFAULT_FONT_SIZE;
setFontSize(hostFontSize);
// create terminal buffer and handle outgoing data
// this is probably status reply information
buffer = new vt320() {
@Override
public void debug(String s) {
Log.d(TAG, s);
}
@Override
public void write(byte[] b) {
try {
if (b != null && transport != null)
transport.write(b);
} catch (IOException e) {
Log.e(TAG, "Problem writing outgoing data in vt320() thread", e);
}
}
@Override
public void write(int b) {
try {
if (transport != null)
transport.write(b);
} catch (IOException e) {
Log.e(TAG, "Problem writing outgoing data in vt320() thread", e);
}
}
// We don't use telnet sequences.
@Override
public void sendTelnetCommand(byte cmd) {
}
// We don't want remote to resize our window.
@Override
public void setWindowSize(int c, int r) {
}
@Override
public void beep() {
if (parent.isShown())
manager.playBeep();
else
manager.sendActivityNotification(host);
}
};
// Don't keep any scrollback if a session is not being opened.
if (host.getWantSession())
buffer.setBufferSize(scrollback);
else
buffer.setBufferSize(0);
resetColors();
buffer.setDisplay(this);
selectionArea = new SelectionArea();
keyListener = new TerminalKeyListener(manager, this, buffer, host.getEncoding());
}
public PromptHelper getPromptHelper() {
return promptHelper;
}
/**
* Spawn thread to open connection and start login process.
*/
protected void startConnection() {
transport = TransportFactory.getTransport(host.getProtocol());
transport.setBridge(this);
transport.setManager(manager);
transport.setHost(host);
// TODO make this more abstract so we don't litter on AbsTransport
transport.setCompression(host.getCompression());
transport.setUseAuthAgent(host.getUseAuthAgent());
transport.setEmulation(emulation);
if (transport.canForwardPorts()) {
for (PortForwardBean portForward : manager.hostdb.getPortForwardsForHost(host))
transport.addPortForward(portForward);
}
outputLine(manager.res.getString(R.string.terminal_connecting, host.getHostname(), host.getPort(), host.getProtocol()));
Thread connectionThread = new Thread(new Runnable() {
public void run() {
transport.connect();
}
});
connectionThread.setName("Connection");
connectionThread.setDaemon(true);
connectionThread.start();
}
/**
* Handle challenges from keyboard-interactive authentication mode.
*/
public String[] replyToChallenge(String name, String instruction, int numPrompts, String[] prompt, boolean[] echo) {
String[] responses = new String[numPrompts];
for(int i = 0; i < numPrompts; i++) {
// request response from user for each prompt
responses[i] = promptHelper.requestStringPrompt(instruction, prompt[i]);
}
return responses;
}
/**
* @return charset in use by bridge
*/
public Charset getCharset() {
return relay.getCharset();
}
/**
* Sets the encoding used by the terminal. If the connection is live,
* then the character set is changed for the next read.
* @param encoding the canonical name of the character encoding
*/
public void setCharset(String encoding) {
if (relay != null)
relay.setCharset(encoding);
keyListener.setCharset(encoding);
}
/**
* Convenience method for writing a line into the underlying MUD buffer.
* Should never be called once the session is established.
*/
public final void outputLine(String line) {
if (transport != null && transport.isSessionOpen())
Log.e(TAG, "Session established, cannot use outputLine!", new IOException("outputLine call traceback"));
synchronized (localOutput) {
final String s = line + "\r\n";
localOutput.add(s);
((vt320) buffer).putString(s);
// For accessibility
final char[] charArray = s.toCharArray();
propagateConsoleText(charArray, charArray.length);
}
}
/**
* Inject a specific string into this terminal. Used for post-login strings
* and pasting clipboard.
*/
public void injectString(final String string) {
if (string == null || string.length() == 0)
return;
Thread injectStringThread = new Thread(new Runnable() {
public void run() {
try {
transport.write(string.getBytes(host.getEncoding()));
} catch (Exception e) {
Log.e(TAG, "Couldn't inject string to remote host: ", e);
}
}
});
injectStringThread.setName("InjectString");
injectStringThread.start();
}
/**
* Internal method to request actual PTY terminal once we've finished
* authentication. If called before authenticated, it will just fail.
*/
public void onConnected() {
disconnected = false;
((vt320) buffer).reset();
// We no longer need our local output.
localOutput.clear();
// previously tried vt100 and xterm for emulation modes
// "screen" works the best for color and escape codes
((vt320) buffer).setAnswerBack(emulation);
if (HostDatabase.DELKEY_BACKSPACE.equals(host.getDelKey()))
((vt320) buffer).setBackspace(vt320.DELETE_IS_BACKSPACE);
else
((vt320) buffer).setBackspace(vt320.DELETE_IS_DEL);
// create thread to relay incoming connection data to buffer
relay = new Relay(this, transport, (vt320) buffer, host.getEncoding());
Thread relayThread = new Thread(relay);
relayThread.setDaemon(true);
relayThread.setName("Relay");
relayThread.start();
// force font-size to make sure we resizePTY as needed
setFontSize(fontSize);
// finally send any post-login string, if requested
injectString(host.getPostLogin());
}
/**
* @return whether a session is open or not
*/
public boolean isSessionOpen() {
if (transport != null)
return transport.isSessionOpen();
return false;
}
public void setOnDisconnectedListener(BridgeDisconnectedListener disconnectListener) {
this.disconnectListener = disconnectListener;
}
/**
* Force disconnection of this terminal bridge.
*/
public void dispatchDisconnect(boolean immediate) {
// We don't need to do this multiple times.
synchronized (this) {
if (disconnected && !immediate)
return;
disconnected = true;
}
// Cancel any pending prompts.
promptHelper.cancelPrompt();
// disconnection request hangs if we havent really connected to a host yet
// temporary fix is to just spawn disconnection into a thread
Thread disconnectThread = new Thread(new Runnable() {
public void run() {
if (transport != null && transport.isConnected())
transport.close();
}
});
disconnectThread.setName("Disconnect");
disconnectThread.start();
if (immediate) {
awaitingClose = true;
if (disconnectListener != null)
disconnectListener.onDisconnected(TerminalBridge.this);
} else {
{
final String line = manager.res.getString(R.string.alert_disconnect_msg);
((vt320) buffer).putString("\r\n" + line + "\r\n");
}
if (host.getStayConnected()) {
manager.requestReconnect(this);
return;
}
Thread disconnectPromptThread = new Thread(new Runnable() {
public void run() {
Boolean result = promptHelper.requestBooleanPrompt(null,
manager.res.getString(R.string.prompt_host_disconnected));
if (result == null || result.booleanValue()) {
awaitingClose = true;
// Tell the TerminalManager that we can be destroyed now.
if (disconnectListener != null)
disconnectListener.onDisconnected(TerminalBridge.this);
}
}
});
disconnectPromptThread.setName("DisconnectPrompt");
disconnectPromptThread.setDaemon(true);
disconnectPromptThread.start();
}
}
public void setSelectingForCopy(boolean selectingForCopy) {
this.selectingForCopy = selectingForCopy;
}
public boolean isSelectingForCopy() {
return selectingForCopy;
}
public SelectionArea getSelectionArea() {
return selectionArea;
}
public synchronized void tryKeyVibrate() {
manager.tryKeyVibrate();
}
/**
* Request a different font size. Will make call to parentChanged() to make
* sure we resize PTY if needed.
*/
/* package */ final void setFontSize(float size) {
if (size <= 0.0)
return;
defaultPaint.setTextSize(size);
fontSize = size;
// read new metrics to get exact pixel dimensions
FontMetrics fm = defaultPaint.getFontMetrics();
charTop = (int)Math.ceil(fm.top);
float[] widths = new float[1];
defaultPaint.getTextWidths("X", widths);
charWidth = (int)Math.ceil(widths[0]);
charHeight = (int)Math.ceil(fm.descent - fm.top);
// refresh any bitmap with new font size
if(parent != null)
parentChanged(parent);
for (FontSizeChangedListener ofscl : fontSizeChangedListeners)
ofscl.onFontSizeChanged(size);
host.setFontSize((int) fontSize);
manager.hostdb.updateFontSize(host);
forcedSize = false;
}
/**
* Add an {@link FontSizeChangedListener} to the list of listeners for this
* bridge.
*
* @param listener
* listener to add
*/
public void addFontSizeChangedListener(FontSizeChangedListener listener) {
fontSizeChangedListeners.add(listener);
}
/**
* Remove an {@link FontSizeChangedListener} from the list of listeners for
* this bridge.
*
* @param listener
*/
public void removeFontSizeChangedListener(FontSizeChangedListener listener) {
fontSizeChangedListeners.remove(listener);
}
/**
* Something changed in our parent {@link TerminalView}, maybe it's a new
* parent, or maybe it's an updated font size. We should recalculate
* terminal size information and request a PTY resize.
*/
public final synchronized void parentChanged(TerminalView parent) {
if (manager != null && !manager.isResizeAllowed()) {
Log.d(TAG, "Resize is not allowed now");
return;
}
this.parent = parent;
final int width = parent.getWidth();
final int height = parent.getHeight();
// Something has gone wrong with our layout; we're 0 width or height!
if (width <= 0 || height <= 0)
return;
clipboard = (ClipboardManager) parent.getContext().getSystemService(Context.CLIPBOARD_SERVICE);
keyListener.setClipboardManager(clipboard);
if (!forcedSize) {
// recalculate buffer size
int newColumns, newRows;
newColumns = width / charWidth;
newRows = height / charHeight;
// If nothing has changed in the terminal dimensions and not an intial
// draw then don't blow away scroll regions and such.
if (newColumns == columns && newRows == rows)
return;
columns = newColumns;
rows = newRows;
}
// reallocate new bitmap if needed
boolean newBitmap = (bitmap == null);
if(bitmap != null)
newBitmap = (bitmap.getWidth() != width || bitmap.getHeight() != height);
if (newBitmap) {
discardBitmap();
bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
canvas.setBitmap(bitmap);
}
// clear out any old buffer information
defaultPaint.setColor(Color.BLACK);
canvas.drawPaint(defaultPaint);
// Stroke the border of the terminal if the size is being forced;
if (forcedSize) {
int borderX = (columns * charWidth) + 1;
int borderY = (rows * charHeight) + 1;
defaultPaint.setColor(Color.GRAY);
defaultPaint.setStrokeWidth(0.0f);
if (width >= borderX)
canvas.drawLine(borderX, 0, borderX, borderY + 1, defaultPaint);
if (height >= borderY)
canvas.drawLine(0, borderY, borderX + 1, borderY, defaultPaint);
}
try {
// request a terminal pty resize
synchronized (buffer) {
buffer.setScreenSize(columns, rows, true);
}
if(transport != null)
transport.setDimensions(columns, rows, width, height);
} catch(Exception e) {
Log.e(TAG, "Problem while trying to resize screen or PTY", e);
}
// redraw local output if we don't have a sesson to receive our resize request
if (transport == null) {
synchronized (localOutput) {
((vt320) buffer).reset();
for (String line : localOutput)
((vt320) buffer).putString(line);
}
}
// force full redraw with new buffer size
fullRedraw = true;
redraw();
parent.notifyUser(String.format("%d x %d", columns, rows));
Log.i(TAG, String.format("parentChanged() now width=%d, height=%d", columns, rows));
}
/**
* Somehow our parent {@link TerminalView} was destroyed. Now we don't need
* to redraw anywhere, and we can recycle our internal bitmap.
*/
public synchronized void parentDestroyed() {
parent = null;
discardBitmap();
}
private void discardBitmap() {
if (bitmap != null)
bitmap.recycle();
bitmap = null;
}
public void setVDUBuffer(VDUBuffer buffer) {
this.buffer = buffer;
}
public VDUBuffer getVDUBuffer() {
return buffer;
}
public void propagateConsoleText(char[] rawText, int length) {
if (parent != null) {
parent.propagateConsoleText(rawText, length);
}
}
public void onDraw() {
int fg, bg;
synchronized (buffer) {
boolean entireDirty = buffer.update[0] || fullRedraw;
boolean isWideCharacter = false;
// walk through all lines in the buffer
for(int l = 0; l < buffer.height; l++) {
// check if this line is dirty and needs to be repainted
// also check for entire-buffer dirty flags
if (!entireDirty && !buffer.update[l + 1]) continue;
// reset dirty flag for this line
buffer.update[l + 1] = false;
// walk through all characters in this line
for (int c = 0; c < buffer.width; c++) {
int addr = 0;
int currAttr = buffer.charAttributes[buffer.windowBase + l][c];
{
int fgcolor = defaultFg;
// check if foreground color attribute is set
if ((currAttr & VDUBuffer.COLOR_FG) != 0)
fgcolor = ((currAttr & VDUBuffer.COLOR_FG) >> VDUBuffer.COLOR_FG_SHIFT) - 1;
if (fgcolor < 8 && (currAttr & VDUBuffer.BOLD) != 0)
fg = color[fgcolor + 8];
else
fg = color[fgcolor];
}
// check if background color attribute is set
if ((currAttr & VDUBuffer.COLOR_BG) != 0)
bg = color[((currAttr & VDUBuffer.COLOR_BG) >> VDUBuffer.COLOR_BG_SHIFT) - 1];
else
bg = color[defaultBg];
// support character inversion by swapping background and foreground color
if ((currAttr & VDUBuffer.INVERT) != 0) {
int swapc = bg;
bg = fg;
fg = swapc;
}
// set underlined attributes if requested
defaultPaint.setUnderlineText((currAttr & VDUBuffer.UNDERLINE) != 0);
isWideCharacter = (currAttr & VDUBuffer.FULLWIDTH) != 0;
if (isWideCharacter)
addr++;
else {
// determine the amount of continuous characters with the same settings and print them all at once
while(c + addr < buffer.width
&& buffer.charAttributes[buffer.windowBase + l][c + addr] == currAttr) {
addr++;
}
}
// Save the current clip region
canvas.save(Canvas.CLIP_SAVE_FLAG);
// clear this dirty area with background color
defaultPaint.setColor(bg);
if (isWideCharacter) {
canvas.clipRect(c * charWidth,
l * charHeight,
(c + 2) * charWidth,
(l + 1) * charHeight);
} else {
canvas.clipRect(c * charWidth,
l * charHeight,
(c + addr) * charWidth,
(l + 1) * charHeight);
}
canvas.drawPaint(defaultPaint);
// write the text string starting at 'c' for 'addr' number of characters
defaultPaint.setColor(fg);
if((currAttr & VDUBuffer.INVISIBLE) == 0)
canvas.drawText(buffer.charArray[buffer.windowBase + l], c,
addr, c * charWidth, (l * charHeight) - charTop,
defaultPaint);
// Restore the previous clip region
canvas.restore();
// advance to the next text block with different characteristics
c += addr - 1;
if (isWideCharacter)
c++;
}
}
// reset entire-buffer flags
buffer.update[0] = false;
}
fullRedraw = false;
}
public void redraw() {
if (parent != null)
parent.postInvalidate();
}
// We don't have a scroll bar.
public void updateScrollBar() {
}
/**
* Resize terminal to fit [rows]x[cols] in screen of size [width]x[height]
* @param rows
* @param cols
* @param width
* @param height
*/
public synchronized void resizeComputed(int cols, int rows, int width, int height) {
float size = 8.0f;
float step = 8.0f;
float limit = 0.125f;
int direction;
while ((direction = fontSizeCompare(size, cols, rows, width, height)) < 0)
size += step;
if (direction == 0) {
Log.d("fontsize", String.format("Found match at %f", size));
return;
}
step /= 2.0f;
size -= step;
while ((direction = fontSizeCompare(size, cols, rows, width, height)) != 0
&& step >= limit) {
step /= 2.0f;
if (direction > 0) {
size -= step;
} else {
size += step;
}
}
if (direction > 0)
size -= step;
this.columns = cols;
this.rows = rows;
setFontSize(size);
forcedSize = true;
}
private int fontSizeCompare(float size, int cols, int rows, int width, int height) {
// read new metrics to get exact pixel dimensions
defaultPaint.setTextSize(size);
FontMetrics fm = defaultPaint.getFontMetrics();
float[] widths = new float[1];
defaultPaint.getTextWidths("X", widths);
int termWidth = (int)widths[0] * cols;
int termHeight = (int)Math.ceil(fm.descent - fm.top) * rows;
Log.d("fontsize", String.format("font size %f resulted in %d x %d", size, termWidth, termHeight));
// Check to see if it fits in resolution specified.
if (termWidth > width || termHeight > height)
return 1;
if (termWidth == width || termHeight == height)
return 0;
return -1;
}
/**
* @return whether underlying transport can forward ports
*/
public boolean canFowardPorts() {
return transport.canForwardPorts();
}
/**
* Adds the {@link PortForwardBean} to the list.
* @param portForward the port forward bean to add
* @return true on successful addition
*/
public boolean addPortForward(PortForwardBean portForward) {
return transport.addPortForward(portForward);
}
/**
* Removes the {@link PortForwardBean} from the list.
* @param portForward the port forward bean to remove
* @return true on successful removal
*/
public boolean removePortForward(PortForwardBean portForward) {
return transport.removePortForward(portForward);
}
/**
* @return the list of port forwards
*/
public List<PortForwardBean> getPortForwards() {
return transport.getPortForwards();
}
/**
* Enables a port forward member. After calling this method, the port forward should
* be operational.
* @param portForward member of our current port forwards list to enable
* @return true on successful port forward setup
*/
public boolean enablePortForward(PortForwardBean portForward) {
if (!transport.isConnected()) {
Log.i(TAG, "Attempt to enable port forward while not connected");
return false;
}
return transport.enablePortForward(portForward);
}
/**
* Disables a port forward member. After calling this method, the port forward should
* be non-functioning.
* @param portForward member of our current port forwards list to enable
* @return true on successful port forward tear-down
*/
public boolean disablePortForward(PortForwardBean portForward) {
if (!transport.isConnected()) {
Log.i(TAG, "Attempt to disable port forward while not connected");
return false;
}
return transport.disablePortForward(portForward);
}
/**
* @return whether the TerminalBridge should close
*/
public boolean isAwaitingClose() {
return awaitingClose;
}
/**
* @return whether this connection had started and subsequently disconnected
*/
public boolean isDisconnected() {
return disconnected;
}
/* (non-Javadoc)
* @see de.mud.terminal.VDUDisplay#setColor(byte, byte, byte, byte)
*/
public void setColor(int index, int red, int green, int blue) {
// Don't allow the system colors to be overwritten for now. May violate specs.
if (index < color.length && index >= 16)
color[index] = 0xff000000 | red << 16 | green << 8 | blue;
}
public final void resetColors() {
int[] defaults = manager.hostdb.getDefaultColorsForScheme(HostDatabase.DEFAULT_COLOR_SCHEME);
defaultFg = defaults[0];
defaultBg = defaults[1];
color = manager.hostdb.getColorsForScheme(HostDatabase.DEFAULT_COLOR_SCHEME);
}
private static Pattern urlPattern = null;
/**
* @return
*/
public List<String> scanForURLs() {
List<String> urls = new LinkedList<String>();
if (urlPattern == null) {
// based on http://www.ietf.org/rfc/rfc2396.txt
String scheme = "[A-Za-z][-+.0-9A-Za-z]*";
String unreserved = "[-._~0-9A-Za-z]";
String pctEncoded = "%[0-9A-Fa-f]{2}";
String subDelims = "[!$&'()*+,;:=]";
String userinfo = "(?:" + unreserved + "|" + pctEncoded + "|" + subDelims + "|:)*";
String h16 = "[0-9A-Fa-f]{1,4}";
String decOctet = "(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])";
String ipv4address = decOctet + "\\." + decOctet + "\\." + decOctet + "\\." + decOctet;
String ls32 = "(?:" + h16 + ":" + h16 + "|" + ipv4address + ")";
String ipv6address = "(?:(?:" + h16 + "){6}" + ls32 + ")";
String ipvfuture = "v[0-9A-Fa-f]+.(?:" + unreserved + "|" + subDelims + "|:)+";
String ipLiteral = "\\[(?:" + ipv6address + "|" + ipvfuture + ")\\]";
String regName = "(?:" + unreserved + "|" + pctEncoded + "|" + subDelims + ")*";
String host = "(?:" + ipLiteral + "|" + ipv4address + "|" + regName + ")";
String port = "[0-9]*";
String authority = "(?:" + userinfo + "@)?" + host + "(?::" + port + ")?";
String pchar = "(?:" + unreserved + "|" + pctEncoded + "|" + subDelims + "|@)";
String segment = pchar + "*";
String pathAbempty = "(?:/" + segment + ")*";
String segmentNz = pchar + "+";
String pathAbsolute = "/(?:" + segmentNz + "(?:/" + segment + ")*)?";
String pathRootless = segmentNz + "(?:/" + segment + ")*";
String hierPart = "(?://" + authority + pathAbempty + "|" + pathAbsolute + "|" + pathRootless + ")";
String query = "(?:" + pchar + "|/|\\?)*";
String fragment = "(?:" + pchar + "|/|\\?)*";
String uriRegex = scheme + ":" + hierPart + "(?:" + query + ")?(?:#" + fragment + ")?";
urlPattern = Pattern.compile(uriRegex);
}
char[] visibleBuffer = new char[buffer.height * buffer.width];
for (int l = 0; l < buffer.height; l++)
System.arraycopy(buffer.charArray[buffer.windowBase + l], 0,
visibleBuffer, l * buffer.width, buffer.width);
Matcher urlMatcher = urlPattern.matcher(new String(visibleBuffer));
while (urlMatcher.find())
urls.add(urlMatcher.group());
return urls;
}
/**
* @return
*/
public boolean isUsingNetwork() {
return transport.usesNetwork();
}
/**
* @return
*/
public TerminalKeyListener getKeyHandler() {
return keyListener;
}
/**
*
*/
public void resetScrollPosition() {
// if we're in scrollback, scroll to bottom of window on input
if (buffer.windowBase != buffer.screenBase)
buffer.setWindowBase(buffer.screenBase);
}
/**
*
*/
public void increaseFontSize() {
setFontSize(fontSize + FONT_SIZE_STEP);
}
/**
*
*/
public void decreaseFontSize() {
setFontSize(fontSize - FONT_SIZE_STEP);
}
}
| Java |
/**
*
*/
package org.connectbot.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.util.Log;
/**
* @author kroot
*
*/
public class ConnectivityReceiver extends BroadcastReceiver {
private static final String TAG = "ConnectBot.ConnectivityManager";
private boolean mIsConnected = false;
final private TerminalManager mTerminalManager;
final private WifiLock mWifiLock;
private int mNetworkRef = 0;
private boolean mLockingWifi;
private Object[] mLock = new Object[0];
public ConnectivityReceiver(TerminalManager manager, boolean lockingWifi) {
mTerminalManager = manager;
final ConnectivityManager cm =
(ConnectivityManager) manager.getSystemService(Context.CONNECTIVITY_SERVICE);
final WifiManager wm = (WifiManager) manager.getSystemService(Context.WIFI_SERVICE);
mWifiLock = wm.createWifiLock(TAG);
final NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
mIsConnected = (info.getState() == State.CONNECTED);
}
mLockingWifi = lockingWifi;
final IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
manager.registerReceiver(this, filter);
}
/* (non-Javadoc)
* @see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
*/
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Log.w(TAG, "onReceived() called: " + intent);
return;
}
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
Log.d(TAG, "onReceived() called; noConnectivity? " + noConnectivity + "; isFailover? " + isFailover);
if (noConnectivity && !isFailover && mIsConnected) {
mIsConnected = false;
mTerminalManager.onConnectivityLost();
} else if (!mIsConnected) {
NetworkInfo info = (NetworkInfo) intent.getExtras()
.get(ConnectivityManager.EXTRA_NETWORK_INFO);
if (mIsConnected = (info.getState() == State.CONNECTED)) {
mTerminalManager.onConnectivityRestored();
}
}
}
/**
*
*/
public void cleanup() {
if (mWifiLock.isHeld())
mWifiLock.release();
mTerminalManager.unregisterReceiver(this);
}
/**
* Increase the number of things using the network. Acquire a Wi-Fi lock
* if necessary.
*/
public void incRef() {
synchronized (mLock) {
mNetworkRef += 1;
acquireWifiLockIfNecessaryLocked();
}
}
/**
* Decrease the number of things using the network. Release the Wi-Fi lock
* if necessary.
*/
public void decRef() {
synchronized (mLock) {
mNetworkRef -= 1;
releaseWifiLockIfNecessaryLocked();
}
}
/**
* @param mLockingWifi
*/
public void setWantWifiLock(boolean lockingWifi) {
synchronized (mLock) {
mLockingWifi = lockingWifi;
if (mLockingWifi) {
acquireWifiLockIfNecessaryLocked();
} else {
releaseWifiLockIfNecessaryLocked();
}
}
}
private void acquireWifiLockIfNecessaryLocked() {
if (mLockingWifi && mNetworkRef > 0 && !mWifiLock.isHeld()) {
mWifiLock.acquire();
}
}
private void releaseWifiLockIfNecessaryLocked() {
if (mNetworkRef == 0 && mWifiLock.isHeld()) {
mWifiLock.release();
}
}
/**
* @return whether we're connected to a network
*/
public boolean isConnected() {
return mIsConnected;
}
}
| Java |
/*
* 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.util.List;
import org.connectbot.bean.HostBean;
import org.connectbot.bean.PortForwardBean;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import org.connectbot.util.HostDatabase;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Resources;
import android.database.SQLException;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
/**
* List all portForwards for a particular host and provide a way for users to add more portForwards,
* edit existing portForwards, and delete portForwards.
*
* @author Kenny Root
*/
public class PortForwardListActivity extends ListActivity {
public final static String TAG = "ConnectBot.PortForwardListActivity";
private static final int LISTENER_CYCLE_TIME = 500;
protected HostDatabase hostdb;
private List<PortForwardBean> portForwards;
private ServiceConnection connection = null;
protected TerminalBridge hostBridge = null;
protected LayoutInflater inflater = null;
private HostBean host;
@Override
public void onStart() {
super.onStart();
this.bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
if(this.hostdb == null)
this.hostdb = new HostDatabase(this);
}
@Override
public void onStop() {
super.onStop();
this.unbindService(connection);
if(this.hostdb != null) {
this.hostdb.close();
this.hostdb = null;
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
long hostId = this.getIntent().getLongExtra(Intent.EXTRA_TITLE, -1);
setContentView(R.layout.act_portforwardlist);
// connect with hosts database and populate list
this.hostdb = new HostDatabase(this);
host = hostdb.findHostById(hostId);
{
final String nickname = host != null ? host.getNickname() : null;
final Resources resources = getResources();
if (nickname != null) {
this.setTitle(String.format("%s: %s (%s)",
resources.getText(R.string.app_name),
resources.getText(R.string.title_port_forwards_list),
nickname));
} else {
this.setTitle(String.format("%s: %s",
resources.getText(R.string.app_name),
resources.getText(R.string.title_port_forwards_list)));
}
}
connection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
TerminalManager bound = ((TerminalManager.TerminalBinder) service).getService();
hostBridge = bound.getConnectedBridge(host);
updateHandler.sendEmptyMessage(-1);
}
public void onServiceDisconnected(ComponentName name) {
hostBridge = null;
}
};
this.updateList();
this.registerForContextMenu(this.getListView());
this.getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
ListView lv = PortForwardListActivity.this.getListView();
PortForwardBean pfb = (PortForwardBean) lv.getItemAtPosition(position);
if (hostBridge != null) {
if (pfb.isEnabled())
hostBridge.disablePortForward(pfb);
else {
if (!hostBridge.enablePortForward(pfb))
Toast.makeText(PortForwardListActivity.this, getString(R.string.portforward_problem), Toast.LENGTH_LONG).show();
}
updateHandler.sendEmptyMessage(-1);
}
}
});
this.inflater = LayoutInflater.from(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem add = menu.add(R.string.portforward_menu_add);
add.setIcon(android.R.drawable.ic_menu_add);
add.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// build dialog to prompt user about updating
final View portForwardView = inflater.inflate(R.layout.dia_portforward, null, false);
final EditText destEdit = (EditText) portForwardView.findViewById(R.id.portforward_destination);
final Spinner typeSpinner = (Spinner)portForwardView.findViewById(R.id.portforward_type);
typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> value, View view,
int position, long id) {
destEdit.setEnabled(position != 2);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
new AlertDialog.Builder(PortForwardListActivity.this)
.setView(portForwardView)
.setPositiveButton(R.string.portforward_pos, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
final EditText nicknameEdit = (EditText) portForwardView.findViewById(R.id.nickname);
final EditText sourcePortEdit = (EditText) portForwardView.findViewById(R.id.portforward_source);
String type = HostDatabase.PORTFORWARD_LOCAL;
switch (typeSpinner.getSelectedItemPosition()) {
case 0:
type = HostDatabase.PORTFORWARD_LOCAL;
break;
case 1:
type = HostDatabase.PORTFORWARD_REMOTE;
break;
case 2:
type = HostDatabase.PORTFORWARD_DYNAMIC5;
break;
}
PortForwardBean pfb = new PortForwardBean(
host != null ? host.getId() : -1,
nicknameEdit.getText().toString(), type,
sourcePortEdit.getText().toString(),
destEdit.getText().toString());
if (hostBridge != null) {
hostBridge.addPortForward(pfb);
hostBridge.enablePortForward(pfb);
}
if (host != null && !hostdb.savePortForward(pfb))
throw new SQLException("Could not save port forward");
updateHandler.sendEmptyMessage(-1);
} catch (Exception e) {
Log.e(TAG, "Could not update port forward", e);
// TODO Show failure dialog.
}
}
})
.setNegativeButton(R.string.delete_neg, null).create().show();
return true;
}
});
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
// Create menu to handle deleting and editing port forward
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
final PortForwardBean pfb = (PortForwardBean) this.getListView().getItemAtPosition(info.position);
menu.setHeaderTitle(pfb.getNickname());
MenuItem edit = menu.add(R.string.portforward_edit);
edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
final View editTunnelView = inflater.inflate(R.layout.dia_portforward, null, false);
final Spinner typeSpinner = (Spinner) editTunnelView.findViewById(R.id.portforward_type);
if (HostDatabase.PORTFORWARD_LOCAL.equals(pfb.getType()))
typeSpinner.setSelection(0);
else if (HostDatabase.PORTFORWARD_REMOTE.equals(pfb.getType()))
typeSpinner.setSelection(1);
else
typeSpinner.setSelection(2);
final EditText nicknameEdit = (EditText) editTunnelView.findViewById(R.id.nickname);
nicknameEdit.setText(pfb.getNickname());
final EditText sourcePortEdit = (EditText) editTunnelView.findViewById(R.id.portforward_source);
sourcePortEdit.setText(String.valueOf(pfb.getSourcePort()));
final EditText destEdit = (EditText) editTunnelView.findViewById(R.id.portforward_destination);
if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(pfb.getType())) {
destEdit.setEnabled(false);
} else {
destEdit.setText(String.format("%s:%d", pfb.getDestAddr(), pfb.getDestPort()));
}
typeSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> value, View view,
int position, long id) {
destEdit.setEnabled(position != 2);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
new AlertDialog.Builder(PortForwardListActivity.this)
.setView(editTunnelView)
.setPositiveButton(R.string.button_change, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
if (hostBridge != null)
hostBridge.disablePortForward(pfb);
pfb.setNickname(nicknameEdit.getText().toString());
switch (typeSpinner.getSelectedItemPosition()) {
case 0:
pfb.setType(HostDatabase.PORTFORWARD_LOCAL);
break;
case 1:
pfb.setType(HostDatabase.PORTFORWARD_REMOTE);
break;
case 2:
pfb.setType(HostDatabase.PORTFORWARD_DYNAMIC5);
break;
}
pfb.setSourcePort(Integer.parseInt(sourcePortEdit.getText().toString()));
pfb.setDest(destEdit.getText().toString());
// Use the new settings for the existing connection.
if (hostBridge != null)
updateHandler.postDelayed(new Runnable() {
public void run() {
hostBridge.enablePortForward(pfb);
updateHandler.sendEmptyMessage(-1);
}
}, LISTENER_CYCLE_TIME);
if (!hostdb.savePortForward(pfb))
throw new SQLException("Could not save port forward");
updateHandler.sendEmptyMessage(-1);
} catch (Exception e) {
Log.e(TAG, "Could not update port forward", e);
// TODO Show failure dialog.
}
}
})
.setNegativeButton(android.R.string.cancel, null).create().show();
return true;
}
});
MenuItem delete = menu.add(R.string.portforward_delete);
delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// prompt user to make sure they really want this
new AlertDialog.Builder(PortForwardListActivity.this)
.setMessage(getString(R.string.delete_message, pfb.getNickname()))
.setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
// Delete the port forward from the host if needed.
if (hostBridge != null)
hostBridge.removePortForward(pfb);
hostdb.deletePortForward(pfb);
} catch (Exception e) {
Log.e(TAG, "Could not delete port forward", e);
}
updateHandler.sendEmptyMessage(-1);
}
})
.setNegativeButton(R.string.delete_neg, null).create().show();
return true;
}
});
}
protected Handler updateHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
PortForwardListActivity.this.updateList();
}
};
protected void updateList() {
if (hostBridge != null) {
this.portForwards = hostBridge.getPortForwards();
} else {
if (this.hostdb == null) return;
this.portForwards = this.hostdb.getPortForwardsForHost(host);
}
PortForwardAdapter adapter = new PortForwardAdapter(this, portForwards);
this.setListAdapter(adapter);
}
class PortForwardAdapter extends ArrayAdapter<PortForwardBean> {
class ViewHolder {
public TextView nickname;
public TextView caption;
}
private List<PortForwardBean> portForwards;
public PortForwardAdapter(Context context, List<PortForwardBean> portForwards) {
super(context, R.layout.item_portforward, portForwards);
this.portForwards = portForwards;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_portforward, null, false);
holder = new ViewHolder();
holder.nickname = (TextView)convertView.findViewById(android.R.id.text1);
holder.caption = (TextView)convertView.findViewById(android.R.id.text2);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
PortForwardBean pfb = portForwards.get(position);
holder.nickname.setText(pfb.getNickname());
holder.caption.setText(pfb.getDescription());
if (hostBridge != null && !pfb.isEnabled()) {
holder.nickname.setPaintFlags(holder.nickname.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
holder.caption.setPaintFlags(holder.caption.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
return convertView;
}
}
}
| Java |
/*
* 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 org.connectbot.util.PreferenceConstants;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.util.Log;
public class SettingsActivity extends PreferenceActivity {
private static final String TAG = "ConnectBot.Settings";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
addPreferencesFromResource(R.xml.preferences);
} catch (ClassCastException e) {
Log.e(TAG, "Shared preferences are corrupt! Resetting to default values.");
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
// Blow away all the preferences
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
PreferenceManager.setDefaultValues(this, R.xml.preferences, true);
// Since they were able to get to the Settings activity, they already agreed to the EULA
editor = preferences.edit();
editor.putBoolean(PreferenceConstants.EULA, true);
editor.commit();
addPreferencesFromResource(R.xml.preferences);
}
// TODO: add parse checking here to make sure we have integer value for scrollback
}
}
| Java |
/*
* 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.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import org.connectbot.bean.PubkeyBean;
import org.connectbot.util.EntropyDialog;
import org.connectbot.util.EntropyView;
import org.connectbot.util.OnEntropyGatheredListener;
import org.connectbot.util.PubkeyDatabase;
import org.connectbot.util.PubkeyUtils;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.SeekBar.OnSeekBarChangeListener;
public class GeneratePubkeyActivity extends Activity implements OnEntropyGatheredListener {
public final static String TAG = "ConnectBot.GeneratePubkeyActivity";
final static int DEFAULT_BITS = 1024;
private LayoutInflater inflater = null;
private EditText nickname;
private RadioGroup keyTypeGroup;
private SeekBar bitsSlider;
private EditText bitsText;
private CheckBox unlockAtStartup;
private CheckBox confirmUse;
private Button save;
private Dialog entropyDialog;
private ProgressDialog progress;
private EditText password1, password2;
private String keyType = PubkeyDatabase.KEY_TYPE_RSA;
private int minBits = 768;
private int bits = DEFAULT_BITS;
private byte[] entropy;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.act_generatepubkey);
nickname = (EditText) findViewById(R.id.nickname);
keyTypeGroup = (RadioGroup) findViewById(R.id.key_type);
bitsText = (EditText) findViewById(R.id.bits);
bitsSlider = (SeekBar) findViewById(R.id.bits_slider);
password1 = (EditText) findViewById(R.id.password1);
password2 = (EditText) findViewById(R.id.password2);
unlockAtStartup = (CheckBox) findViewById(R.id.unlock_at_startup);
confirmUse = (CheckBox) findViewById(R.id.confirm_use);
save = (Button) findViewById(R.id.save);
inflater = LayoutInflater.from(this);
nickname.addTextChangedListener(textChecker);
password1.addTextChangedListener(textChecker);
password2.addTextChangedListener(textChecker);
keyTypeGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.rsa) {
minBits = 768;
bitsSlider.setEnabled(true);
bitsSlider.setProgress(DEFAULT_BITS - minBits);
bitsText.setText(String.valueOf(DEFAULT_BITS));
bitsText.setEnabled(true);
keyType = PubkeyDatabase.KEY_TYPE_RSA;
} else if (checkedId == R.id.dsa) {
// DSA keys can only be 1024 bits
bitsSlider.setEnabled(false);
bitsSlider.setProgress(DEFAULT_BITS - minBits);
bitsText.setText(String.valueOf(DEFAULT_BITS));
bitsText.setEnabled(false);
keyType = PubkeyDatabase.KEY_TYPE_DSA;
}
}
});
bitsSlider.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromTouch) {
// Stay evenly divisible by 8 because it looks nicer to have
// 2048 than 2043 bits.
int leftover = progress % 8;
int ourProgress = progress;
if (leftover > 0)
ourProgress += 8 - leftover;
bits = minBits + ourProgress;
bitsText.setText(String.valueOf(bits));
}
public void onStartTrackingTouch(SeekBar seekBar) {
// We don't care about the start.
}
public void onStopTrackingTouch(SeekBar seekBar) {
// We don't care about the stop.
}
});
bitsText.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
try {
bits = Integer.parseInt(bitsText.getText().toString());
if (bits < minBits) {
bits = minBits;
bitsText.setText(String.valueOf(bits));
}
} catch (NumberFormatException nfe) {
bits = DEFAULT_BITS;
bitsText.setText(String.valueOf(bits));
}
bitsSlider.setProgress(bits - minBits);
}
}
});
save.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
GeneratePubkeyActivity.this.save.setEnabled(false);
GeneratePubkeyActivity.this.startEntropyGather();
}
});
}
private void checkEntries() {
boolean allowSave = true;
if (!password1.getText().toString().equals(password2.getText().toString()))
allowSave = false;
if (nickname.getText().length() == 0)
allowSave = false;
save.setEnabled(allowSave);
}
private void startEntropyGather() {
final View entropyView = inflater.inflate(R.layout.dia_gatherentropy, null, false);
((EntropyView)entropyView.findViewById(R.id.entropy)).addOnEntropyGatheredListener(GeneratePubkeyActivity.this);
entropyDialog = new EntropyDialog(GeneratePubkeyActivity.this, entropyView);
entropyDialog.show();
}
public void onEntropyGathered(byte[] entropy) {
// For some reason the entropy dialog was aborted, exit activity
if (entropy == null) {
finish();
return;
}
this.entropy = entropy.clone();
int numSetBits = 0;
for (int i = 0; i < 20; i++)
numSetBits += measureNumberOfSetBits(this.entropy[i]);
Log.d(TAG, "Entropy distribution=" + (int)(100.0 * numSetBits / 160.0) + "%");
Log.d(TAG, "entropy gathered; attemping to generate key...");
startKeyGen();
}
private void startKeyGen() {
progress = new ProgressDialog(GeneratePubkeyActivity.this);
progress.setMessage(GeneratePubkeyActivity.this.getResources().getText(R.string.pubkey_generating));
progress.setIndeterminate(true);
progress.setCancelable(false);
progress.show();
Thread keyGenThread = new Thread(mKeyGen);
keyGenThread.setName("KeyGen");
keyGenThread.start();
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
progress.dismiss();
GeneratePubkeyActivity.this.finish();
}
};
final private Runnable mKeyGen = new Runnable() {
public void run() {
try {
boolean encrypted = false;
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(entropy);
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(keyType);
keyPairGen.initialize(bits, random);
KeyPair pair = keyPairGen.generateKeyPair();
PrivateKey priv = pair.getPrivate();
PublicKey pub = pair.getPublic();
String secret = password1.getText().toString();
if (secret.length() > 0)
encrypted = true;
Log.d(TAG, "private: " + PubkeyUtils.formatKey(priv));
Log.d(TAG, "public: " + PubkeyUtils.formatKey(pub));
PubkeyBean pubkey = new PubkeyBean();
pubkey.setNickname(nickname.getText().toString());
pubkey.setType(keyType);
pubkey.setPrivateKey(PubkeyUtils.getEncodedPrivate(priv, secret));
pubkey.setPublicKey(PubkeyUtils.getEncodedPublic(pub));
pubkey.setEncrypted(encrypted);
pubkey.setStartup(unlockAtStartup.isChecked());
pubkey.setConfirmUse(confirmUse.isChecked());
PubkeyDatabase pubkeydb = new PubkeyDatabase(GeneratePubkeyActivity.this);
pubkeydb.savePubkey(pubkey);
pubkeydb.close();
} catch (Exception e) {
Log.e(TAG, "Could not generate key pair");
e.printStackTrace();
}
handler.sendEmptyMessage(0);
}
};
final private TextWatcher textChecker = new TextWatcher() {
public void afterTextChanged(Editable s) {}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
checkEntries();
}
};
private int measureNumberOfSetBits(byte b) {
int numSetBits = 0;
for (int i = 0; i < 8; i++) {
if ((b & 1) == 1)
numSetBits++;
b >>= 1;
}
return numSetBits;
}
}
| Java |
/*
* 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.bean;
import org.connectbot.util.HostDatabase;
import android.content.ContentValues;
/**
* @author Kenny Root
*
*/
public class PortForwardBean extends AbstractBean {
public static final String BEAN_NAME = "portforward";
/* Database fields */
private long id = -1;
private long hostId = -1;
private String nickname = null;
private String type = null;
private int sourcePort = -1;
private String destAddr = null;
private int destPort = -1;
/* Transient values */
private boolean enabled = false;
private Object identifier = null;
/**
* @param id database ID of port forward
* @param nickname Nickname to use to identify port forward
* @param type One of the port forward types from {@link HostDatabase}
* @param sourcePort Source port number
* @param destAddr Destination hostname or IP address
* @param destPort Destination port number
*/
public PortForwardBean(long id, long hostId, String nickname, String type, int sourcePort, String destAddr, int destPort) {
this.id = id;
this.hostId = hostId;
this.nickname = nickname;
this.type = type;
this.sourcePort = sourcePort;
this.destAddr = destAddr;
this.destPort = destPort;
}
/**
* @param type One of the port forward types from {@link HostDatabase}
* @param source Source port number
* @param dest Destination is "host:port" format
*/
public PortForwardBean(long hostId, String nickname, String type, String source, String dest) {
this.hostId = hostId;
this.nickname = nickname;
this.type = type;
this.sourcePort = Integer.parseInt(source);
setDest(dest);
}
public String getBeanName() {
return BEAN_NAME;
}
/**
* @param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* @return the id
*/
public long getId() {
return id;
}
/**
* @param nickname the nickname to set
*/
public void setNickname(String nickname) {
this.nickname = nickname;
}
/**
* @return the nickname
*/
public String getNickname() {
return nickname;
}
/**
* @param type the type to set
*/
public void setType(String type) {
this.type = type;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @param sourcePort the sourcePort to set
*/
public void setSourcePort(int sourcePort) {
this.sourcePort = sourcePort;
}
/**
* @return the sourcePort
*/
public int getSourcePort() {
return sourcePort;
}
/**
* @param dest The destination in "host:port" format
*/
public final void setDest(String dest) {
String[] destSplit = dest.split(":");
this.destAddr = destSplit[0];
if (destSplit.length > 1)
this.destPort = Integer.parseInt(destSplit[1]);
}
/**
* @param destAddr the destAddr to set
*/
public void setDestAddr(String destAddr) {
this.destAddr = destAddr;
}
/**
* @return the destAddr
*/
public String getDestAddr() {
return destAddr;
}
/**
* @param destPort the destPort to set
*/
public void setDestPort(int destPort) {
this.destPort = destPort;
}
/**
* @return the destPort
*/
public int getDestPort() {
return destPort;
}
/**
* @param enabled the enabled to set
*/
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
/**
* @return the enabled
*/
public boolean isEnabled() {
return enabled;
}
/**
* @param identifier the identifier of this particular type to set
*/
public void setIdentifier(Object identifier) {
this.identifier = identifier;
}
/**
* @return the identifier used by this particular type
*/
public Object getIdentifier() {
return identifier;
}
/**
* @return human readable description of the port forward
*/
public CharSequence getDescription() {
String description = "Unknown type";
if (HostDatabase.PORTFORWARD_LOCAL.equals(type)) {
description = String.format("Local port %d to %s:%d", sourcePort, destAddr, destPort);
} else if (HostDatabase.PORTFORWARD_REMOTE.equals(type)) {
description = String.format("Remote port %d to %s:%d", sourcePort, destAddr, destPort);
/* I don't think we need the SOCKS4 type.
} else if (HostDatabase.PORTFORWARD_DYNAMIC4.equals(type)) {
description = String.format("Dynamic port %d (SOCKS4)", sourcePort);
*/
} else if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(type)) {
description = String.format("Dynamic port %d (SOCKS)", sourcePort);
}
return description;
}
/**
* @return
*/
public ContentValues getValues() {
ContentValues values = new ContentValues();
values.put(HostDatabase.FIELD_PORTFORWARD_HOSTID, hostId);
values.put(HostDatabase.FIELD_PORTFORWARD_NICKNAME, nickname);
values.put(HostDatabase.FIELD_PORTFORWARD_TYPE, type);
values.put(HostDatabase.FIELD_PORTFORWARD_SOURCEPORT, sourcePort);
values.put(HostDatabase.FIELD_PORTFORWARD_DESTADDR, destAddr);
values.put(HostDatabase.FIELD_PORTFORWARD_DESTPORT, destPort);
return values;
}
}
| Java |
/*
* 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.bean;
import de.mud.terminal.VDUBuffer;
/**
* @author Kenny Root
* Keep track of a selection area for the terminal copying mechanism.
* If the orientation is flipped one way, swap the bottom and top or
* left and right to keep it in the correct orientation.
*/
public class SelectionArea {
private int top;
private int bottom;
private int left;
private int right;
private int maxColumns;
private int maxRows;
private boolean selectingOrigin;
public SelectionArea() {
reset();
}
public final void reset() {
top = left = bottom = right = 0;
selectingOrigin = true;
}
/**
* @param columns
* @param rows
*/
public void setBounds(int columns, int rows) {
maxColumns = columns - 1;
maxRows = rows - 1;
}
private int checkBounds(int value, int max) {
if (value < 0)
return 0;
else if (value > max)
return max;
else
return value;
}
public boolean isSelectingOrigin() {
return selectingOrigin;
}
public void finishSelectingOrigin() {
selectingOrigin = false;
}
public void decrementRow() {
if (selectingOrigin)
setTop(top - 1);
else
setBottom(bottom - 1);
}
public void incrementRow() {
if (selectingOrigin)
setTop(top + 1);
else
setBottom(bottom + 1);
}
public void setRow(int row) {
if (selectingOrigin)
setTop(row);
else
setBottom(row);
}
private void setTop(int top) {
this.top = bottom = checkBounds(top, maxRows);
}
public int getTop() {
return Math.min(top, bottom);
}
private void setBottom(int bottom) {
this.bottom = checkBounds(bottom, maxRows);
}
public int getBottom() {
return Math.max(top, bottom);
}
public void decrementColumn() {
if (selectingOrigin)
setLeft(left - 1);
else
setRight(right - 1);
}
public void incrementColumn() {
if (selectingOrigin)
setLeft(left + 1);
else
setRight(right + 1);
}
public void setColumn(int column) {
if (selectingOrigin)
setLeft(column);
else
setRight(column);
}
private void setLeft(int left) {
this.left = right = checkBounds(left, maxColumns);
}
public int getLeft() {
return Math.min(left, right);
}
private void setRight(int right) {
this.right = checkBounds(right, maxColumns);
}
public int getRight() {
return Math.max(left, right);
}
public String copyFrom(VDUBuffer vb) {
int size = (getRight() - getLeft() + 1) * (getBottom() - getTop() + 1);
StringBuffer buffer = new StringBuffer(size);
for(int y = getTop(); y <= getBottom(); y++) {
int lastNonSpace = buffer.length();
for (int x = getLeft(); x <= getRight(); x++) {
// only copy printable chars
char c = vb.getChar(x, y);
if (!Character.isDefined(c) ||
(Character.isISOControl(c) && c != '\t'))
c = ' ';
if (c != ' ')
lastNonSpace = buffer.length();
buffer.append(c);
}
// Don't leave a bunch of spaces in our copy buffer.
if (buffer.length() > lastNonSpace)
buffer.delete(lastNonSpace + 1, buffer.length());
if (y != bottom)
buffer.append("\n");
}
return buffer.toString();
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append("SelectionArea[top=");
buffer.append(top);
buffer.append(", bottom=");
buffer.append(bottom);
buffer.append(", left=");
buffer.append(left);
buffer.append(", right=");
buffer.append(right);
buffer.append(", maxColumns=");
buffer.append(maxColumns);
buffer.append(", maxRows=");
buffer.append(maxRows);
buffer.append(", isSelectingOrigin=");
buffer.append(isSelectingOrigin());
buffer.append("]");
return buffer.toString();
}
}
| Java |
/*
* 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.bean;
import java.util.Map.Entry;
import org.connectbot.util.XmlBuilder;
import android.content.ContentValues;
/**
* @author Kenny Root
*
*/
abstract class AbstractBean {
public abstract ContentValues getValues();
public abstract String getBeanName();
public String toXML() {
XmlBuilder xml = new XmlBuilder();
xml.append(String.format("<%s>", getBeanName()));
ContentValues values = getValues();
for (Entry<String, Object> entry : values.valueSet()) {
Object value = entry.getValue();
if (value != null)
xml.append(entry.getKey(), value);
}
xml.append(String.format("</%s>", getBeanName()));
return xml.toString();
}
}
| Java |
/*
* 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.bean;
import org.connectbot.util.HostDatabase;
import android.content.ContentValues;
import android.net.Uri;
/**
* @author Kenny Root
*
*/
public class HostBean extends AbstractBean {
public static final String BEAN_NAME = "host";
/* Database fields */
private long id = -1;
private String nickname = null;
private String username = null;
private String hostname = null;
private int port = 22;
private String protocol = "ssh";
private String hostKeyAlgo = null;
private byte[] hostKey = null;
private long lastConnect = -1;
private String color;
private boolean useKeys = true;
private String useAuthAgent = HostDatabase.AUTHAGENT_NO;
private String postLogin = null;
private long pubkeyId = -1;
private boolean wantSession = true;
private String delKey = HostDatabase.DELKEY_DEL;
private int fontSize = -1;
private boolean compression = false;
private String encoding = HostDatabase.ENCODING_DEFAULT;
private boolean stayConnected = false;
public HostBean() {
}
@Override
public String getBeanName() {
return BEAN_NAME;
}
public HostBean(String nickname, String protocol, String username, String hostname, int port) {
this.nickname = nickname;
this.protocol = protocol;
this.username = username;
this.hostname = hostname;
this.port = port;
}
public void setId(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getNickname() {
return nickname;
}
public void setUsername(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getHostname() {
return hostname;
}
public void setPort(int port) {
this.port = port;
}
public int getPort() {
return port;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getProtocol() {
return protocol;
}
public void setHostKeyAlgo(String hostKeyAlgo) {
this.hostKeyAlgo = hostKeyAlgo;
}
public String getHostKeyAlgo() {
return hostKeyAlgo;
}
public void setHostKey(byte[] hostKey) {
if (hostKey == null)
this.hostKey = null;
else
this.hostKey = hostKey.clone();
}
public byte[] getHostKey() {
if (hostKey == null)
return null;
else
return hostKey.clone();
}
public void setLastConnect(long lastConnect) {
this.lastConnect = lastConnect;
}
public long getLastConnect() {
return lastConnect;
}
public void setColor(String color) {
this.color = color;
}
public String getColor() {
return color;
}
public void setUseKeys(boolean useKeys) {
this.useKeys = useKeys;
}
public boolean getUseKeys() {
return useKeys;
}
public void setUseAuthAgent(String useAuthAgent) {
this.useAuthAgent = useAuthAgent;
}
public String getUseAuthAgent() {
return useAuthAgent;
}
public void setPostLogin(String postLogin) {
this.postLogin = postLogin;
}
public String getPostLogin() {
return postLogin;
}
public void setPubkeyId(long pubkeyId) {
this.pubkeyId = pubkeyId;
}
public long getPubkeyId() {
return pubkeyId;
}
public void setWantSession(boolean wantSession) {
this.wantSession = wantSession;
}
public boolean getWantSession() {
return wantSession;
}
public void setDelKey(String delKey) {
this.delKey = delKey;
}
public String getDelKey() {
return delKey;
}
public void setFontSize(int fontSize) {
this.fontSize = fontSize;
}
public int getFontSize() {
return fontSize;
}
public void setCompression(boolean compression) {
this.compression = compression;
}
public boolean getCompression() {
return compression;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
public String getEncoding() {
return this.encoding;
}
public void setStayConnected(boolean stayConnected) {
this.stayConnected = stayConnected;
}
public boolean getStayConnected() {
return stayConnected;
}
public String getDescription() {
String description = String.format("%s@%s", username, hostname);
if (port != 22)
description += String.format(":%d", port);
return description;
}
@Override
public ContentValues getValues() {
ContentValues values = new ContentValues();
values.put(HostDatabase.FIELD_HOST_NICKNAME, nickname);
values.put(HostDatabase.FIELD_HOST_PROTOCOL, protocol);
values.put(HostDatabase.FIELD_HOST_USERNAME, username);
values.put(HostDatabase.FIELD_HOST_HOSTNAME, hostname);
values.put(HostDatabase.FIELD_HOST_PORT, port);
values.put(HostDatabase.FIELD_HOST_HOSTKEYALGO, hostKeyAlgo);
values.put(HostDatabase.FIELD_HOST_HOSTKEY, hostKey);
values.put(HostDatabase.FIELD_HOST_LASTCONNECT, lastConnect);
values.put(HostDatabase.FIELD_HOST_COLOR, color);
values.put(HostDatabase.FIELD_HOST_USEKEYS, Boolean.toString(useKeys));
values.put(HostDatabase.FIELD_HOST_USEAUTHAGENT, useAuthAgent);
values.put(HostDatabase.FIELD_HOST_POSTLOGIN, postLogin);
values.put(HostDatabase.FIELD_HOST_PUBKEYID, pubkeyId);
values.put(HostDatabase.FIELD_HOST_WANTSESSION, Boolean.toString(wantSession));
values.put(HostDatabase.FIELD_HOST_DELKEY, delKey);
values.put(HostDatabase.FIELD_HOST_FONTSIZE, fontSize);
values.put(HostDatabase.FIELD_HOST_COMPRESSION, Boolean.toString(compression));
values.put(HostDatabase.FIELD_HOST_ENCODING, encoding);
values.put(HostDatabase.FIELD_HOST_STAYCONNECTED, stayConnected);
return values;
}
@Override
public boolean equals(Object o) {
if (o == null || !(o instanceof HostBean))
return false;
HostBean host = (HostBean)o;
if (id != -1 && host.getId() != -1)
return host.getId() == id;
if (nickname == null) {
if (host.getNickname() != null)
return false;
} else if (!nickname.equals(host.getNickname()))
return false;
if (protocol == null) {
if (host.getProtocol() != null)
return false;
} else if (!protocol.equals(host.getProtocol()))
return false;
if (username == null) {
if (host.getUsername() != null)
return false;
} else if (!username.equals(host.getUsername()))
return false;
if (hostname == null) {
if (host.getHostname() != null)
return false;
} else if (!hostname.equals(host.getHostname()))
return false;
if (port != host.getPort())
return false;
return true;
}
@Override
public int hashCode() {
int hash = 7;
if (id != -1)
return (int)id;
hash = 31 * hash + (null == nickname ? 0 : nickname.hashCode());
hash = 31 * hash + (null == protocol ? 0 : protocol.hashCode());
hash = 31 * hash + (null == username ? 0 : username.hashCode());
hash = 31 * hash + (null == hostname ? 0 : hostname.hashCode());
hash = 31 * hash + port;
return hash;
}
/**
* @return URI identifying this HostBean
*/
public Uri getUri() {
StringBuilder sb = new StringBuilder();
sb.append(protocol)
.append("://");
if (username != null)
sb.append(Uri.encode(username))
.append('@');
sb.append(Uri.encode(hostname))
.append(':')
.append(port)
.append("/#")
.append(nickname);
return Uri.parse(sb.toString());
}
}
| Java |
/*
* 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.bean;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.DSAPublicKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import org.connectbot.util.PubkeyDatabase;
import org.connectbot.util.PubkeyUtils;
import android.content.ContentValues;
/**
* @author Kenny Root
*
*/
public class PubkeyBean extends AbstractBean {
public static final String BEAN_NAME = "pubkey";
private static final String KEY_TYPE_RSA = "RSA";
private static final String KEY_TYPE_DSA = "DSA";
/* Database fields */
private long id;
private String nickname;
private String type;
private byte[] privateKey;
private PublicKey publicKey;
private boolean encrypted = false;
private boolean startup = false;
private boolean confirmUse = false;
private int lifetime = 0;
/* Transient values */
private boolean unlocked = false;
private Object unlockedPrivate = null;
@Override
public String getBeanName() {
return BEAN_NAME;
}
public void setId(long id) {
this.id = id;
}
public long getId() {
return id;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getNickname() {
return nickname;
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
public void setPrivateKey(byte[] privateKey) {
if (privateKey == null)
this.privateKey = null;
else
this.privateKey = privateKey.clone();
}
public byte[] getPrivateKey() {
if (privateKey == null)
return null;
else
return privateKey.clone();
}
private PublicKey decodePublicKeyAs(EncodedKeySpec keySpec, String keyType) {
try {
final KeyFactory kf = KeyFactory.getInstance(keyType);
return kf.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
return null;
} catch (InvalidKeySpecException e) {
return null;
}
}
public void setPublicKey(byte[] encoded) {
final X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encoded);
if (type != null) {
publicKey = decodePublicKeyAs(pubKeySpec, type);
} else {
publicKey = decodePublicKeyAs(pubKeySpec, KEY_TYPE_RSA);
if (publicKey != null) {
type = KEY_TYPE_RSA;
} else {
publicKey = decodePublicKeyAs(pubKeySpec, KEY_TYPE_DSA);
if (publicKey != null) {
type = KEY_TYPE_DSA;
}
}
}
}
public PublicKey getPublicKey() {
return publicKey;
}
public void setEncrypted(boolean encrypted) {
this.encrypted = encrypted;
}
public boolean isEncrypted() {
return encrypted;
}
public void setStartup(boolean startup) {
this.startup = startup;
}
public boolean isStartup() {
return startup;
}
public void setConfirmUse(boolean confirmUse) {
this.confirmUse = confirmUse;
}
public boolean isConfirmUse() {
return confirmUse;
}
public void setLifetime(int lifetime) {
this.lifetime = lifetime;
}
public int getLifetime() {
return lifetime;
}
public void setUnlocked(boolean unlocked) {
this.unlocked = unlocked;
}
public boolean isUnlocked() {
return unlocked;
}
public void setUnlockedPrivate(Object unlockedPrivate) {
this.unlockedPrivate = unlockedPrivate;
}
public Object getUnlockedPrivate() {
return unlockedPrivate;
}
public String getDescription() {
StringBuilder sb = new StringBuilder();
if (publicKey instanceof RSAPublicKey) {
int bits = ((RSAPublicKey) publicKey).getModulus().bitLength();
sb.append("RSA ");
sb.append(bits);
sb.append("-bit");
} else if (publicKey instanceof DSAPublicKey) {
sb.append("DSA 1024-bit");
} else {
sb.append("Unknown Key Type");
}
if (encrypted)
sb.append(" (encrypted)");
return sb.toString();
}
/* (non-Javadoc)
* @see org.connectbot.bean.AbstractBean#getValues()
*/
@Override
public ContentValues getValues() {
ContentValues values = new ContentValues();
values.put(PubkeyDatabase.FIELD_PUBKEY_NICKNAME, nickname);
values.put(PubkeyDatabase.FIELD_PUBKEY_TYPE, type);
values.put(PubkeyDatabase.FIELD_PUBKEY_PRIVATE, privateKey);
values.put(PubkeyDatabase.FIELD_PUBKEY_PUBLIC, publicKey.getEncoded());
values.put(PubkeyDatabase.FIELD_PUBKEY_ENCRYPTED, encrypted ? 1 : 0);
values.put(PubkeyDatabase.FIELD_PUBKEY_STARTUP, startup ? 1 : 0);
values.put(PubkeyDatabase.FIELD_PUBKEY_CONFIRMUSE, confirmUse ? 1 : 0);
values.put(PubkeyDatabase.FIELD_PUBKEY_LIFETIME, lifetime);
return values;
}
public boolean changePassword(String oldPassword, String newPassword) throws Exception {
PrivateKey priv;
try {
priv = PubkeyUtils.decodePrivate(getPrivateKey(), getType(), oldPassword);
} catch (Exception e) {
return false;
}
setPrivateKey(PubkeyUtils.getEncodedPrivate(priv, newPassword));
setEncrypted(newPassword.length() > 0);
return true;
}
}
| Java |
/*
* 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.List;
import org.connectbot.bean.SelectionArea;
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.Activity;
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.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.WindowManager;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;
import de.mud.terminal.vt320;
public class ConsoleActivity extends Activity {
public final static String TAG = "ConnectBot.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 = 1500;
// Direction to shift the ViewFlipper
private static final int SHIFT_LEFT = 0;
private static final int SHIFT_RIGHT = 1;
protected ViewFlipper flip = null;
protected TerminalManager bound = 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 TextView empty;
private Animation slide_left_in, slide_left_out, slide_right_in, slide_right_out, fade_stay_hidden, 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 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.disconnectHandler = disconnectHandler;
Log.d(TAG, String.format("Connected to TerminalManager and found bridges.size=%d", bound.bridges.size()));
bound.setResizeAllowed(true);
// clear out any existing bridges and record requested index
flip.removeAllViews();
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
for (TerminalBridge bridge : bound.bridges) {
final int currentIndex = addNewTerminalView(bridge);
// check to see if this bridge was requested
if (bridge == requestedBridge)
requestedIndex = currentIndex;
}
setDisplayedTerminal(requestedIndex);
}
public void onServiceDisconnected(ComponentName className) {
// tell each bridge to forget about our prompt handler
synchronized (bound.bridges) {
for(TerminalBridge bridge : bound.bridges)
bridge.promptHelper.setHandler(null);
}
flip.removeAllViews();
updateEmptyVisible();
bound = null;
}
};
protected Handler promptHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// someone below us requested to display a prompt
updatePromptVisible();
}
};
protected Handler disconnectHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Log.d(TAG, "Someone sending HANDLE_DISCONNECT to parentHandler");
// someone below us requested to display a password dialog
// they are sending nickname and requested
TerminalBridge bridge = (TerminalBridge)msg.obj;
if (bridge.isAwaitingClose())
closeBridge(bridge);
}
};
/**
* @param bridge
*/
private void closeBridge(final TerminalBridge bridge) {
synchronized (flip) {
final int flipIndex = getFlipIndex(bridge);
if (flipIndex >= 0) {
if (flip.getDisplayedChild() == flipIndex) {
shiftCurrentTerminal(SHIFT_LEFT);
}
flip.removeViewAt(flipIndex);
/* TODO Remove this workaround when ViewFlipper is fixed to listen
* to view removals. Android Issue 1784
*/
final int numChildren = flip.getChildCount();
if (flip.getDisplayedChild() >= numChildren &&
numChildren > 0) {
flip.setDisplayedChild(numChildren - 1);
}
updateEmptyVisible();
}
// If we just closed the last bridge, go back to the previous activity.
if (flip.getChildCount() == 0) {
finish();
}
}
}
protected View findCurrentView(int id) {
View view = flip.getCurrentView();
if(view == null) return null;
return view.findViewById(id);
}
protected PromptHelper getCurrentPromptHelper() {
View view = findCurrentView(R.id.console_flip);
if(!(view instanceof TerminalView)) return null;
return ((TerminalView)view).bridge.promptHelper;
}
protected void hideAllPrompts() {
stringPromptGroup.setVisibility(View.GONE);
booleanPromptGroup.setVisibility(View.GONE);
}
// more like configureLaxMode -- enable network IO on UI thread
private void configureStrictMode() {
try {
Class.forName("android.os.StrictMode");
StrictModeSetup.run();
} catch (ClassNotFoundException e) {
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
configureStrictMode();
hardKeyboard = getResources().getConfiguration().keyboard ==
Configuration.KEYBOARD_QWERTY;
this.setContentView(R.layout.act_console);
clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
// 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
requested = getIntent().getData();
inflater = LayoutInflater.from(this);
flip = (ViewFlipper)findViewById(R.id.console_flip);
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();
}
});
// preload animations for terminal switching
slide_left_in = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
slide_left_out = AnimationUtils.loadAnimation(this, R.anim.slide_left_out);
slide_right_in = AnimationUtils.loadAnimation(this, R.anim.slide_right_in);
slide_right_out = AnimationUtils.loadAnimation(this, R.anim.slide_right_out);
fade_out_delayed = AnimationUtils.loadAnimation(this, R.anim.fade_out_delayed);
fade_stay_hidden = AnimationUtils.loadAnimation(this, R.anim.fade_stay_hidden);
// 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);
final RelativeLayout keyboardGroup = (RelativeLayout) findViewById(R.id.keyboard_group);
mKeyboardButton = (ImageView) findViewById(R.id.button_keyboard);
mKeyboardButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null)
return;
inputManager.showSoftInput(flip, InputMethodManager.SHOW_FORCED);
keyboardGroup.setVisibility(View.GONE);
}
});
final ImageView ctrlButton = (ImageView) findViewById(R.id.button_ctrl);
ctrlButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return;
TerminalView terminal = (TerminalView)flip;
TerminalKeyListener handler = terminal.bridge.getKeyHandler();
handler.metaPress(TerminalKeyListener.META_CTRL_ON);
keyboardGroup.setVisibility(View.GONE);
}
});
final ImageView escButton = (ImageView) findViewById(R.id.button_esc);
escButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
View flip = findCurrentView(R.id.console_flip);
if (flip == null) return;
TerminalView terminal = (TerminalView)flip;
TerminalKeyListener handler = terminal.bridge.getKeyHandler();
handler.sendEscape();
keyboardGroup.setVisibility(View.GONE);
}
});
// detect fling gestures to switch between terminals
final GestureDetector detect = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
private float totalY = 0;
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
final float distx = e2.getRawX() - e1.getRawX();
final float disty = e2.getRawY() - e1.getRawY();
final int goalwidth = flip.getWidth() / 2;
// need to slide across half of display to trigger console change
// make sure user kept a steady hand horizontally
if (Math.abs(disty) < (flip.getHeight() / 4)) {
if (distx > goalwidth) {
shiftCurrentTerminal(SHIFT_RIGHT);
return true;
}
if (distx < -goalwidth) {
shiftCurrentTerminal(SHIFT_LEFT);
return true;
}
}
return false;
}
@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
if (Math.abs(e1.getX() - e2.getX()) < ViewConfiguration.getTouchSlop() * 4) {
View flip = findCurrentView(R.id.console_flip);
if(flip == null) return false;
TerminalView terminal = (TerminalView)flip;
// 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() > flip.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;
}
});
flip.setLongClickable(true);
flip.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// 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;
}
}
Configuration config = getResources().getConfiguration();
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) {
keyboardGroup.startAnimation(keyboard_fade_in);
keyboardGroup.setVisibility(View.VISIBLE);
handler.postDelayed(new Runnable() {
public void run() {
if (keyboardGroup.getVisibility() == View.GONE)
return;
keyboardGroup.startAnimation(keyboard_fade_out);
keyboardGroup.setVisibility(View.GONE);
}
}, KEYBOARD_DISPLAY_TIME);
}
// pass any touch events back to detector
return detect.onTouchEvent(event);
}
});
}
/**
*
*/
private void configureOrientation() {
String rotateDefault;
if (getResources().getConfiguration().keyboard == Configuration.KEYBOARD_NOKEYS)
rotateDefault = PreferenceConstants.ROTATION_PORTRAIT;
else
rotateDefault = PreferenceConstants.ROTATION_LANDSCAPE;
String rotate = prefs.getString(PreferenceConstants.ROTATION, rotateDefault);
if (PreferenceConstants.ROTATION_DEFAULT.equals(rotate))
rotate = rotateDefault;
// request a forced orientation if requested by user
if (PreferenceConstants.ROTATION_LANDSCAPE.equals(rotate)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
forcedOrientation = true;
} else if (PreferenceConstants.ROTATION_PORTRAIT.equals(rotate)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
forcedOrientation = true;
} else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
forcedOrientation = false;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
View view = findCurrentView(R.id.console_flip);
final boolean activeTerminal = (view instanceof TerminalView);
boolean sessionOpen = false;
boolean disconnected = false;
boolean canForwardPorts = false;
if (activeTerminal) {
TerminalBridge bridge = ((TerminalView) view).bridge;
sessionOpen = bridge.isSessionOpen();
disconnected = bridge.isDisconnected();
canForwardPorts = bridge.canFowardPorts();
}
menu.setQwertyMode(true);
disconnect = menu.add(R.string.list_host_disconnect);
if (hardKeyboard)
disconnect.setAlphabeticShortcut('w');
if (!sessionOpen && disconnected)
disconnect.setTitle(R.string.console_menu_close);
disconnect.setEnabled(activeTerminal);
disconnect.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
disconnect.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// disconnect or close the currently visible session
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
TerminalBridge bridge = terminalView.bridge;
bridge.dispatchDisconnect(true);
return true;
}
});
copy = menu.add(R.string.console_menu_copy);
if (hardKeyboard)
copy.setAlphabeticShortcut('c');
copy.setIcon(android.R.drawable.ic_menu_set_as);
copy.setEnabled(activeTerminal);
copy.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// mark as copying and reset any previous bounds
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
copySource = terminalView.bridge;
SelectionArea area = copySource.getSelectionArea();
area.reset();
area.setBounds(copySource.buffer.getColumns(), copySource.buffer.getRows());
copySource.setSelectingForCopy(true);
// Make sure we show the initial selection
copySource.redraw();
Toast.makeText(ConsoleActivity.this, getString(R.string.console_copy_start), Toast.LENGTH_LONG).show();
return true;
}
});
paste = menu.add(R.string.console_menu_paste);
if (hardKeyboard)
paste.setAlphabeticShortcut('v');
paste.setIcon(android.R.drawable.ic_menu_edit);
paste.setEnabled(clipboard.hasText() && sessionOpen);
paste.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// force insert of clipboard text into current console
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
TerminalBridge bridge = terminalView.bridge;
// pull string from clipboard and generate all events to force down
String clip = clipboard.getText().toString();
bridge.injectString(clip);
return true;
}
});
portForward = menu.add(R.string.console_menu_portforwards);
if (hardKeyboard)
portForward.setAlphabeticShortcut('f');
portForward.setIcon(android.R.drawable.ic_menu_manage);
portForward.setEnabled(sessionOpen && canForwardPorts);
portForward.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
TerminalBridge bridge = terminalView.bridge;
Intent intent = new Intent(ConsoleActivity.this, PortForwardListActivity.class);
intent.putExtra(Intent.EXTRA_TITLE, bridge.host.getId());
ConsoleActivity.this.startActivityForResult(intent, REQUEST_EDIT);
return true;
}
});
urlscan = menu.add(R.string.console_menu_urlscan);
if (hardKeyboard)
urlscan.setAlphabeticShortcut('u');
urlscan.setIcon(android.R.drawable.ic_menu_search);
urlscan.setEnabled(activeTerminal);
urlscan.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
final TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
List<String> urls = terminalView.bridge.scanForURLs();
Dialog urlDialog = new Dialog(ConsoleActivity.this);
urlDialog.setTitle(R.string.console_menu_urlscan);
ListView urlListView = new ListView(ConsoleActivity.this);
URLItemListener urlListener = new URLItemListener(ConsoleActivity.this);
urlListView.setOnItemClickListener(urlListener);
urlListView.setAdapter(new ArrayAdapter<String>(ConsoleActivity.this, android.R.layout.simple_list_item_1, urls));
urlDialog.setContentView(urlListView);
urlDialog.show();
return true;
}
});
resize = menu.add(R.string.console_menu_resize);
if (hardKeyboard)
resize.setAlphabeticShortcut('s');
resize.setIcon(android.R.drawable.ic_menu_crop);
resize.setEnabled(sessionOpen);
resize.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
final TerminalView terminalView = (TerminalView) findCurrentView(R.id.console_flip);
final View resizeView = inflater.inflate(R.layout.dia_resize, null, false);
new AlertDialog.Builder(ConsoleActivity.this)
.setView(resizeView)
.setPositiveButton(R.string.button_resize, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
int width, height;
try {
width = Integer.parseInt(((EditText) resizeView
.findViewById(R.id.width))
.getText().toString());
height = Integer.parseInt(((EditText) resizeView
.findViewById(R.id.height))
.getText().toString());
} catch (NumberFormatException nfe) {
// TODO change this to a real dialog where we can
// make the input boxes turn red to indicate an error.
return;
}
terminalView.forceSize(width, height);
}
}).setNegativeButton(android.R.string.cancel, null).create().show();
return true;
}
});
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
setVolumeControlStream(AudioManager.STREAM_NOTIFICATION);
final View view = findCurrentView(R.id.console_flip);
boolean activeTerminal = (view instanceof TerminalView);
boolean sessionOpen = false;
boolean disconnected = false;
boolean canForwardPorts = false;
if (activeTerminal) {
TerminalBridge bridge = ((TerminalView) view).bridge;
sessionOpen = bridge.isSessionOpen();
disconnected = bridge.isDisconnected();
canForwardPorts = bridge.canFowardPorts();
}
disconnect.setEnabled(activeTerminal);
if (sessionOpen || !disconnected)
disconnect.setTitle(R.string.list_host_disconnect);
else
disconnect.setTitle(R.string.console_menu_close);
copy.setEnabled(activeTerminal);
paste.setEnabled(clipboard.hasText() && sessionOpen);
portForward.setEnabled(sessionOpen && canForwardPorts);
urlscan.setEnabled(activeTerminal);
resize.setEnabled(sessionOpen);
return true;
}
@Override
public void onOptionsMenuClosed(Menu menu) {
super.onOptionsMenuClosed(menu);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
@Override
public void onStart() {
super.onStart();
// connect with manager service to find all bridges
// when connected it will insert all views
bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
}
@Override
public void onPause() {
super.onPause();
Log.d(TAG, "onPause called");
if (forcedOrientation && bound != null)
bound.setResizeAllowed(false);
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume called");
// Make sure we don't let the screen fall asleep.
// This also keeps the Wi-Fi chipset from disconnecting us.
if (prefs.getBoolean(PreferenceConstants.KEEP_ALIVE, true)) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
} else {
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
configureOrientation();
if (forcedOrientation && bound != null)
bound.setResizeAllowed(true);
}
/* (non-Javadoc)
* @see android.app.Activity#onNewIntent(android.content.Intent)
*/
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.d(TAG, "onNewIntent called");
requested = intent.getData();
if (requested == null) {
Log.e(TAG, "Got null intent data in onNewIntent()");
return;
}
if (bound == null) {
Log.e(TAG, "We're not bound in onNewIntent()");
return;
}
TerminalBridge requestedBridge = bound.getConnectedBridge(requested.getFragment());
int requestedIndex = 0;
synchronized (flip) {
if (requestedBridge == null) {
// If we didn't find the requested connection, try opening it
try {
Log.d(TAG, String.format("We couldnt find an existing bridge with URI=%s (nickname=%s),"+
"so creating one now", requested.toString(), requested.getFragment()));
requestedBridge = bound.openConnection(requested);
} catch(Exception e) {
Log.e(TAG, "Problem while trying to create new requested bridge from URI", e);
// TODO: We should display an error dialog here.
return;
}
requestedIndex = addNewTerminalView(requestedBridge);
} else {
final int flipIndex = getFlipIndex(requestedBridge);
if (flipIndex > requestedIndex) {
requestedIndex = flipIndex;
}
}
setDisplayedTerminal(requestedIndex);
}
}
@Override
public void onStop() {
super.onStop();
unbindService(connection);
}
protected void shiftCurrentTerminal(final int direction) {
View overlay;
synchronized (flip) {
boolean shouldAnimate = flip.getChildCount() > 1;
// Only show animation if there is something else to go to.
if (shouldAnimate) {
// keep current overlay from popping up again
overlay = findCurrentView(R.id.terminal_overlay);
if (overlay != null)
overlay.startAnimation(fade_stay_hidden);
if (direction == SHIFT_LEFT) {
flip.setInAnimation(slide_left_in);
flip.setOutAnimation(slide_left_out);
flip.showNext();
} else if (direction == SHIFT_RIGHT) {
flip.setInAnimation(slide_right_in);
flip.setOutAnimation(slide_right_out);
flip.showPrevious();
}
}
ConsoleActivity.this.updateDefault();
if (shouldAnimate) {
// show overlay on new slide and start fade
overlay = findCurrentView(R.id.terminal_overlay);
if (overlay != null)
overlay.startAnimation(fade_out_delayed);
}
updatePromptVisible();
}
}
/**
* Save the currently shown {@link TerminalView} as the default. This is
* saved back down into {@link TerminalManager} where we can read it again
* later.
*/
private void updateDefault() {
// update the current default terminal
View view = findCurrentView(R.id.console_flip);
if(!(view instanceof TerminalView)) return;
TerminalView terminal = (TerminalView)view;
if(bound == null) return;
bound.defaultBridge = terminal.bridge;
}
protected void updateEmptyVisible() {
// update visibility of empty status message
empty.setVisibility((flip.getChildCount() == 0) ? View.VISIBLE : View.GONE);
}
/**
* Show any prompts requested by the currently visible {@link TerminalView}.
*/
protected void updatePromptVisible() {
// check if our currently-visible terminalbridge is requesting any prompt services
View view = findCurrentView(R.id.console_flip);
// Hide all the prompts in case a prompt request was canceled
hideAllPrompts();
if(!(view instanceof TerminalView)) {
// we dont have an active view, so hide any prompts
return;
}
PromptHelper prompt = ((TerminalView)view).bridge.promptHelper;
if(String.class.equals(prompt.promptRequested)) {
stringPromptGroup.setVisibility(View.VISIBLE);
String instructions = prompt.promptInstructions;
if (instructions != null && instructions.length() > 0) {
stringPromptInstructions.setVisibility(View.VISIBLE);
stringPromptInstructions.setText(instructions);
} else
stringPromptInstructions.setVisibility(View.GONE);
stringPrompt.setText("");
stringPrompt.setHint(prompt.promptHint);
stringPrompt.requestFocus();
} else if(Boolean.class.equals(prompt.promptRequested)) {
booleanPromptGroup.setVisibility(View.VISIBLE);
booleanPrompt.setText(prompt.promptHint);
booleanYes.requestFocus();
} else {
hideAllPrompts();
view.requestFocus();
}
}
private class URLItemListener implements OnItemClickListener {
private WeakReference<Context> contextRef;
URLItemListener(Context context) {
this.contextRef = new WeakReference<Context>(context);
}
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
Context context = contextRef.get();
if (context == null)
return;
try {
TextView urlView = (TextView) view;
String url = urlView.getText().toString();
if (url.indexOf("://") < 0)
url = "http://" + url;
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(intent);
} catch (Exception e) {
Log.e(TAG, "couldn't open URL", e);
// We should probably tell the user that we couldn't find a handler...
}
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
Log.d(TAG, String.format("onConfigurationChanged; requestedOrientation=%d, newConfig.orientation=%d", getRequestedOrientation(), newConfig.orientation));
if (bound != null) {
if (forcedOrientation &&
(newConfig.orientation != Configuration.ORIENTATION_LANDSCAPE &&
getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) ||
(newConfig.orientation != Configuration.ORIENTATION_PORTRAIT &&
getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT))
bound.setResizeAllowed(false);
else
bound.setResizeAllowed(true);
bound.hardKeyboardHidden = (newConfig.hardKeyboardHidden == Configuration.HARDKEYBOARDHIDDEN_YES);
mKeyboardButton.setVisibility(bound.hardKeyboardHidden ? View.VISIBLE : View.GONE);
}
}
/**
* Adds a new TerminalBridge to the current set of views in our ViewFlipper.
*
* @param bridge TerminalBridge to add to our ViewFlipper
* @return the child index of the new view in the ViewFlipper
*/
private int addNewTerminalView(TerminalBridge bridge) {
// let them know about our prompt handler services
bridge.promptHelper.setHandler(promptHandler);
// inflate each terminal view
RelativeLayout view = (RelativeLayout)inflater.inflate(R.layout.item_terminal, flip, false);
// set the terminal overlay text
TextView overlay = (TextView)view.findViewById(R.id.terminal_overlay);
overlay.setText(bridge.host.getNickname());
// and add our terminal view control, using index to place behind overlay
TerminalView terminal = new TerminalView(ConsoleActivity.this, bridge);
terminal.setId(R.id.console_flip);
view.addView(terminal, 0);
synchronized (flip) {
// finally attach to the flipper
flip.addView(view);
return flip.getChildCount() - 1;
}
}
private int getFlipIndex(TerminalBridge bridge) {
synchronized (flip) {
final int children = flip.getChildCount();
for (int i = 0; i < children; i++) {
final View view = flip.getChildAt(i).findViewById(R.id.console_flip);
if (view == null || !(view instanceof TerminalView)) {
// How did that happen?
continue;
}
final TerminalView tv = (TerminalView) view;
if (tv.bridge == bridge) {
return i;
}
}
}
return -1;
}
/**
* Displays the child in the ViewFlipper at the requestedIndex and updates the prompts.
*
* @param requestedIndex the index of the terminal view to display
*/
private void setDisplayedTerminal(int requestedIndex) {
synchronized (flip) {
try {
// show the requested bridge if found, also fade out overlay
flip.setDisplayedChild(requestedIndex);
flip.getCurrentView().findViewById(R.id.terminal_overlay)
.startAnimation(fade_out_delayed);
} catch (NullPointerException npe) {
Log.d(TAG, "View went away when we were about to display it", npe);
}
updatePromptVisible();
updateEmptyVisible();
}
}
}
| Java |
/*
* 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.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
/**
* @author Kenny Root
*
*/
public class HelpActivity extends Activity {
public final static String TAG = "ConnectBot.HelpActivity";
public final static String HELPDIR = "help";
public final static String SUFFIX = ".html";
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.act_help);
this.setTitle(String.format("%s: %s",
getResources().getText(R.string.app_name),
getResources().getText(R.string.title_help)));
AssetManager am = this.getAssets();
LinearLayout content = (LinearLayout)this.findViewById(R.id.topics);
try {
for (String name : am.list(HELPDIR)) {
if (name.endsWith(SUFFIX)) {
Button button = new Button(this);
final String topic = name.substring(0, name.length() - SUFFIX.length());
button.setText(topic);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(HelpActivity.this, HelpTopicActivity.class);
intent.putExtra(Intent.EXTRA_TITLE, topic);
HelpActivity.this.startActivity(intent);
}
});
content.addView(button);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "couldn't get list of help assets", e);
}
}
}
| Java |
/*
* 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.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.connectbot.bean.SelectionArea;
import org.connectbot.service.FontSizeChangedListener;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalKeyListener;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelXorXfermode;
import android.graphics.RectF;
import android.net.Uri;
import android.os.AsyncTask;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityManager;
import android.view.inputmethod.BaseInputConnection;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputConnection;
import android.widget.Toast;
import de.mud.terminal.VDUBuffer;
/**
* User interface {@link View} for showing a TerminalBridge in an
* {@link Activity}. Handles drawing bitmap updates and passing keystrokes down
* to terminal.
*
* @author jsharkey
*/
public class TerminalView extends View implements FontSizeChangedListener {
private final Context context;
public final TerminalBridge bridge;
private final Paint paint;
private final Paint cursorPaint;
private final Paint cursorStrokePaint;
// Cursor paints to distinguish modes
private Path ctrlCursor, altCursor, shiftCursor;
private RectF tempSrc, tempDst;
private Matrix scaleMatrix;
private static final Matrix.ScaleToFit scaleType = Matrix.ScaleToFit.FILL;
private Toast notification = null;
private String lastNotification = null;
private volatile boolean notifications = true;
// Related to Accessibility Features
private boolean mAccessibilityInitialized = false;
private boolean mAccessibilityActive = true;
private Object[] mAccessibilityLock = new Object[0];
private StringBuffer mAccessibilityBuffer;
private Pattern mControlCodes = null;
private Matcher mCodeMatcher = null;
private AccessibilityEventSender mEventSender = null;
private static final String BACKSPACE_CODE = "\\x08\\x1b\\[K";
private static final String CONTROL_CODE_PATTERN = "\\x1b\\[K[^m]+[m|:]";
private static final int ACCESSIBILITY_EVENT_THRESHOLD = 1000;
private static final String SCREENREADER_INTENT_ACTION = "android.accessibilityservice.AccessibilityService";
private static final String SCREENREADER_INTENT_CATEGORY = "android.accessibilityservice.category.FEEDBACK_SPOKEN";
public TerminalView(Context context, TerminalBridge bridge) {
super(context);
this.context = context;
this.bridge = bridge;
paint = new Paint();
setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
setFocusable(true);
setFocusableInTouchMode(true);
cursorPaint = new Paint();
cursorPaint.setColor(bridge.color[bridge.defaultFg]);
cursorPaint.setXfermode(new PixelXorXfermode(bridge.color[bridge.defaultBg]));
cursorPaint.setAntiAlias(true);
cursorStrokePaint = new Paint(cursorPaint);
cursorStrokePaint.setStrokeWidth(0.1f);
cursorStrokePaint.setStyle(Paint.Style.STROKE);
/*
* Set up our cursor indicators on a 1x1 Path object which we can later
* transform to our character width and height
*/
// TODO make this into a resource somehow
shiftCursor = new Path();
shiftCursor.lineTo(0.5f, 0.33f);
shiftCursor.lineTo(1.0f, 0.0f);
altCursor = new Path();
altCursor.moveTo(0.0f, 1.0f);
altCursor.lineTo(0.5f, 0.66f);
altCursor.lineTo(1.0f, 1.0f);
ctrlCursor = new Path();
ctrlCursor.moveTo(0.0f, 0.25f);
ctrlCursor.lineTo(1.0f, 0.5f);
ctrlCursor.lineTo(0.0f, 0.75f);
// For creating the transform when the terminal resizes
tempSrc = new RectF();
tempSrc.set(0.0f, 0.0f, 1.0f, 1.0f);
tempDst = new RectF();
scaleMatrix = new Matrix();
bridge.addFontSizeChangedListener(this);
// connect our view up to the bridge
setOnKeyListener(bridge.getKeyHandler());
mAccessibilityBuffer = new StringBuffer();
// Enable accessibility features if a screen reader is active.
new AccessibilityStateTester().execute((Void) null);
}
public void destroy() {
// tell bridge to destroy its bitmap
bridge.parentDestroyed();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
bridge.parentChanged(this);
scaleCursors();
}
public void onFontSizeChanged(float size) {
scaleCursors();
}
private void scaleCursors() {
// Create a scale matrix to scale our 1x1 representation of the cursor
tempDst.set(0.0f, 0.0f, bridge.charWidth, bridge.charHeight);
scaleMatrix.setRectToRect(tempSrc, tempDst, scaleType);
}
@Override
public void onDraw(Canvas canvas) {
if(bridge.bitmap != null) {
// draw the bitmap
bridge.onDraw();
// draw the bridge bitmap if it exists
canvas.drawBitmap(bridge.bitmap, 0, 0, paint);
// also draw cursor if visible
if (bridge.buffer.isCursorVisible()) {
int cursorColumn = bridge.buffer.getCursorColumn();
final int cursorRow = bridge.buffer.getCursorRow();
final int columns = bridge.buffer.getColumns();
if (cursorColumn == columns)
cursorColumn = columns - 1;
if (cursorColumn < 0 || cursorRow < 0)
return;
int currentAttribute = bridge.buffer.getAttributes(
cursorColumn, cursorRow);
boolean onWideCharacter = (currentAttribute & VDUBuffer.FULLWIDTH) != 0;
int x = cursorColumn * bridge.charWidth;
int y = (bridge.buffer.getCursorRow()
+ bridge.buffer.screenBase - bridge.buffer.windowBase)
* bridge.charHeight;
// Save the current clip and translation
canvas.save();
canvas.translate(x, y);
canvas.clipRect(0, 0,
bridge.charWidth * (onWideCharacter ? 2 : 1),
bridge.charHeight);
canvas.drawPaint(cursorPaint);
final int deadKey = bridge.getKeyHandler().getDeadKey();
if (deadKey != 0) {
canvas.drawText(new char[] { (char)deadKey }, 0, 1, 0, 0, cursorStrokePaint);
}
// Make sure we scale our decorations to the correct size.
canvas.concat(scaleMatrix);
int metaState = bridge.getKeyHandler().getMetaState();
if ((metaState & TerminalKeyListener.META_SHIFT_ON) != 0)
canvas.drawPath(shiftCursor, cursorStrokePaint);
else if ((metaState & TerminalKeyListener.META_SHIFT_LOCK) != 0)
canvas.drawPath(shiftCursor, cursorPaint);
if ((metaState & TerminalKeyListener.META_ALT_ON) != 0)
canvas.drawPath(altCursor, cursorStrokePaint);
else if ((metaState & TerminalKeyListener.META_ALT_LOCK) != 0)
canvas.drawPath(altCursor, cursorPaint);
if ((metaState & TerminalKeyListener.META_CTRL_ON) != 0)
canvas.drawPath(ctrlCursor, cursorStrokePaint);
else if ((metaState & TerminalKeyListener.META_CTRL_LOCK) != 0)
canvas.drawPath(ctrlCursor, cursorPaint);
// Restore previous clip region
canvas.restore();
}
// draw any highlighted area
if (bridge.isSelectingForCopy()) {
SelectionArea area = bridge.getSelectionArea();
canvas.save(Canvas.CLIP_SAVE_FLAG);
canvas.clipRect(
area.getLeft() * bridge.charWidth,
area.getTop() * bridge.charHeight,
(area.getRight() + 1) * bridge.charWidth,
(area.getBottom() + 1) * bridge.charHeight
);
canvas.drawPaint(cursorPaint);
canvas.restore();
}
}
}
public void notifyUser(String message) {
if (!notifications)
return;
if (notification != null) {
// Don't keep telling the user the same thing.
if (lastNotification != null && lastNotification.equals(message))
return;
notification.setText(message);
notification.show();
} else {
notification = Toast.makeText(context, message, Toast.LENGTH_SHORT);
notification.show();
}
lastNotification = message;
}
/**
* Ask the {@link TerminalBridge} we're connected to to resize to a specific size.
* @param width
* @param height
*/
public void forceSize(int width, int height) {
bridge.resizeComputed(width, height, getWidth(), getHeight());
}
/**
* Sets the ability for the TerminalView to display Toast notifications to the user.
* @param value whether to enable notifications or not
*/
public void setNotifications(boolean value) {
notifications = value;
}
@Override
public boolean onCheckIsTextEditor() {
return true;
}
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
outAttrs.imeOptions |=
EditorInfo.IME_FLAG_NO_EXTRACT_UI |
EditorInfo.IME_FLAG_NO_ENTER_ACTION |
EditorInfo.IME_ACTION_NONE;
outAttrs.inputType = EditorInfo.TYPE_NULL;
return new BaseInputConnection(this, false) {
@Override
public boolean deleteSurroundingText (int leftLength, int rightLength) {
if (rightLength == 0 && leftLength == 0) {
return this.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
}
for (int i = 0; i < leftLength; i++) {
this.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
}
// TODO: forward delete
return true;
}
};
}
public void propagateConsoleText(char[] rawText, int length) {
if (mAccessibilityActive) {
synchronized (mAccessibilityLock) {
mAccessibilityBuffer.append(rawText, 0, length);
}
if (mAccessibilityInitialized) {
if (mEventSender != null) {
removeCallbacks(mEventSender);
} else {
mEventSender = new AccessibilityEventSender();
}
postDelayed(mEventSender, ACCESSIBILITY_EVENT_THRESHOLD);
}
}
}
private class AccessibilityEventSender implements Runnable {
public void run() {
synchronized (mAccessibilityLock) {
if (mCodeMatcher == null) {
mCodeMatcher = mControlCodes.matcher(mAccessibilityBuffer);
} else {
mCodeMatcher.reset(mAccessibilityBuffer);
}
// Strip all control codes out.
mAccessibilityBuffer = new StringBuffer(mCodeMatcher.replaceAll(" "));
// Apply Backspaces using backspace character sequence
int i = mAccessibilityBuffer.indexOf(BACKSPACE_CODE);
while (i != -1) {
mAccessibilityBuffer = mAccessibilityBuffer.replace(i == 0 ? 0 : i - 1, i
+ BACKSPACE_CODE.length(), "");
i = mAccessibilityBuffer.indexOf(BACKSPACE_CODE);
}
if (mAccessibilityBuffer.length() > 0) {
AccessibilityEvent event = AccessibilityEvent.obtain(
AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED);
event.setFromIndex(0);
event.setAddedCount(mAccessibilityBuffer.length());
event.getText().add(mAccessibilityBuffer);
sendAccessibilityEventUnchecked(event);
mAccessibilityBuffer.setLength(0);
}
}
}
}
private class AccessibilityStateTester extends AsyncTask<Void, Void, Boolean> {
@Override
protected Boolean doInBackground(Void... params) {
/*
* Presumably if the accessibility manager is not enabled, we don't
* need to send accessibility events.
*/
final AccessibilityManager accessibility = (AccessibilityManager) context
.getSystemService(Context.ACCESSIBILITY_SERVICE);
if (!accessibility.isEnabled()) {
return false;
}
/*
* Restrict the set of intents to only accessibility services that
* have the category FEEDBACK_SPOKEN (aka, screen readers).
*/
final Intent screenReaderIntent = new Intent(SCREENREADER_INTENT_ACTION);
screenReaderIntent.addCategory(SCREENREADER_INTENT_CATEGORY);
final ContentResolver cr = context.getContentResolver();
final List<ResolveInfo> screenReaders = context.getPackageManager().queryIntentServices(
screenReaderIntent, 0);
boolean foundScreenReader = false;
final int N = screenReaders.size();
for (int i = 0; i < N; i++) {
final ResolveInfo screenReader = screenReaders.get(i);
/*
* All screen readers are expected to implement a content
* provider that responds to:
* content://<nameofpackage>.providers.StatusProvider
*/
final Cursor cursor = cr.query(
Uri.parse("content://" + screenReader.serviceInfo.packageName
+ ".providers.StatusProvider"), null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
/*
* These content providers use a special cursor that only has
* one element, an integer that is 1 if the screen reader is
* running.
*/
final int status = cursor.getInt(0);
cursor.close();
if (status == 1) {
foundScreenReader = true;
break;
}
}
}
if (foundScreenReader) {
mControlCodes = Pattern.compile(CONTROL_CODE_PATTERN);
}
return foundScreenReader;
}
@Override
protected void onPostExecute(Boolean result) {
mAccessibilityActive = result;
mAccessibilityInitialized = true;
if (result) {
mEventSender = new AccessibilityEventSender();
postDelayed(mEventSender, ACCESSIBILITY_EVENT_THRESHOLD);
} else {
mAccessibilityBuffer = null;
}
}
}
}
| Java |
/*
* 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 org.connectbot.util.HelpTopicView;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
/**
* @author Kenny Root
*
*/
public class HelpTopicActivity extends Activity {
public final static String TAG = "ConnectBot.HelpActivity";
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.act_help_topic);
String topic = getIntent().getStringExtra(Intent.EXTRA_TITLE);
this.setTitle(String.format("%s: %s - %s",
getResources().getText(R.string.app_name),
getResources().getText(R.string.title_help),
topic));
HelpTopicView helpTopic = (HelpTopicView) findViewById(R.id.topic_text);
helpTopic.setTopic(topic);
}
}
| Java |
/*
* 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.Set;
import java.util.Map.Entry;
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.PreferenceActivity;
import android.util.Log;
public class HostEditorActivity extends PreferenceActivity 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 dont have any floating cursor to dispose later
SQLiteDatabase db = hostdb.getReadableDatabase();
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);
if(key.equals(HostDatabase.FIELD_HOST_HOSTKEY)) continue;
String value = cursor.getString(i);
values.put(key, value);
}
}
cursor.close();
db.close();
// db = pubkeydb.getReadableDatabase();
// cursor = db.query(PubkeyDatabase.TABLE_PUBKEYS,
// new String[] { "_id", PubkeyDatabase.FIELD_PUBKEY_NICKNAME },
// null, null, null, null, null);
//
// if (cursor.moveToFirst()) {
// do {
// String pubkeyid = String.valueOf(cursor.getLong(0));
// String value = cursor.getString(1);
// pubkeys.put(pubkeyid, value);
// } while (cursor.moveToNext());
// }
//
// cursor.close();
// db.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() {
//Log.d(this.getClass().toString(), "commit() changes back to database");
SQLiteDatabase db = hostdb.getWritableDatabase();
db.update(table, update, "_id = ?", new String[] { String.valueOf(id) });
db.close();
// 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 = "ConnectBot.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 = new HostDatabase(this);
this.pubkeydb = new PubkeyDatabase(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)this.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);
if(this.hostdb == null)
this.hostdb = new HostDatabase(this);
if(this.pubkeydb == null)
this.pubkeydb = new PubkeyDatabase(this);
}
@Override
public void onStop() {
super.onStop();
unbindService(connection);
if(this.hostdb != null) {
this.hostdb.close();
this.hostdb = null;
}
if(this.pubkeydb != null) {
this.pubkeydb.close();
this.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) 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;
}
}
}
| Java |
/*
* 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.transport;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
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.regex.Matcher;
import java.util.regex.Pattern;
import org.connectbot.R;
import org.connectbot.bean.HostBean;
import org.connectbot.bean.PortForwardBean;
import org.connectbot.bean.PubkeyBean;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import org.connectbot.service.TerminalManager.KeyHolder;
import org.connectbot.util.HostDatabase;
import org.connectbot.util.PubkeyDatabase;
import org.connectbot.util.PubkeyUtils;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.trilead.ssh2.AuthAgentCallback;
import com.trilead.ssh2.ChannelCondition;
import com.trilead.ssh2.Connection;
import com.trilead.ssh2.ConnectionInfo;
import com.trilead.ssh2.ConnectionMonitor;
import com.trilead.ssh2.DynamicPortForwarder;
import com.trilead.ssh2.InteractiveCallback;
import com.trilead.ssh2.KnownHosts;
import com.trilead.ssh2.LocalPortForwarder;
import com.trilead.ssh2.ServerHostKeyVerifier;
import com.trilead.ssh2.Session;
import com.trilead.ssh2.crypto.PEMDecoder;
import com.trilead.ssh2.signature.DSAPrivateKey;
import com.trilead.ssh2.signature.DSAPublicKey;
import com.trilead.ssh2.signature.DSASHA1Verify;
import com.trilead.ssh2.signature.RSAPrivateKey;
import com.trilead.ssh2.signature.RSAPublicKey;
import com.trilead.ssh2.signature.RSASHA1Verify;
/**
* @author Kenny Root
*
*/
public class SSH extends AbsTransport implements ConnectionMonitor, InteractiveCallback, AuthAgentCallback {
public SSH() {
super();
}
/**
* @param bridge
* @param db
*/
public SSH(HostBean host, TerminalBridge bridge, TerminalManager manager) {
super(host, bridge, manager);
}
private static final String PROTOCOL = "ssh";
private static final String TAG = "ConnectBot.SSH";
private static final int DEFAULT_PORT = 22;
private static final String AUTH_PUBLICKEY = "publickey",
AUTH_PASSWORD = "password",
AUTH_KEYBOARDINTERACTIVE = "keyboard-interactive";
private final static int AUTH_TRIES = 20;
static final Pattern hostmask;
static {
hostmask = Pattern.compile("^(.+)@([0-9a-z.-]+)(:(\\d+))?$", Pattern.CASE_INSENSITIVE);
}
private boolean compression = false;
private volatile boolean authenticated = false;
private volatile boolean connected = false;
private volatile boolean sessionOpen = false;
private boolean pubkeysExhausted = false;
private boolean interactiveCanContinue = true;
private Connection connection;
private Session session;
private ConnectionInfo connectionInfo;
private OutputStream stdin;
private InputStream stdout;
private InputStream stderr;
private static final int conditions = ChannelCondition.STDOUT_DATA
| ChannelCondition.STDERR_DATA
| ChannelCondition.CLOSED
| ChannelCondition.EOF;
private List<PortForwardBean> portForwards = new LinkedList<PortForwardBean>();
private int columns;
private int rows;
private int width;
private int height;
private String useAuthAgent = HostDatabase.AUTHAGENT_NO;
private String agentLockPassphrase;
public class HostKeyVerifier implements ServerHostKeyVerifier {
public boolean verifyServerHostKey(String hostname, int port,
String serverHostKeyAlgorithm, byte[] serverHostKey) throws IOException {
// read in all known hosts from hostdb
KnownHosts hosts = manager.hostdb.getKnownHosts();
Boolean result;
String matchName = String.format("%s:%d", hostname, port);
String fingerprint = KnownHosts.createHexFingerprint(serverHostKeyAlgorithm, serverHostKey);
String algorithmName;
if ("ssh-rsa".equals(serverHostKeyAlgorithm))
algorithmName = "RSA";
else if ("ssh-dss".equals(serverHostKeyAlgorithm))
algorithmName = "DSA";
else
algorithmName = serverHostKeyAlgorithm;
switch(hosts.verifyHostkey(matchName, serverHostKeyAlgorithm, serverHostKey)) {
case KnownHosts.HOSTKEY_IS_OK:
bridge.outputLine(manager.res.getString(R.string.terminal_sucess, algorithmName, fingerprint));
return true;
case KnownHosts.HOSTKEY_IS_NEW:
// prompt user
bridge.outputLine(manager.res.getString(R.string.host_authenticity_warning, hostname));
bridge.outputLine(manager.res.getString(R.string.host_fingerprint, algorithmName, fingerprint));
result = bridge.promptHelper.requestBooleanPrompt(null, manager.res.getString(R.string.prompt_continue_connecting));
if(result == null) return false;
if(result.booleanValue()) {
// save this key in known database
manager.hostdb.saveKnownHost(hostname, port, serverHostKeyAlgorithm, serverHostKey);
}
return result.booleanValue();
case KnownHosts.HOSTKEY_HAS_CHANGED:
String header = String.format("@ %s @",
manager.res.getString(R.string.host_verification_failure_warning_header));
char[] atsigns = new char[header.length()];
Arrays.fill(atsigns, '@');
String border = new String(atsigns);
bridge.outputLine(border);
bridge.outputLine(manager.res.getString(R.string.host_verification_failure_warning));
bridge.outputLine(border);
bridge.outputLine(String.format(manager.res.getString(R.string.host_fingerprint),
algorithmName, fingerprint));
// Users have no way to delete keys, so we'll prompt them for now.
result = bridge.promptHelper.requestBooleanPrompt(null, manager.res.getString(R.string.prompt_continue_connecting));
if(result == null) return false;
if(result.booleanValue()) {
// save this key in known database
manager.hostdb.saveKnownHost(hostname, port, serverHostKeyAlgorithm, serverHostKey);
}
return result.booleanValue();
default:
return false;
}
}
}
private void authenticate() {
try {
if (connection.authenticateWithNone(host.getUsername())) {
finishConnection();
return;
}
} catch(Exception e) {
Log.d(TAG, "Host does not support 'none' authentication.");
}
bridge.outputLine(manager.res.getString(R.string.terminal_auth));
try {
long pubkeyId = host.getPubkeyId();
if (!pubkeysExhausted &&
pubkeyId != HostDatabase.PUBKEYID_NEVER &&
connection.isAuthMethodAvailable(host.getUsername(), AUTH_PUBLICKEY)) {
// if explicit pubkey defined for this host, then prompt for password as needed
// otherwise just try all in-memory keys held in terminalmanager
if (pubkeyId == HostDatabase.PUBKEYID_ANY) {
// try each of the in-memory keys
bridge.outputLine(manager.res
.getString(R.string.terminal_auth_pubkey_any));
for (Entry<String, KeyHolder> entry : manager.loadedKeypairs.entrySet()) {
if (entry.getValue().bean.isConfirmUse()
&& !promptForPubkeyUse(entry.getKey()))
continue;
if (this.tryPublicKey(host.getUsername(), entry.getKey(),
entry.getValue().trileadKey)) {
finishConnection();
break;
}
}
} else {
bridge.outputLine(manager.res.getString(R.string.terminal_auth_pubkey_specific));
// use a specific key for this host, as requested
PubkeyBean pubkey = manager.pubkeydb.findPubkeyById(pubkeyId);
if (pubkey == null)
bridge.outputLine(manager.res.getString(R.string.terminal_auth_pubkey_invalid));
else
if (tryPublicKey(pubkey))
finishConnection();
}
pubkeysExhausted = true;
} else if (interactiveCanContinue &&
connection.isAuthMethodAvailable(host.getUsername(), AUTH_KEYBOARDINTERACTIVE)) {
// this auth method will talk with us using InteractiveCallback interface
// it blocks until authentication finishes
bridge.outputLine(manager.res.getString(R.string.terminal_auth_ki));
interactiveCanContinue = false;
if(connection.authenticateWithKeyboardInteractive(host.getUsername(), this)) {
finishConnection();
} else {
bridge.outputLine(manager.res.getString(R.string.terminal_auth_ki_fail));
}
} else if (connection.isAuthMethodAvailable(host.getUsername(), AUTH_PASSWORD)) {
bridge.outputLine(manager.res.getString(R.string.terminal_auth_pass));
String password = bridge.getPromptHelper().requestStringPrompt(null,
manager.res.getString(R.string.prompt_password));
if (password != null
&& connection.authenticateWithPassword(host.getUsername(), password)) {
finishConnection();
} else {
bridge.outputLine(manager.res.getString(R.string.terminal_auth_pass_fail));
}
} else {
bridge.outputLine(manager.res.getString(R.string.terminal_auth_fail));
}
} catch (IllegalStateException e) {
Log.e(TAG, "Connection went away while we were trying to authenticate", e);
return;
} catch(Exception e) {
Log.e(TAG, "Problem during handleAuthentication()", e);
}
}
/**
* Attempt connection with database row pointed to by cursor.
* @param cursor
* @return true for successful authentication
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws IOException
*/
private boolean tryPublicKey(PubkeyBean pubkey) throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
Object trileadKey = null;
if(manager.isKeyLoaded(pubkey.getNickname())) {
// load this key from memory if its already there
Log.d(TAG, String.format("Found unlocked key '%s' already in-memory", pubkey.getNickname()));
if (pubkey.isConfirmUse()) {
if (!promptForPubkeyUse(pubkey.getNickname()))
return false;
}
trileadKey = manager.getKey(pubkey.getNickname());
} else {
// otherwise load key from database and prompt for password as needed
String password = null;
if (pubkey.isEncrypted()) {
password = bridge.getPromptHelper().requestStringPrompt(null,
manager.res.getString(R.string.prompt_pubkey_password, pubkey.getNickname()));
// Something must have interrupted the prompt.
if (password == null)
return false;
}
if(PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType())) {
// load specific key using pem format
trileadKey = PEMDecoder.decode(new String(pubkey.getPrivateKey()).toCharArray(), password);
} else {
// load using internal generated format
PrivateKey privKey;
try {
privKey = PubkeyUtils.decodePrivate(pubkey.getPrivateKey(),
pubkey.getType(), password);
} catch (Exception e) {
String message = String.format("Bad password for key '%s'. Authentication failed.", pubkey.getNickname());
Log.e(TAG, message, e);
bridge.outputLine(message);
return false;
}
PublicKey pubKey = pubkey.getPublicKey();
// convert key to trilead format
trileadKey = PubkeyUtils.convertToTrilead(privKey, pubKey);
Log.d(TAG, "Unlocked key " + PubkeyUtils.formatKey(pubKey));
}
Log.d(TAG, String.format("Unlocked key '%s'", pubkey.getNickname()));
// save this key in memory
manager.addKey(pubkey, trileadKey);
}
return tryPublicKey(host.getUsername(), pubkey.getNickname(), trileadKey);
}
private boolean tryPublicKey(String username, String keyNickname, Object trileadKey) throws IOException {
//bridge.outputLine(String.format("Attempting 'publickey' with key '%s' [%s]...", keyNickname, trileadKey.toString()));
boolean success = connection.authenticateWithPublicKey(username, trileadKey);
if(!success)
bridge.outputLine(manager.res.getString(R.string.terminal_auth_pubkey_fail, keyNickname));
return success;
}
/**
* Internal method to request actual PTY terminal once we've finished
* authentication. If called before authenticated, it will just fail.
*/
private void finishConnection() {
authenticated = true;
for (PortForwardBean portForward : portForwards) {
try {
enablePortForward(portForward);
bridge.outputLine(manager.res.getString(R.string.terminal_enable_portfoward, portForward.getDescription()));
} catch (Exception e) {
Log.e(TAG, "Error setting up port forward during connect", e);
}
}
if (!host.getWantSession()) {
bridge.outputLine(manager.res.getString(R.string.terminal_no_session));
bridge.onConnected();
return;
}
try {
session = connection.openSession();
if (!useAuthAgent.equals(HostDatabase.AUTHAGENT_NO))
session.requestAuthAgentForwarding(this);
session.requestPTY(getEmulation(), columns, rows, width, height, null);
session.startShell();
stdin = session.getStdin();
stdout = session.getStdout();
stderr = session.getStderr();
sessionOpen = true;
bridge.onConnected();
} catch (IOException e1) {
Log.e(TAG, "Problem while trying to create PTY in finishConnection()", e1);
}
}
@Override
public void connect() {
connection = new Connection(host.getHostname(), host.getPort());
connection.addConnectionMonitor(this);
try {
connection.setCompression(compression);
} catch (IOException e) {
Log.e(TAG, "Could not enable compression!", e);
}
try {
/* Uncomment when debugging SSH protocol:
DebugLogger logger = new DebugLogger() {
public void log(int level, String className, String message) {
Log.d("SSH", message);
}
};
Logger.enabled = true;
Logger.logger = logger;
*/
connectionInfo = connection.connect(new HostKeyVerifier());
connected = true;
if (connectionInfo.clientToServerCryptoAlgorithm
.equals(connectionInfo.serverToClientCryptoAlgorithm)
&& connectionInfo.clientToServerMACAlgorithm
.equals(connectionInfo.serverToClientMACAlgorithm)) {
bridge.outputLine(manager.res.getString(R.string.terminal_using_algorithm,
connectionInfo.clientToServerCryptoAlgorithm,
connectionInfo.clientToServerMACAlgorithm));
} else {
bridge.outputLine(manager.res.getString(
R.string.terminal_using_c2s_algorithm,
connectionInfo.clientToServerCryptoAlgorithm,
connectionInfo.clientToServerMACAlgorithm));
bridge.outputLine(manager.res.getString(
R.string.terminal_using_s2c_algorithm,
connectionInfo.serverToClientCryptoAlgorithm,
connectionInfo.serverToClientMACAlgorithm));
}
} catch (IOException e) {
Log.e(TAG, "Problem in SSH connection thread during authentication", e);
// Display the reason in the text.
bridge.outputLine(e.getCause().getMessage());
onDisconnect();
return;
}
try {
// enter a loop to keep trying until authentication
int tries = 0;
while (connected && !connection.isAuthenticationComplete() && tries++ < AUTH_TRIES) {
authenticate();
// sleep to make sure we dont kill system
Thread.sleep(1000);
}
} catch(Exception e) {
Log.e(TAG, "Problem in SSH connection thread during authentication", e);
}
}
@Override
public void close() {
connected = false;
if (session != null) {
session.close();
session = null;
}
if (connection != null) {
connection.close();
connection = null;
}
}
private void onDisconnect() {
close();
bridge.dispatchDisconnect(false);
}
@Override
public void flush() throws IOException {
if (stdin != null)
stdin.flush();
}
@Override
public int read(byte[] buffer, int start, int len) throws IOException {
int bytesRead = 0;
if (session == null)
return 0;
int newConditions = session.waitForCondition(conditions, 0);
if ((newConditions & ChannelCondition.STDOUT_DATA) != 0) {
bytesRead = stdout.read(buffer, start, len);
}
if ((newConditions & ChannelCondition.STDERR_DATA) != 0) {
byte discard[] = new byte[256];
while (stderr.available() > 0) {
stderr.read(discard);
}
}
if ((newConditions & ChannelCondition.EOF) != 0) {
onDisconnect();
throw new IOException("Remote end closed connection");
}
return bytesRead;
}
@Override
public void write(byte[] buffer) throws IOException {
if (stdin != null)
stdin.write(buffer);
}
@Override
public void write(int c) throws IOException {
if (stdin != null)
stdin.write(c);
}
@Override
public Map<String, String> getOptions() {
Map<String, String> options = new HashMap<String, String>();
options.put("compression", Boolean.toString(compression));
return options;
}
@Override
public void setOptions(Map<String, String> options) {
if (options.containsKey("compression"))
compression = Boolean.parseBoolean(options.get("compression"));
}
public static String getProtocolName() {
return PROTOCOL;
}
@Override
public boolean isSessionOpen() {
return sessionOpen;
}
@Override
public boolean isConnected() {
return connected;
}
public void connectionLost(Throwable reason) {
onDisconnect();
}
@Override
public boolean canForwardPorts() {
return true;
}
@Override
public List<PortForwardBean> getPortForwards() {
return portForwards;
}
@Override
public boolean addPortForward(PortForwardBean portForward) {
return portForwards.add(portForward);
}
@Override
public boolean removePortForward(PortForwardBean portForward) {
// Make sure we don't have a phantom forwarder.
disablePortForward(portForward);
return portForwards.remove(portForward);
}
@Override
public boolean enablePortForward(PortForwardBean portForward) {
if (!portForwards.contains(portForward)) {
Log.e(TAG, "Attempt to enable port forward not in list");
return false;
}
if (!authenticated)
return false;
if (HostDatabase.PORTFORWARD_LOCAL.equals(portForward.getType())) {
LocalPortForwarder lpf = null;
try {
lpf = connection.createLocalPortForwarder(
new InetSocketAddress(InetAddress.getLocalHost(), portForward.getSourcePort()),
portForward.getDestAddr(), portForward.getDestPort());
} catch (Exception e) {
Log.e(TAG, "Could not create local port forward", e);
return false;
}
if (lpf == null) {
Log.e(TAG, "returned LocalPortForwarder object is null");
return false;
}
portForward.setIdentifier(lpf);
portForward.setEnabled(true);
return true;
} else if (HostDatabase.PORTFORWARD_REMOTE.equals(portForward.getType())) {
try {
connection.requestRemotePortForwarding("", portForward.getSourcePort(), portForward.getDestAddr(), portForward.getDestPort());
} catch (Exception e) {
Log.e(TAG, "Could not create remote port forward", e);
return false;
}
portForward.setEnabled(true);
return true;
} else if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(portForward.getType())) {
DynamicPortForwarder dpf = null;
try {
dpf = connection.createDynamicPortForwarder(
new InetSocketAddress(InetAddress.getLocalHost(), portForward.getSourcePort()));
} catch (Exception e) {
Log.e(TAG, "Could not create dynamic port forward", e);
return false;
}
portForward.setIdentifier(dpf);
portForward.setEnabled(true);
return true;
} else {
// Unsupported type
Log.e(TAG, String.format("attempt to forward unknown type %s", portForward.getType()));
return false;
}
}
@Override
public boolean disablePortForward(PortForwardBean portForward) {
if (!portForwards.contains(portForward)) {
Log.e(TAG, "Attempt to disable port forward not in list");
return false;
}
if (!authenticated)
return false;
if (HostDatabase.PORTFORWARD_LOCAL.equals(portForward.getType())) {
LocalPortForwarder lpf = null;
lpf = (LocalPortForwarder)portForward.getIdentifier();
if (!portForward.isEnabled() || lpf == null) {
Log.d(TAG, String.format("Could not disable %s; it appears to be not enabled or have no handler", portForward.getNickname()));
return false;
}
portForward.setEnabled(false);
try {
lpf.close();
} catch (IOException e) {
Log.e(TAG, "Could not stop local port forwarder, setting enabled to false", e);
return false;
}
return true;
} else if (HostDatabase.PORTFORWARD_REMOTE.equals(portForward.getType())) {
portForward.setEnabled(false);
try {
connection.cancelRemotePortForwarding(portForward.getSourcePort());
} catch (IOException e) {
Log.e(TAG, "Could not stop remote port forwarding, setting enabled to false", e);
return false;
}
return true;
} else if (HostDatabase.PORTFORWARD_DYNAMIC5.equals(portForward.getType())) {
DynamicPortForwarder dpf = null;
dpf = (DynamicPortForwarder)portForward.getIdentifier();
if (!portForward.isEnabled() || dpf == null) {
Log.d(TAG, String.format("Could not disable %s; it appears to be not enabled or have no handler", portForward.getNickname()));
return false;
}
portForward.setEnabled(false);
try {
dpf.close();
} catch (IOException e) {
Log.e(TAG, "Could not stop dynamic port forwarder, setting enabled to false", e);
return false;
}
return true;
} else {
// Unsupported type
Log.e(TAG, String.format("attempt to forward unknown type %s", portForward.getType()));
return false;
}
}
@Override
public void setDimensions(int columns, int rows, int width, int height) {
this.columns = columns;
this.rows = rows;
if (sessionOpen) {
try {
session.resizePTY(columns, rows, width, height);
} catch (IOException e) {
Log.e(TAG, "Couldn't send resize PTY packet", e);
}
}
}
@Override
public int getDefaultPort() {
return DEFAULT_PORT;
}
@Override
public String getDefaultNickname(String username, String hostname, int port) {
if (port == DEFAULT_PORT) {
return String.format("%s@%s", username, hostname);
} else {
return String.format("%s@%s:%d", username, hostname, port);
}
}
public static Uri getUri(String input) {
Matcher matcher = hostmask.matcher(input);
if (!matcher.matches())
return null;
StringBuilder sb = new StringBuilder();
sb.append(PROTOCOL)
.append("://")
.append(Uri.encode(matcher.group(1)))
.append('@')
.append(matcher.group(2));
String portString = matcher.group(4);
int port = DEFAULT_PORT;
if (portString != null) {
try {
port = Integer.parseInt(portString);
if (port < 1 || port > 65535) {
port = DEFAULT_PORT;
}
} catch (NumberFormatException nfe) {
// Keep the default port
}
}
if (port != DEFAULT_PORT) {
sb.append(':')
.append(port);
}
sb.append("/#")
.append(Uri.encode(input));
Uri uri = Uri.parse(sb.toString());
return uri;
}
/**
* Handle challenges from keyboard-interactive authentication mode.
*/
public String[] replyToChallenge(String name, String instruction, int numPrompts, String[] prompt, boolean[] echo) {
interactiveCanContinue = true;
String[] responses = new String[numPrompts];
for(int i = 0; i < numPrompts; i++) {
// request response from user for each prompt
responses[i] = bridge.promptHelper.requestStringPrompt(instruction, prompt[i]);
}
return responses;
}
@Override
public HostBean createHost(Uri uri) {
HostBean host = new HostBean();
host.setProtocol(PROTOCOL);
host.setHostname(uri.getHost());
int port = uri.getPort();
if (port < 0)
port = DEFAULT_PORT;
host.setPort(port);
host.setUsername(uri.getUserInfo());
String nickname = uri.getFragment();
if (nickname == null || nickname.length() == 0) {
host.setNickname(getDefaultNickname(host.getUsername(),
host.getHostname(), host.getPort()));
} else {
host.setNickname(uri.getFragment());
}
return host;
}
@Override
public void getSelectionArgs(Uri uri, Map<String, String> selection) {
selection.put(HostDatabase.FIELD_HOST_PROTOCOL, PROTOCOL);
selection.put(HostDatabase.FIELD_HOST_NICKNAME, uri.getFragment());
selection.put(HostDatabase.FIELD_HOST_HOSTNAME, uri.getHost());
int port = uri.getPort();
if (port < 0)
port = DEFAULT_PORT;
selection.put(HostDatabase.FIELD_HOST_PORT, Integer.toString(port));
selection.put(HostDatabase.FIELD_HOST_USERNAME, uri.getUserInfo());
}
@Override
public void setCompression(boolean compression) {
this.compression = compression;
}
public static String getFormatHint(Context context) {
return String.format("%s@%s:%s",
context.getString(R.string.format_username),
context.getString(R.string.format_hostname),
context.getString(R.string.format_port));
}
@Override
public void setUseAuthAgent(String useAuthAgent) {
this.useAuthAgent = useAuthAgent;
}
public Map<String,byte[]> retrieveIdentities() {
Map<String,byte[]> pubKeys = new HashMap<String,byte[]>(manager.loadedKeypairs.size());
for (Entry<String,KeyHolder> entry : manager.loadedKeypairs.entrySet()) {
Object trileadKey = entry.getValue().trileadKey;
try {
if (trileadKey instanceof RSAPrivateKey) {
RSAPublicKey pubkey = ((RSAPrivateKey) trileadKey).getPublicKey();
pubKeys.put(entry.getKey(), RSASHA1Verify.encodeSSHRSAPublicKey(pubkey));
} else if (trileadKey instanceof DSAPrivateKey) {
DSAPublicKey pubkey = ((DSAPrivateKey) trileadKey).getPublicKey();
pubKeys.put(entry.getKey(), DSASHA1Verify.encodeSSHDSAPublicKey(pubkey));
} else
continue;
} catch (IOException e) {
continue;
}
}
return pubKeys;
}
public Object getPrivateKey(byte[] publicKey) {
String nickname = manager.getKeyNickname(publicKey);
if (nickname == null)
return null;
if (useAuthAgent.equals(HostDatabase.AUTHAGENT_NO)) {
Log.e(TAG, "");
return null;
} else if (useAuthAgent.equals(HostDatabase.AUTHAGENT_CONFIRM) ||
manager.loadedKeypairs.get(nickname).bean.isConfirmUse()) {
if (!promptForPubkeyUse(nickname))
return null;
}
return manager.getKey(nickname);
}
private boolean promptForPubkeyUse(String nickname) {
Boolean result = bridge.promptHelper.requestBooleanPrompt(null,
manager.res.getString(R.string.prompt_allow_agent_to_use_key,
nickname));
return result;
}
public boolean addIdentity(Object key, String comment, boolean confirmUse, int lifetime) {
PubkeyBean pubkey = new PubkeyBean();
// pubkey.setType(PubkeyDatabase.KEY_TYPE_IMPORTED);
pubkey.setNickname(comment);
pubkey.setConfirmUse(confirmUse);
pubkey.setLifetime(lifetime);
manager.addKey(pubkey, key);
return true;
}
public boolean removeAllIdentities() {
manager.loadedKeypairs.clear();
return true;
}
public boolean removeIdentity(byte[] publicKey) {
return manager.removeKey(publicKey);
}
public boolean isAgentLocked() {
return agentLockPassphrase != null;
}
public boolean requestAgentUnlock(String unlockPassphrase) {
if (agentLockPassphrase == null)
return false;
if (agentLockPassphrase.equals(unlockPassphrase))
agentLockPassphrase = null;
return agentLockPassphrase == null;
}
public boolean setAgentLock(String lockPassphrase) {
if (agentLockPassphrase != null)
return false;
agentLockPassphrase = lockPassphrase;
return true;
}
/* (non-Javadoc)
* @see org.connectbot.transport.AbsTransport#usesNetwork()
*/
@Override
public boolean usesNetwork() {
return true;
}
}
| Java |
/*
* 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.transport;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import org.connectbot.bean.HostBean;
import org.connectbot.bean.PortForwardBean;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import android.content.Context;
import android.net.Uri;
/**
* @author Kenny Root
*
*/
public abstract class AbsTransport {
HostBean host;
TerminalBridge bridge;
TerminalManager manager;
String emulation;
public AbsTransport() {}
public AbsTransport(HostBean host, TerminalBridge bridge, TerminalManager manager) {
this.host = host;
this.bridge = bridge;
this.manager = manager;
}
/**
* @return protocol part of the URI
*/
public static String getProtocolName() {
return "unknown";
}
/**
* Encode the current transport into a URI that can be passed via intent calls.
* @return URI to host
*/
public static Uri getUri(String input) {
return null;
}
/**
* Causes transport to connect to the target host. After connecting but before a
* session is started, must call back to {@link TerminalBridge#onConnected()}.
* After that call a session may be opened.
*/
public abstract void connect();
/**
* Reads from the transport. Transport must support reading into a the byte array
* <code>buffer</code> at the start of <code>offset</code> and a maximum of
* <code>length</code> bytes. If the remote host disconnects, throw an
* {@link IOException}.
* @param buffer byte buffer to store read bytes into
* @param offset where to start writing in the buffer
* @param length maximum number of bytes to read
* @return number of bytes read
* @throws IOException when remote host disconnects
*/
public abstract int read(byte[] buffer, int offset, int length) throws IOException;
/**
* Writes to the transport. If the host is not yet connected, simply return without
* doing anything. An {@link IOException} should be thrown if there is an error after
* connection.
* @param buffer bytes to write to transport
* @throws IOException when there is a problem writing after connection
*/
public abstract void write(byte[] buffer) throws IOException;
/**
* Writes to the transport. See {@link #write(byte[])} for behavior details.
* @param c character to write to the transport
* @throws IOException when there is a problem writing after connection
*/
public abstract void write(int c) throws IOException;
/**
* Flushes the write commands to the transport.
* @throws IOException when there is a problem writing after connection
*/
public abstract void flush() throws IOException;
/**
* Closes the connection to the terminal. Note that the resulting failure to read
* should call {@link TerminalBridge#dispatchDisconnect(boolean)}.
*/
public abstract void close();
/**
* Tells the transport what dimensions the display is currently
* @param columns columns of text
* @param rows rows of text
* @param width width in pixels
* @param height height in pixels
*/
public abstract void setDimensions(int columns, int rows, int width, int height);
public void setOptions(Map<String,String> options) {
// do nothing
}
public Map<String,String> getOptions() {
return null;
}
public void setCompression(boolean compression) {
// do nothing
}
public void setUseAuthAgent(String useAuthAgent) {
// do nothing
}
public void setEmulation(String emulation) {
this.emulation = emulation;
}
public String getEmulation() {
return emulation;
}
public void setHost(HostBean host) {
this.host = host;
}
public void setBridge(TerminalBridge bridge) {
this.bridge = bridge;
}
public void setManager(TerminalManager manager) {
this.manager = manager;
}
/**
* Whether or not this transport type can forward ports.
* @return true on ability to forward ports
*/
public boolean canForwardPorts() {
return false;
}
/**
* Adds the {@link PortForwardBean} to the list.
* @param portForward the port forward bean to add
* @return true on successful addition
*/
public boolean addPortForward(PortForwardBean portForward) {
return false;
}
/**
* Enables a port forward member. After calling this method, the port forward should
* be operational iff it could be enabled by the transport.
* @param portForward member of our current port forwards list to enable
* @return true on successful port forward setup
*/
public boolean enablePortForward(PortForwardBean portForward) {
return false;
}
/**
* Disables a port forward member. After calling this method, the port forward should
* be non-functioning iff it could be disabled by the transport.
* @param portForward member of our current port forwards list to enable
* @return true on successful port forward tear-down
*/
public boolean disablePortForward(PortForwardBean portForward) {
return false;
}
/**
* Removes the {@link PortForwardBean} from the available port forwards.
* @param portForward the port forward bean to remove
* @return true on successful removal
*/
public boolean removePortForward(PortForwardBean portForward) {
return false;
}
/**
* Gets a list of the {@link PortForwardBean} currently used by this transport.
* @return the list of port forwards
*/
public List<PortForwardBean> getPortForwards() {
return null;
}
public abstract boolean isConnected();
public abstract boolean isSessionOpen();
/**
* @return int default port for protocol
*/
public abstract int getDefaultPort();
/**
* @param username
* @param hostname
* @param port
* @return
*/
public abstract String getDefaultNickname(String username, String hostname, int port);
/**
* @param uri
* @param selectionKeys
* @param selectionValues
*/
public abstract void getSelectionArgs(Uri uri, Map<String, String> selection);
/**
* @param uri
* @return
*/
public abstract HostBean createHost(Uri uri);
/**
* @param context context containing the correct resources
* @return string that hints at the format for connection
*/
public static String getFormatHint(Context context) {
return "???";
}
/**
* @return
*/
public abstract boolean usesNetwork();
}
| Java |
/*
* 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.transport;
import java.util.HashMap;
import java.util.Map;
import org.connectbot.bean.HostBean;
import org.connectbot.util.HostDatabase;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
/**
* @author Kenny Root
*
*/
public class TransportFactory {
private static final String TAG = "ConnectBot.TransportFactory";
private static String[] transportNames = {
SSH.getProtocolName(),
Telnet.getProtocolName(),
Local.getProtocolName(),
};
/**
* @param protocol
* @return
*/
public static AbsTransport getTransport(String protocol) {
if (SSH.getProtocolName().equals(protocol)) {
return new SSH();
} else if (Telnet.getProtocolName().equals(protocol)) {
return new Telnet();
} else if (Local.getProtocolName().equals(protocol)) {
return new Local();
} else {
return null;
}
}
public static Uri getUri(String scheme, String input) {
Log.d("TransportFactory", String.format(
"Attempting to discover URI for scheme=%s on input=%s", scheme,
input));
if (SSH.getProtocolName().equals(scheme))
return SSH.getUri(input);
else if (Telnet.getProtocolName().equals(scheme))
return Telnet.getUri(input);
else if (Local.getProtocolName().equals(scheme)) {
Log.d("TransportFactory", "Got to the local parsing area");
return Local.getUri(input);
} else
return null;
}
public static String[] getTransportNames() {
return transportNames;
}
public static boolean isSameTransportType(AbsTransport a, AbsTransport b) {
if (a == null || b == null)
return false;
return a.getClass().equals(b.getClass());
}
public static boolean canForwardPorts(String protocol) {
// TODO uh, make this have less knowledge about its children
if (SSH.getProtocolName().equals(protocol)) {
return true;
} else {
return false;
}
}
/**
* @param protocol text name of protocol
* @param context
* @return expanded format hint
*/
public static String getFormatHint(String protocol, Context context) {
if (SSH.getProtocolName().equals(protocol)) {
return SSH.getFormatHint(context);
} else if (Telnet.getProtocolName().equals(protocol)) {
return Telnet.getFormatHint(context);
} else if (Local.getProtocolName().equals(protocol)) {
return Local.getFormatHint(context);
} else {
return AbsTransport.getFormatHint(context);
}
}
/**
* @param hostdb Handle to HostDatabase
* @param uri URI to target server
* @param host HostBean in which to put the results
* @return true when host was found
*/
public static HostBean findHost(HostDatabase hostdb, Uri uri) {
AbsTransport transport = getTransport(uri.getScheme());
Map<String, String> selection = new HashMap<String, String>();
transport.getSelectionArgs(uri, selection);
if (selection.size() == 0) {
Log.e(TAG, String.format("Transport %s failed to do something useful with URI=%s",
uri.getScheme(), uri.toString()));
throw new IllegalStateException("Failed to get needed selection arguments");
}
return hostdb.findHost(selection);
}
}
| Java |
/*
* 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.transport;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.connectbot.R;
import org.connectbot.bean.HostBean;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import org.connectbot.util.HostDatabase;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import de.mud.telnet.TelnetProtocolHandler;
/**
* Telnet transport implementation.<br/>
* Original idea from the JTA telnet package (de.mud.telnet)
*
* @author Kenny Root
*
*/
public class Telnet extends AbsTransport {
private static final String TAG = "ConnectBot.Telnet";
private static final String PROTOCOL = "telnet";
private static final int DEFAULT_PORT = 23;
private TelnetProtocolHandler handler;
private Socket socket;
private InputStream is;
private OutputStream os;
private int width;
private int height;
private boolean connected = false;
static final Pattern hostmask;
static {
hostmask = Pattern.compile("^([0-9a-z.-]+)(:(\\d+))?$", Pattern.CASE_INSENSITIVE);
}
public Telnet() {
handler = new TelnetProtocolHandler() {
/** get the current terminal type */
@Override
public String getTerminalType() {
return getEmulation();
}
/** get the current window size */
@Override
public int[] getWindowSize() {
return new int[] { width, height };
}
/** notify about local echo */
@Override
public void setLocalEcho(boolean echo) {
/* EMPTY */
}
/** write data to our back end */
@Override
public void write(byte[] b) throws IOException {
if (os != null)
os.write(b);
}
/** sent on IAC EOR (prompt terminator for remote access systems). */
@Override
public void notifyEndOfRecord() {
}
@Override
protected String getCharsetName() {
Charset charset = bridge.getCharset();
if (charset != null)
return charset.name();
else
return "";
}
};
}
/**
* @param host
* @param bridge
* @param manager
*/
public Telnet(HostBean host, TerminalBridge bridge, TerminalManager manager) {
super(host, bridge, manager);
}
public static String getProtocolName() {
return PROTOCOL;
}
@Override
public void connect() {
try {
socket = new Socket(host.getHostname(), host.getPort());
connected = true;
is = socket.getInputStream();
os = socket.getOutputStream();
bridge.onConnected();
} catch (UnknownHostException e) {
Log.d(TAG, "IO Exception connecting to host", e);
} catch (IOException e) {
Log.d(TAG, "IO Exception connecting to host", e);
}
}
@Override
public void close() {
connected = false;
if (socket != null)
try {
socket.close();
socket = null;
} catch (IOException e) {
Log.d(TAG, "Error closing telnet socket.", e);
}
}
@Override
public void flush() throws IOException {
os.flush();
}
@Override
public int getDefaultPort() {
return DEFAULT_PORT;
}
@Override
public boolean isConnected() {
return connected;
}
@Override
public boolean isSessionOpen() {
return connected;
}
@Override
public int read(byte[] buffer, int start, int len) throws IOException {
/* process all already read bytes */
int n = 0;
do {
n = handler.negotiate(buffer, start);
if (n > 0)
return n;
} while (n == 0);
while (n <= 0) {
do {
n = handler.negotiate(buffer, start);
if (n > 0)
return n;
} while (n == 0);
n = is.read(buffer, start, len);
if (n < 0) {
bridge.dispatchDisconnect(false);
throw new IOException("Remote end closed connection.");
}
handler.inputfeed(buffer, start, n);
n = handler.negotiate(buffer, start);
}
return n;
}
@Override
public void write(byte[] buffer) throws IOException {
try {
if (os != null)
os.write(buffer);
} catch (SocketException e) {
bridge.dispatchDisconnect(false);
}
}
@Override
public void write(int c) throws IOException {
try {
if (os != null)
os.write(c);
} catch (SocketException e) {
bridge.dispatchDisconnect(false);
}
}
@Override
public void setDimensions(int columns, int rows, int width, int height) {
try {
handler.setWindowSize(columns, rows);
} catch (IOException e) {
Log.e(TAG, "Couldn't resize remote terminal", e);
}
}
@Override
public String getDefaultNickname(String username, String hostname, int port) {
if (port == DEFAULT_PORT) {
return String.format("%s", hostname);
} else {
return String.format("%s:%d", hostname, port);
}
}
public static Uri getUri(String input) {
Matcher matcher = hostmask.matcher(input);
if (!matcher.matches())
return null;
StringBuilder sb = new StringBuilder();
sb.append(PROTOCOL)
.append("://")
.append(matcher.group(1));
String portString = matcher.group(3);
int port = DEFAULT_PORT;
if (portString != null) {
try {
port = Integer.parseInt(portString);
if (port < 1 || port > 65535) {
port = DEFAULT_PORT;
}
} catch (NumberFormatException nfe) {
// Keep the default port
}
}
if (port != DEFAULT_PORT) {
sb.append(':');
sb.append(port);
}
sb.append("/#")
.append(Uri.encode(input));
Uri uri = Uri.parse(sb.toString());
return uri;
}
@Override
public HostBean createHost(Uri uri) {
HostBean host = new HostBean();
host.setProtocol(PROTOCOL);
host.setHostname(uri.getHost());
int port = uri.getPort();
if (port < 0)
port = DEFAULT_PORT;
host.setPort(port);
String nickname = uri.getFragment();
if (nickname == null || nickname.length() == 0) {
host.setNickname(getDefaultNickname(host.getUsername(),
host.getHostname(), host.getPort()));
} else {
host.setNickname(uri.getFragment());
}
return host;
}
@Override
public void getSelectionArgs(Uri uri, Map<String, String> selection) {
selection.put(HostDatabase.FIELD_HOST_PROTOCOL, PROTOCOL);
selection.put(HostDatabase.FIELD_HOST_NICKNAME, uri.getFragment());
selection.put(HostDatabase.FIELD_HOST_HOSTNAME, uri.getHost());
int port = uri.getPort();
if (port < 0)
port = DEFAULT_PORT;
selection.put(HostDatabase.FIELD_HOST_PORT, Integer.toString(port));
}
public static String getFormatHint(Context context) {
return String.format("%s:%s",
context.getString(R.string.format_hostname),
context.getString(R.string.format_port));
}
/* (non-Javadoc)
* @see org.connectbot.transport.AbsTransport#usesNetwork()
*/
@Override
public boolean usesNetwork() {
return true;
}
}
| Java |
/*
* 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.transport;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import org.connectbot.R;
import org.connectbot.bean.HostBean;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import org.connectbot.util.HostDatabase;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.google.ase.Exec;
/**
* @author Kenny Root
*
*/
public class Local extends AbsTransport {
private static final String TAG = "ConnectBot.Local";
private static final String PROTOCOL = "local";
private static final String DEFAULT_URI = "local:#Local";
private FileDescriptor shellFd;
private FileInputStream is;
private FileOutputStream os;
/**
*
*/
public Local() {
}
/**
* @param host
* @param bridge
* @param manager
*/
public Local(HostBean host, TerminalBridge bridge, TerminalManager manager) {
super(host, bridge, manager);
}
public static String getProtocolName() {
return PROTOCOL;
}
@Override
public void close() {
try {
if (os != null) {
os.close();
os = null;
}
if (is != null) {
is.close();
is = null;
}
} catch (IOException e) {
Log.e(TAG, "Couldn't close shell", e);
}
}
@Override
public void connect() {
int[] pids = new int[1];
try {
shellFd = Exec.createSubprocess("/system/bin/sh", "-", null, pids);
} catch (Exception e) {
bridge.outputLine(manager.res.getString(R.string.local_shell_unavailable));
Log.e(TAG, "Cannot start local shell", e);
return;
}
final int shellPid = pids[0];
Runnable exitWatcher = new Runnable() {
public void run() {
Exec.waitFor(shellPid);
bridge.dispatchDisconnect(false);
}
};
Thread exitWatcherThread = new Thread(exitWatcher);
exitWatcherThread.setName("LocalExitWatcher");
exitWatcherThread.setDaemon(true);
exitWatcherThread.start();
is = new FileInputStream(shellFd);
os = new FileOutputStream(shellFd);
bridge.onConnected();
}
@Override
public void flush() throws IOException {
os.flush();
}
@Override
public String getDefaultNickname(String username, String hostname, int port) {
return DEFAULT_URI;
}
@Override
public int getDefaultPort() {
return 0;
}
@Override
public boolean isConnected() {
return is != null && os != null;
}
@Override
public boolean isSessionOpen() {
return is != null && os != null;
}
@Override
public int read(byte[] buffer, int start, int len) throws IOException {
if (is == null) {
bridge.dispatchDisconnect(false);
throw new IOException("session closed");
}
return is.read(buffer, start, len);
}
@Override
public void setDimensions(int columns, int rows, int width, int height) {
try {
Exec.setPtyWindowSize(shellFd, rows, columns, width, height);
} catch (Exception e) {
Log.e(TAG, "Couldn't resize pty", e);
}
}
@Override
public void write(byte[] buffer) throws IOException {
if (os != null)
os.write(buffer);
}
@Override
public void write(int c) throws IOException {
if (os != null)
os.write(c);
}
public static Uri getUri(String input) {
Uri uri = Uri.parse(DEFAULT_URI);
if (input != null && input.length() > 0) {
uri = uri.buildUpon().fragment(input).build();
}
return uri;
}
@Override
public HostBean createHost(Uri uri) {
HostBean host = new HostBean();
host.setProtocol(PROTOCOL);
String nickname = uri.getFragment();
if (nickname == null || nickname.length() == 0) {
host.setNickname(getDefaultNickname(host.getUsername(),
host.getHostname(), host.getPort()));
} else {
host.setNickname(uri.getFragment());
}
return host;
}
@Override
public void getSelectionArgs(Uri uri, Map<String, String> selection) {
selection.put(HostDatabase.FIELD_HOST_PROTOCOL, PROTOCOL);
selection.put(HostDatabase.FIELD_HOST_NICKNAME, uri.getFragment());
}
public static String getFormatHint(Context context) {
return context.getString(R.string.hostpref_nickname_title);
}
/* (non-Javadoc)
* @see org.connectbot.transport.AbsTransport#usesNetwork()
*/
@Override
public boolean usesNetwork() {
return false;
}
}
| Java |
/*
* 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 android.os.StrictMode;
public class StrictModeSetup {
public static void run() {
StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.LAX);
}
}
| Java |
/*
* 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.util.List;
import org.connectbot.bean.HostBean;
import org.connectbot.service.TerminalBridge;
import org.connectbot.service.TerminalManager;
import org.connectbot.transport.TransportFactory;
import org.connectbot.util.HostDatabase;
import org.connectbot.util.PreferenceConstants;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
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.Intent.ShortcutIconResource;
import android.content.SharedPreferences.Editor;
import android.content.res.ColorStateList;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class HostListActivity extends ListActivity {
public final static int REQUEST_EDIT = 1;
public final static int REQUEST_EULA = 2;
protected TerminalManager bound = null;
protected HostDatabase hostdb;
private List<HostBean> hosts;
protected LayoutInflater inflater = null;
protected boolean sortedByColor = false;
private MenuItem sortcolor;
private MenuItem sortlast;
private Spinner transportSpinner;
private TextView quickconnect;
private SharedPreferences prefs = null;
protected boolean makingShortcut = false;
protected Handler updateHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
HostListActivity.this.updateList();
}
};
private ServiceConnection connection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
bound = ((TerminalManager.TerminalBinder) service).getService();
// update our listview binder to find the service
HostListActivity.this.updateList();
}
public void onServiceDisconnected(ComponentName className) {
bound = null;
HostListActivity.this.updateList();
}
};
@Override
public void onStart() {
super.onStart();
// start the terminal manager service
this.bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
if(this.hostdb == null)
this.hostdb = new HostDatabase(this);
}
@Override
public void onStop() {
super.onStop();
this.unbindService(connection);
if(this.hostdb != null) {
this.hostdb.close();
this.hostdb = null;
}
}
@Override
public void onResume() {
super.onResume();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_EULA) {
if(resultCode == Activity.RESULT_OK) {
// yay they agreed, so store that info
Editor edit = prefs.edit();
edit.putBoolean(PreferenceConstants.EULA, true);
edit.commit();
} else {
// user didnt agree, so close
this.finish();
}
} else if (requestCode == REQUEST_EDIT) {
this.updateList();
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.act_hostlist);
this.setTitle(String.format("%s: %s",
getResources().getText(R.string.app_name),
getResources().getText(R.string.title_hosts_list)));
// check for eula agreement
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean agreed = prefs.getBoolean(PreferenceConstants.EULA, false);
if(!agreed) {
this.startActivityForResult(new Intent(this, WizardActivity.class), REQUEST_EULA);
}
this.makingShortcut = Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction())
|| Intent.ACTION_PICK.equals(getIntent().getAction());
// connect with hosts database and populate list
this.hostdb = new HostDatabase(this);
ListView list = this.getListView();
this.sortedByColor = prefs.getBoolean(PreferenceConstants.SORT_BY_COLOR, false);
//this.list.setSelector(R.drawable.highlight_disabled_pressed);
list.setOnItemClickListener(new OnItemClickListener() {
public synchronized void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// launch off to console details
HostBean host = (HostBean) parent.getAdapter().getItem(position);
Uri uri = host.getUri();
Intent contents = new Intent(Intent.ACTION_VIEW, uri);
contents.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (makingShortcut) {
// create shortcut if requested
ShortcutIconResource icon = Intent.ShortcutIconResource.fromContext(HostListActivity.this, R.drawable.icon);
Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, contents);
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, host.getNickname());
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
setResult(RESULT_OK, intent);
finish();
} else {
// otherwise just launch activity to show this host
HostListActivity.this.startActivity(contents);
}
}
});
this.registerForContextMenu(list);
quickconnect = (TextView) this.findViewById(R.id.front_quickconnect);
quickconnect.setVisibility(makingShortcut ? View.GONE : View.VISIBLE);
quickconnect.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;
return startConsoleActivity();
}
});
transportSpinner = (Spinner)findViewById(R.id.transport_selection);
transportSpinner.setVisibility(makingShortcut ? View.GONE : View.VISIBLE);
ArrayAdapter<String> transportSelection = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, TransportFactory.getTransportNames());
transportSelection.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
transportSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
String formatHint = TransportFactory.getFormatHint(
(String) transportSpinner.getSelectedItem(),
HostListActivity.this);
quickconnect.setHint(formatHint);
quickconnect.setError(null);
quickconnect.requestFocus();
}
public void onNothingSelected(AdapterView<?> arg0) { }
});
transportSpinner.setAdapter(transportSelection);
this.inflater = LayoutInflater.from(this);
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
// don't offer menus when creating shortcut
if (makingShortcut) return true;
sortcolor.setVisible(!sortedByColor);
sortlast.setVisible(sortedByColor);
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// don't offer menus when creating shortcut
if(makingShortcut) return true;
// add host, ssh keys, about
sortcolor = menu.add(R.string.list_menu_sortcolor);
sortcolor.setIcon(android.R.drawable.ic_menu_share);
sortcolor.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
sortedByColor = true;
updateList();
return true;
}
});
sortlast = menu.add(R.string.list_menu_sortname);
sortlast.setIcon(android.R.drawable.ic_menu_share);
sortlast.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
sortedByColor = false;
updateList();
return true;
}
});
MenuItem keys = menu.add(R.string.list_menu_pubkeys);
keys.setIcon(android.R.drawable.ic_lock_lock);
keys.setIntent(new Intent(HostListActivity.this, PubkeyListActivity.class));
MenuItem colors = menu.add("Colors");
colors.setIcon(android.R.drawable.ic_menu_slideshow);
colors.setIntent(new Intent(HostListActivity.this, ColorsActivity.class));
MenuItem settings = menu.add(R.string.list_menu_settings);
settings.setIcon(android.R.drawable.ic_menu_preferences);
settings.setIntent(new Intent(HostListActivity.this, SettingsActivity.class));
MenuItem help = menu.add(R.string.title_help);
help.setIcon(android.R.drawable.ic_menu_help);
help.setIntent(new Intent(HostListActivity.this, HelpActivity.class));
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
// create menu to handle hosts
// create menu to handle deleting and sharing lists
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
final HostBean host = (HostBean) this.getListView().getItemAtPosition(info.position);
menu.setHeaderTitle(host.getNickname());
// edit, disconnect, delete
MenuItem connect = menu.add(R.string.list_host_disconnect);
final TerminalBridge bridge = bound.getConnectedBridge(host);
connect.setEnabled((bridge != null));
connect.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
bridge.dispatchDisconnect(true);
updateHandler.sendEmptyMessage(-1);
return true;
}
});
MenuItem edit = menu.add(R.string.list_host_edit);
edit.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Intent intent = new Intent(HostListActivity.this, HostEditorActivity.class);
intent.putExtra(Intent.EXTRA_TITLE, host.getId());
HostListActivity.this.startActivityForResult(intent, REQUEST_EDIT);
return true;
}
});
MenuItem portForwards = menu.add(R.string.list_host_portforwards);
portForwards.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Intent intent = new Intent(HostListActivity.this, PortForwardListActivity.class);
intent.putExtra(Intent.EXTRA_TITLE, host.getId());
HostListActivity.this.startActivityForResult(intent, REQUEST_EDIT);
return true;
}
});
if (!TransportFactory.canForwardPorts(host.getProtocol()))
portForwards.setEnabled(false);
MenuItem delete = menu.add(R.string.list_host_delete);
delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// prompt user to make sure they really want this
new AlertDialog.Builder(HostListActivity.this)
.setMessage(getString(R.string.delete_message, host.getNickname()))
.setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// make sure we disconnect
if(bridge != null)
bridge.dispatchDisconnect(true);
hostdb.deleteHost(host);
updateHandler.sendEmptyMessage(-1);
}
})
.setNegativeButton(R.string.delete_neg, null).create().show();
return true;
}
});
}
/**
* @param text
* @return
*/
private boolean startConsoleActivity() {
Uri uri = TransportFactory.getUri((String) transportSpinner
.getSelectedItem(), quickconnect.getText().toString());
if (uri == null) {
quickconnect.setError(getString(R.string.list_format_error,
TransportFactory.getFormatHint(
(String) transportSpinner.getSelectedItem(),
HostListActivity.this)));
return false;
}
HostBean host = TransportFactory.findHost(hostdb, uri);
if (host == null) {
host = TransportFactory.getTransport(uri.getScheme()).createHost(uri);
host.setColor(HostDatabase.COLOR_GRAY);
host.setPubkeyId(HostDatabase.PUBKEYID_ANY);
hostdb.saveHost(host);
}
Intent intent = new Intent(HostListActivity.this, ConsoleActivity.class);
intent.setData(uri);
startActivity(intent);
return true;
}
protected void updateList() {
if (prefs.getBoolean(PreferenceConstants.SORT_BY_COLOR, false) != sortedByColor) {
Editor edit = prefs.edit();
edit.putBoolean(PreferenceConstants.SORT_BY_COLOR, sortedByColor);
edit.commit();
}
if (hostdb == null)
hostdb = new HostDatabase(this);
hosts = hostdb.getHosts(sortedByColor);
// Don't lose hosts that are connected via shortcuts but not in the database.
if (bound != null) {
for (TerminalBridge bridge : bound.bridges) {
if (!hosts.contains(bridge.host))
hosts.add(0, bridge.host);
}
}
HostAdapter adapter = new HostAdapter(this, hosts, bound);
this.setListAdapter(adapter);
}
class HostAdapter extends ArrayAdapter<HostBean> {
private List<HostBean> hosts;
private final TerminalManager manager;
private final ColorStateList red, green, blue;
public final static int STATE_UNKNOWN = 1, STATE_CONNECTED = 2, STATE_DISCONNECTED = 3;
class ViewHolder {
public TextView nickname;
public TextView caption;
public ImageView icon;
}
public HostAdapter(Context context, List<HostBean> hosts, TerminalManager manager) {
super(context, R.layout.item_host, hosts);
this.hosts = hosts;
this.manager = manager;
red = context.getResources().getColorStateList(R.color.red);
green = context.getResources().getColorStateList(R.color.green);
blue = context.getResources().getColorStateList(R.color.blue);
}
/**
* Check if we're connected to a terminal with the given host.
*/
private int getConnectedState(HostBean host) {
// always disconnected if we dont have backend service
if (this.manager == null)
return STATE_UNKNOWN;
if (manager.getConnectedBridge(host) != null)
return STATE_CONNECTED;
if (manager.disconnected.contains(host))
return STATE_DISCONNECTED;
return STATE_UNKNOWN;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_host, null, false);
holder = new ViewHolder();
holder.nickname = (TextView)convertView.findViewById(android.R.id.text1);
holder.caption = (TextView)convertView.findViewById(android.R.id.text2);
holder.icon = (ImageView)convertView.findViewById(android.R.id.icon);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
HostBean host = hosts.get(position);
if (host == null) {
// Well, something bad happened. We can't continue.
Log.e("HostAdapter", "Host bean is null!");
holder.nickname.setText("Error during lookup");
holder.caption.setText("see 'adb logcat' for more");
return convertView;
}
holder.nickname.setText(host.getNickname());
switch (this.getConnectedState(host)) {
case STATE_UNKNOWN:
holder.icon.setImageState(new int[] { }, true);
break;
case STATE_CONNECTED:
holder.icon.setImageState(new int[] { android.R.attr.state_checked }, true);
break;
case STATE_DISCONNECTED:
holder.icon.setImageState(new int[] { android.R.attr.state_expanded }, true);
break;
}
ColorStateList chosen = null;
if (HostDatabase.COLOR_RED.equals(host.getColor()))
chosen = this.red;
else if (HostDatabase.COLOR_GREEN.equals(host.getColor()))
chosen = this.green;
else if (HostDatabase.COLOR_BLUE.equals(host.getColor()))
chosen = this.blue;
Context context = convertView.getContext();
if (chosen != null) {
// set color normally if not selected
holder.nickname.setTextColor(chosen);
holder.caption.setTextColor(chosen);
} else {
// selected, so revert back to default black text
holder.nickname.setTextAppearance(context, android.R.attr.textAppearanceLarge);
holder.caption.setTextAppearance(context, android.R.attr.textAppearanceSmall);
}
long now = System.currentTimeMillis() / 1000;
String nice = context.getString(R.string.bind_never);
if (host.getLastConnect() > 0) {
int minutes = (int)((now - host.getLastConnect()) / 60);
if (minutes >= 60) {
int hours = (minutes / 60);
if (hours >= 24) {
int days = (hours / 24);
nice = context.getString(R.string.bind_days, days);
} else
nice = context.getString(R.string.bind_hours, hours);
} else
nice = context.getString(R.string.bind_minutes, minutes);
}
holder.caption.setText(nice);
return convertView;
}
}
}
| Java |
/*
* 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.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Collections;
import java.util.EventListener;
import java.util.LinkedList;
import java.util.List;
import org.connectbot.bean.PubkeyBean;
import org.connectbot.service.TerminalManager;
import org.connectbot.util.PubkeyDatabase;
import org.connectbot.util.PubkeyUtils;
import org.openintents.intents.FileManagerIntents;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.ClipboardManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import com.trilead.ssh2.crypto.Base64;
import com.trilead.ssh2.crypto.PEMDecoder;
import com.trilead.ssh2.crypto.PEMStructure;
/**
* List public keys in database by nickname and describe their properties. Allow users to import,
* generate, rename, and delete key pairs.
*
* @author Kenny Root
*/
public class PubkeyListActivity extends ListActivity implements EventListener {
public final static String TAG = "ConnectBot.PubkeyListActivity";
private static final int MAX_KEYFILE_SIZE = 8192;
private static final int REQUEST_CODE_PICK_FILE = 1;
// Constants for AndExplorer's file picking intent
private static final String ANDEXPLORER_TITLE = "explorer_title";
private static final String MIME_TYPE_ANDEXPLORER_FILE = "vnd.android.cursor.dir/lysesoft.andexplorer.file";
protected PubkeyDatabase pubkeydb;
private List<PubkeyBean> pubkeys;
protected ClipboardManager clipboard;
protected LayoutInflater inflater = null;
protected TerminalManager bound = null;
private MenuItem onstartToggle = null;
private MenuItem confirmUse = null;
private ServiceConnection connection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
bound = ((TerminalManager.TerminalBinder) service).getService();
// update our listview binder to find the service
updateList();
}
public void onServiceDisconnected(ComponentName className) {
bound = null;
updateList();
}
};
@Override
public void onStart() {
super.onStart();
bindService(new Intent(this, TerminalManager.class), connection, Context.BIND_AUTO_CREATE);
if(pubkeydb == null)
pubkeydb = new PubkeyDatabase(this);
}
@Override
public void onStop() {
super.onStop();
unbindService(connection);
if(pubkeydb != null) {
pubkeydb.close();
pubkeydb = null;
}
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.act_pubkeylist);
this.setTitle(String.format("%s: %s",
getResources().getText(R.string.app_name),
getResources().getText(R.string.title_pubkey_list)));
// connect with hosts database and populate list
pubkeydb = new PubkeyDatabase(this);
updateList();
registerForContextMenu(getListView());
getListView().setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
PubkeyBean pubkey = (PubkeyBean) getListView().getItemAtPosition(position);
boolean loaded = bound.isKeyLoaded(pubkey.getNickname());
// handle toggling key in-memory on/off
if(loaded) {
bound.removeKey(pubkey.getNickname());
updateHandler.sendEmptyMessage(-1);
} else {
handleAddKey(pubkey);
}
}
});
clipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
inflater = LayoutInflater.from(this);
}
/**
* Read given file into memory as <code>byte[]</code>.
*/
protected static byte[] readRaw(File file) throws Exception {
InputStream is = new FileInputStream(file);
ByteArrayOutputStream os = new ByteArrayOutputStream();
int bytesRead;
byte[] buffer = new byte[1024];
while ((bytesRead = is.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.flush();
os.close();
is.close();
return os.toByteArray();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem generatekey = menu.add(R.string.pubkey_generate);
generatekey.setIcon(android.R.drawable.ic_menu_manage);
generatekey.setIntent(new Intent(PubkeyListActivity.this, GeneratePubkeyActivity.class));
MenuItem importkey = menu.add(R.string.pubkey_import);
importkey.setIcon(android.R.drawable.ic_menu_upload);
importkey.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Uri sdcard = Uri.fromFile(Environment.getExternalStorageDirectory());
String pickerTitle = getString(R.string.pubkey_list_pick);
// Try to use OpenIntent's file browser to pick a file
Intent intent = new Intent(FileManagerIntents.ACTION_PICK_FILE);
intent.setData(sdcard);
intent.putExtra(FileManagerIntents.EXTRA_TITLE, pickerTitle);
intent.putExtra(FileManagerIntents.EXTRA_BUTTON_TEXT, getString(android.R.string.ok));
try {
startActivityForResult(intent, REQUEST_CODE_PICK_FILE);
} catch (ActivityNotFoundException e) {
// If OI didn't work, try AndExplorer
intent = new Intent(Intent.ACTION_PICK);
intent.setDataAndType(sdcard, MIME_TYPE_ANDEXPLORER_FILE);
intent.putExtra(ANDEXPLORER_TITLE, pickerTitle);
try {
startActivityForResult(intent, REQUEST_CODE_PICK_FILE);
} catch (ActivityNotFoundException e1) {
pickFileSimple();
}
}
return true;
}
});
return true;
}
protected void handleAddKey(final PubkeyBean pubkey) {
if (pubkey.isEncrypted()) {
final View view = inflater.inflate(R.layout.dia_password, null);
final EditText passwordField = (EditText)view.findViewById(android.R.id.text1);
new AlertDialog.Builder(PubkeyListActivity.this)
.setView(view)
.setPositiveButton(R.string.pubkey_unlock, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
handleAddKey(pubkey, passwordField.getText().toString());
}
})
.setNegativeButton(android.R.string.cancel, null).create().show();
} else {
handleAddKey(pubkey, null);
}
}
protected void handleAddKey(PubkeyBean pubkey, String password) {
Object trileadKey = null;
if(PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType())) {
// load specific key using pem format
try {
trileadKey = PEMDecoder.decode(new String(pubkey.getPrivateKey()).toCharArray(), password);
} catch(Exception e) {
String message = getResources().getString(R.string.pubkey_failed_add, pubkey.getNickname());
Log.e(TAG, message, e);
Toast.makeText(PubkeyListActivity.this, message, Toast.LENGTH_LONG);
}
} else {
// load using internal generated format
PrivateKey privKey = null;
PublicKey pubKey = null;
try {
privKey = PubkeyUtils.decodePrivate(pubkey.getPrivateKey(), pubkey.getType(), password);
pubKey = pubkey.getPublicKey();
} catch (Exception e) {
String message = getResources().getString(R.string.pubkey_failed_add, pubkey.getNickname());
Log.e(TAG, message, e);
Toast.makeText(PubkeyListActivity.this, message, Toast.LENGTH_LONG);
return;
}
// convert key to trilead format
trileadKey = PubkeyUtils.convertToTrilead(privKey, pubKey);
Log.d(TAG, "Unlocked key " + PubkeyUtils.formatKey(pubKey));
}
if(trileadKey == null) return;
Log.d(TAG, String.format("Unlocked key '%s'", pubkey.getNickname()));
// save this key in memory
bound.addKey(pubkey, trileadKey, true);
updateHandler.sendEmptyMessage(-1);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
// Create menu to handle deleting and editing pubkey
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
final PubkeyBean pubkey = (PubkeyBean) getListView().getItemAtPosition(info.position);
menu.setHeaderTitle(pubkey.getNickname());
// TODO: option load/unload key from in-memory list
// prompt for password as needed for passworded keys
// cant change password or clipboard imported keys
final boolean imported = PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType());
final boolean loaded = bound.isKeyLoaded(pubkey.getNickname());
MenuItem load = menu.add(loaded ? R.string.pubkey_memory_unload : R.string.pubkey_memory_load);
load.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
if(loaded) {
bound.removeKey(pubkey.getNickname());
updateHandler.sendEmptyMessage(-1);
} else {
handleAddKey(pubkey);
//bound.addKey(nickname, trileadKey);
}
return true;
}
});
onstartToggle = menu.add(R.string.pubkey_load_on_start);
onstartToggle.setEnabled(!pubkey.isEncrypted());
onstartToggle.setCheckable(true);
onstartToggle.setChecked(pubkey.isStartup());
onstartToggle.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// toggle onstart status
pubkey.setStartup(!pubkey.isStartup());
pubkeydb.savePubkey(pubkey);
updateHandler.sendEmptyMessage(-1);
return true;
}
});
MenuItem copyPublicToClipboard = menu.add(R.string.pubkey_copy_public);
copyPublicToClipboard.setEnabled(!imported);
copyPublicToClipboard.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
try {
PublicKey pk = pubkey.getPublicKey();
String openSSHPubkey = PubkeyUtils.convertToOpenSSHFormat(pk, pubkey.getNickname());
clipboard.setText(openSSHPubkey);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
});
MenuItem copyPrivateToClipboard = menu.add(R.string.pubkey_copy_private);
copyPrivateToClipboard.setEnabled(!pubkey.isEncrypted() || imported);
copyPrivateToClipboard.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
try {
String data = null;
if (imported)
data = new String(pubkey.getPrivateKey());
else {
PrivateKey pk = PubkeyUtils.decodePrivate(pubkey.getPrivateKey(), pubkey.getType());
data = PubkeyUtils.exportPEM(pk, null);
}
clipboard.setText(data);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
});
MenuItem changePassword = menu.add(R.string.pubkey_change_password);
changePassword.setEnabled(!imported);
changePassword.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
final View changePasswordView = inflater.inflate(R.layout.dia_changepassword, null, false);
((TableRow)changePasswordView.findViewById(R.id.old_password_prompt))
.setVisibility(pubkey.isEncrypted() ? View.VISIBLE : View.GONE);
new AlertDialog.Builder(PubkeyListActivity.this)
.setView(changePasswordView)
.setPositiveButton(R.string.button_change, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String oldPassword = ((EditText)changePasswordView.findViewById(R.id.old_password)).getText().toString();
String password1 = ((EditText)changePasswordView.findViewById(R.id.password1)).getText().toString();
String password2 = ((EditText)changePasswordView.findViewById(R.id.password2)).getText().toString();
if (!password1.equals(password2)) {
new AlertDialog.Builder(PubkeyListActivity.this)
.setMessage(R.string.alert_passwords_do_not_match_msg)
.setPositiveButton(android.R.string.ok, null)
.create().show();
return;
}
try {
if (!pubkey.changePassword(oldPassword, password1))
new AlertDialog.Builder(PubkeyListActivity.this)
.setMessage(R.string.alert_wrong_password_msg)
.setPositiveButton(android.R.string.ok, null)
.create().show();
else {
pubkeydb.savePubkey(pubkey);
updateHandler.sendEmptyMessage(-1);
}
} catch (Exception e) {
Log.e(TAG, "Could not change private key password", e);
new AlertDialog.Builder(PubkeyListActivity.this)
.setMessage(R.string.alert_key_corrupted_msg)
.setPositiveButton(android.R.string.ok, null)
.create().show();
}
}
})
.setNegativeButton(android.R.string.cancel, null).create().show();
return true;
}
});
confirmUse = menu.add(R.string.pubkey_confirm_use);
confirmUse.setCheckable(true);
confirmUse.setChecked(pubkey.isConfirmUse());
confirmUse.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// toggle confirm use
pubkey.setConfirmUse(!pubkey.isConfirmUse());
pubkeydb.savePubkey(pubkey);
updateHandler.sendEmptyMessage(-1);
return true;
}
});
MenuItem delete = menu.add(R.string.pubkey_delete);
delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
// prompt user to make sure they really want this
new AlertDialog.Builder(PubkeyListActivity.this)
.setMessage(getString(R.string.delete_message, pubkey.getNickname()))
.setPositiveButton(R.string.delete_pos, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// dont forget to remove from in-memory
if(loaded)
bound.removeKey(pubkey.getNickname());
// delete from backend database and update gui
pubkeydb.deletePubkey(pubkey);
updateHandler.sendEmptyMessage(-1);
}
})
.setNegativeButton(R.string.delete_neg, null).create().show();
return true;
}
});
}
protected Handler updateHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
updateList();
}
};
protected void updateList() {
if (pubkeydb == null) return;
pubkeys = pubkeydb.allPubkeys();
PubkeyAdapter adapter = new PubkeyAdapter(this, pubkeys);
this.setListAdapter(adapter);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case REQUEST_CODE_PICK_FILE:
if (resultCode == RESULT_OK && intent != null) {
Uri uri = intent.getData();
try {
if (uri != null) {
readKeyFromFile(new File(URI.create(uri.toString())));
} else {
String filename = intent.getDataString();
if (filename != null)
readKeyFromFile(new File(URI.create(filename)));
}
} catch (IllegalArgumentException e) {
Log.e(TAG, "Couldn't read from picked file", e);
}
}
break;
}
}
/**
* @param name
*/
private void readKeyFromFile(File file) {
PubkeyBean pubkey = new PubkeyBean();
// find the exact file selected
pubkey.setNickname(file.getName());
if (file.length() > MAX_KEYFILE_SIZE) {
Toast.makeText(PubkeyListActivity.this,
R.string.pubkey_import_parse_problem,
Toast.LENGTH_LONG).show();
return;
}
// parse the actual key once to check if its encrypted
// then save original file contents into our database
try {
byte[] raw = readRaw(file);
String data = new String(raw);
if (data.startsWith(PubkeyUtils.PKCS8_START)) {
int start = data.indexOf(PubkeyUtils.PKCS8_START) + PubkeyUtils.PKCS8_START.length();
int end = data.indexOf(PubkeyUtils.PKCS8_END);
if (end > start) {
char[] encoded = data.substring(start, end - 1).toCharArray();
Log.d(TAG, "encoded: " + new String(encoded));
byte[] decoded = Base64.decode(encoded);
KeyPair kp = PubkeyUtils.recoverKeyPair(decoded);
pubkey.setType(kp.getPrivate().getAlgorithm());
pubkey.setPrivateKey(kp.getPrivate().getEncoded());
pubkey.setPublicKey(kp.getPublic().getEncoded());
} else {
Log.e(TAG, "Problem parsing PKCS#8 file; corrupt?");
Toast.makeText(PubkeyListActivity.this,
R.string.pubkey_import_parse_problem,
Toast.LENGTH_LONG).show();
}
} else {
PEMStructure struct = PEMDecoder.parsePEM(new String(raw).toCharArray());
pubkey.setEncrypted(PEMDecoder.isPEMEncrypted(struct));
pubkey.setType(PubkeyDatabase.KEY_TYPE_IMPORTED);
pubkey.setPrivateKey(raw);
}
// write new value into database
if (pubkeydb == null)
pubkeydb = new PubkeyDatabase(this);
pubkeydb.savePubkey(pubkey);
updateHandler.sendEmptyMessage(-1);
} catch(Exception e) {
Log.e(TAG, "Problem parsing imported private key", e);
Toast.makeText(PubkeyListActivity.this, R.string.pubkey_import_parse_problem, Toast.LENGTH_LONG).show();
}
}
/**
*
*/
private void pickFileSimple() {
// build list of all files in sdcard root
final File sdcard = Environment.getExternalStorageDirectory();
Log.d(TAG, sdcard.toString());
// Don't show a dialog if the SD card is completely absent.
final String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)
&& !Environment.MEDIA_MOUNTED.equals(state)) {
new AlertDialog.Builder(PubkeyListActivity.this)
.setMessage(R.string.alert_sdcard_absent)
.setNegativeButton(android.R.string.cancel, null).create().show();
return;
}
List<String> names = new LinkedList<String>();
{
File[] files = sdcard.listFiles();
if (files != null) {
for(File file : sdcard.listFiles()) {
if(file.isDirectory()) continue;
names.add(file.getName());
}
}
}
Collections.sort(names);
final String[] namesList = names.toArray(new String[] {});
Log.d(TAG, names.toString());
// prompt user to select any file from the sdcard root
new AlertDialog.Builder(PubkeyListActivity.this)
.setTitle(R.string.pubkey_list_pick)
.setItems(namesList, new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
String name = namesList[arg1];
readKeyFromFile(new File(sdcard, name));
}
})
.setNegativeButton(android.R.string.cancel, null).create().show();
}
class PubkeyAdapter extends ArrayAdapter<PubkeyBean> {
private List<PubkeyBean> pubkeys;
class ViewHolder {
public TextView nickname;
public TextView caption;
public ImageView icon;
}
public PubkeyAdapter(Context context, List<PubkeyBean> pubkeys) {
super(context, R.layout.item_pubkey, pubkeys);
this.pubkeys = pubkeys;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_pubkey, null, false);
holder = new ViewHolder();
holder.nickname = (TextView) convertView.findViewById(android.R.id.text1);
holder.caption = (TextView) convertView.findViewById(android.R.id.text2);
holder.icon = (ImageView) convertView.findViewById(android.R.id.icon1);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
PubkeyBean pubkey = pubkeys.get(position);
holder.nickname.setText(pubkey.getNickname());
boolean imported = PubkeyDatabase.KEY_TYPE_IMPORTED.equals(pubkey.getType());
if (imported) {
try {
PEMStructure struct = PEMDecoder.parsePEM(new String(pubkey.getPrivateKey()).toCharArray());
String type = (struct.pemType == PEMDecoder.PEM_RSA_PRIVATE_KEY) ? "RSA" : "DSA";
holder.caption.setText(String.format("%s unknown-bit", type));
} catch (IOException e) {
Log.e(TAG, "Error decoding IMPORTED public key at " + pubkey.getId(), e);
}
} else {
try {
holder.caption.setText(pubkey.getDescription());
} catch (Exception e) {
Log.e(TAG, "Error decoding public key at " + pubkey.getId(), e);
holder.caption.setText(R.string.pubkey_unknown_format);
}
}
if (bound == null) {
holder.icon.setVisibility(View.GONE);
} else {
holder.icon.setVisibility(View.VISIBLE);
if (bound.isKeyLoaded(pubkey.getNickname()))
holder.icon.setImageState(new int[] { android.R.attr.state_checked }, true);
else
holder.icon.setImageState(new int[] { }, true);
}
return convertView;
}
}
}
| Java |
/*
* 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.util;
/**
* @author Kenny Root
*
*/
public class Colors {
public final static Integer[] defaults = new Integer[] {
0xff000000, // black
0xffcc0000, // red
0xff00cc00, // green
0xffcccc00, // brown
0xff0000cc, // blue
0xffcc00cc, // purple
0xff00cccc, // cyan
0xffcccccc, // light grey
0xff444444, // dark grey
0xffff4444, // light red
0xff44ff44, // light green
0xffffff44, // yellow
0xff4444ff, // light blue
0xffff44ff, // light purple
0xff44ffff, // light cyan
0xffffffff, // white
0xff000000, 0xff00005f, 0xff000087, 0xff0000af, 0xff0000d7,
0xff0000ff, 0xff005f00, 0xff005f5f, 0xff005f87, 0xff005faf,
0xff005fd7, 0xff005fff, 0xff008700, 0xff00875f, 0xff008787,
0xff0087af, 0xff0087d7, 0xff0087ff, 0xff00af00, 0xff00af5f,
0xff00af87, 0xff00afaf, 0xff00afd7, 0xff00afff, 0xff00d700,
0xff00d75f, 0xff00d787, 0xff00d7af, 0xff00d7d7, 0xff00d7ff,
0xff00ff00, 0xff00ff5f, 0xff00ff87, 0xff00ffaf, 0xff00ffd7,
0xff00ffff, 0xff5f0000, 0xff5f005f, 0xff5f0087, 0xff5f00af,
0xff5f00d7, 0xff5f00ff, 0xff5f5f00, 0xff5f5f5f, 0xff5f5f87,
0xff5f5faf, 0xff5f5fd7, 0xff5f5fff, 0xff5f8700, 0xff5f875f,
0xff5f8787, 0xff5f87af, 0xff5f87d7, 0xff5f87ff, 0xff5faf00,
0xff5faf5f, 0xff5faf87, 0xff5fafaf, 0xff5fafd7, 0xff5fafff,
0xff5fd700, 0xff5fd75f, 0xff5fd787, 0xff5fd7af, 0xff5fd7d7,
0xff5fd7ff, 0xff5fff00, 0xff5fff5f, 0xff5fff87, 0xff5fffaf,
0xff5fffd7, 0xff5fffff, 0xff870000, 0xff87005f, 0xff870087,
0xff8700af, 0xff8700d7, 0xff8700ff, 0xff875f00, 0xff875f5f,
0xff875f87, 0xff875faf, 0xff875fd7, 0xff875fff, 0xff878700,
0xff87875f, 0xff878787, 0xff8787af, 0xff8787d7, 0xff8787ff,
0xff87af00, 0xff87af5f, 0xff87af87, 0xff87afaf, 0xff87afd7,
0xff87afff, 0xff87d700, 0xff87d75f, 0xff87d787, 0xff87d7af,
0xff87d7d7, 0xff87d7ff, 0xff87ff00, 0xff87ff5f, 0xff87ff87,
0xff87ffaf, 0xff87ffd7, 0xff87ffff, 0xffaf0000, 0xffaf005f,
0xffaf0087, 0xffaf00af, 0xffaf00d7, 0xffaf00ff, 0xffaf5f00,
0xffaf5f5f, 0xffaf5f87, 0xffaf5faf, 0xffaf5fd7, 0xffaf5fff,
0xffaf8700, 0xffaf875f, 0xffaf8787, 0xffaf87af, 0xffaf87d7,
0xffaf87ff, 0xffafaf00, 0xffafaf5f, 0xffafaf87, 0xffafafaf,
0xffafafd7, 0xffafafff, 0xffafd700, 0xffafd75f, 0xffafd787,
0xffafd7af, 0xffafd7d7, 0xffafd7ff, 0xffafff00, 0xffafff5f,
0xffafff87, 0xffafffaf, 0xffafffd7, 0xffafffff, 0xffd70000,
0xffd7005f, 0xffd70087, 0xffd700af, 0xffd700d7, 0xffd700ff,
0xffd75f00, 0xffd75f5f, 0xffd75f87, 0xffd75faf, 0xffd75fd7,
0xffd75fff, 0xffd78700, 0xffd7875f, 0xffd78787, 0xffd787af,
0xffd787d7, 0xffd787ff, 0xffd7af00, 0xffd7af5f, 0xffd7af87,
0xffd7afaf, 0xffd7afd7, 0xffd7afff, 0xffd7d700, 0xffd7d75f,
0xffd7d787, 0xffd7d7af, 0xffd7d7d7, 0xffd7d7ff, 0xffd7ff00,
0xffd7ff5f, 0xffd7ff87, 0xffd7ffaf, 0xffd7ffd7, 0xffd7ffff,
0xffff0000, 0xffff005f, 0xffff0087, 0xffff00af, 0xffff00d7,
0xffff00ff, 0xffff5f00, 0xffff5f5f, 0xffff5f87, 0xffff5faf,
0xffff5fd7, 0xffff5fff, 0xffff8700, 0xffff875f, 0xffff8787,
0xffff87af, 0xffff87d7, 0xffff87ff, 0xffffaf00, 0xffffaf5f,
0xffffaf87, 0xffffafaf, 0xffffafd7, 0xffffafff, 0xffffd700,
0xffffd75f, 0xffffd787, 0xffffd7af, 0xffffd7d7, 0xffffd7ff,
0xffffff00, 0xffffff5f, 0xffffff87, 0xffffffaf, 0xffffffd7,
0xffffffff, 0xff080808, 0xff121212, 0xff1c1c1c, 0xff262626,
0xff303030, 0xff3a3a3a, 0xff444444, 0xff4e4e4e, 0xff585858,
0xff626262, 0xff6c6c6c, 0xff767676, 0xff808080, 0xff8a8a8a,
0xff949494, 0xff9e9e9e, 0xffa8a8a8, 0xffb2b2b2, 0xffbcbcbc,
0xffc6c6c6, 0xffd0d0d0, 0xffdadada, 0xffe4e4e4, 0xffeeeeee,
};
}
| Java |
/*
* 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.util;
import java.io.IOException;
import java.math.BigInteger;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.interfaces.DSAParams;
import java.security.interfaces.DSAPrivateKey;
import java.security.interfaces.DSAPublicKey;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.DSAPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.EncryptedPrivateKeyInfo;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import android.util.Log;
import com.trilead.ssh2.crypto.Base64;
import com.trilead.ssh2.signature.DSASHA1Verify;
import com.trilead.ssh2.signature.RSASHA1Verify;
public class PubkeyUtils {
public static final String PKCS8_START = "-----BEGIN PRIVATE KEY-----";
public static final String PKCS8_END = "-----END PRIVATE KEY-----";
// Size in bytes of salt to use.
private static final int SALT_SIZE = 8;
// Number of iterations for password hashing. PKCS#5 recommends 1000
private static final int ITERATIONS = 1000;
public static String formatKey(Key key){
String algo = key.getAlgorithm();
String fmt = key.getFormat();
byte[] encoded = key.getEncoded();
return "Key[algorithm=" + algo + ", format=" + fmt +
", bytes=" + encoded.length + "]";
}
public static byte[] sha256(byte[] data) throws NoSuchAlgorithmException {
return MessageDigest.getInstance("SHA-256").digest(data);
}
public static byte[] cipher(int mode, byte[] data, byte[] secret) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
SecretKeySpec secretKeySpec = new SecretKeySpec(sha256(secret), "AES");
Cipher c = Cipher.getInstance("AES");
c.init(mode, secretKeySpec);
return c.doFinal(data);
}
public static byte[] encrypt(byte[] cleartext, String secret) throws Exception {
byte[] salt = new byte[SALT_SIZE];
byte[] ciphertext = Encryptor.encrypt(salt, ITERATIONS, secret, cleartext);
byte[] complete = new byte[salt.length + ciphertext.length];
System.arraycopy(salt, 0, complete, 0, salt.length);
System.arraycopy(ciphertext, 0, complete, salt.length, ciphertext.length);
Arrays.fill(salt, (byte) 0x00);
Arrays.fill(ciphertext, (byte) 0x00);
return complete;
}
public static byte[] decrypt(byte[] complete, String secret) throws Exception {
try {
byte[] salt = new byte[SALT_SIZE];
byte[] ciphertext = new byte[complete.length - salt.length];
System.arraycopy(complete, 0, salt, 0, salt.length);
System.arraycopy(complete, salt.length, ciphertext, 0, ciphertext.length);
return Encryptor.decrypt(salt, ITERATIONS, secret, ciphertext);
} catch (Exception e) {
Log.d("decrypt", "Could not decrypt with new method", e);
// We might be using the old encryption method.
return cipher(Cipher.DECRYPT_MODE, complete, secret.getBytes());
}
}
public static byte[] getEncodedPublic(PublicKey pk) {
return new X509EncodedKeySpec(pk.getEncoded()).getEncoded();
}
public static byte[] getEncodedPrivate(PrivateKey pk) {
return new PKCS8EncodedKeySpec(pk.getEncoded()).getEncoded();
}
public static byte[] getEncodedPrivate(PrivateKey pk, String secret) throws Exception {
if (secret.length() > 0)
return encrypt(getEncodedPrivate(pk), secret);
else
return getEncodedPrivate(pk);
}
public static PrivateKey decodePrivate(byte[] encoded, String keyType) throws NoSuchAlgorithmException, InvalidKeySpecException {
PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(encoded);
KeyFactory kf = KeyFactory.getInstance(keyType);
return kf.generatePrivate(privKeySpec);
}
public static PrivateKey decodePrivate(byte[] encoded, String keyType, String secret) throws Exception {
if (secret != null && secret.length() > 0)
return decodePrivate(decrypt(encoded, secret), keyType);
else
return decodePrivate(encoded, keyType);
}
public static PublicKey decodePublic(byte[] encoded, String keyType) throws NoSuchAlgorithmException, InvalidKeySpecException {
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encoded);
KeyFactory kf = KeyFactory.getInstance(keyType);
return kf.generatePublic(pubKeySpec);
}
public static KeyPair recoverKeyPair(byte[] encoded) throws NoSuchAlgorithmException, InvalidKeySpecException {
KeySpec privKeySpec = new PKCS8EncodedKeySpec(encoded);
KeySpec pubKeySpec;
PrivateKey priv;
PublicKey pub;
KeyFactory kf;
try {
kf = KeyFactory.getInstance(PubkeyDatabase.KEY_TYPE_RSA);
priv = kf.generatePrivate(privKeySpec);
pubKeySpec = new RSAPublicKeySpec(((RSAPrivateCrtKey) priv)
.getModulus(), ((RSAPrivateCrtKey) priv)
.getPublicExponent());
pub = kf.generatePublic(pubKeySpec);
} catch (ClassCastException e) {
kf = KeyFactory.getInstance(PubkeyDatabase.KEY_TYPE_DSA);
priv = kf.generatePrivate(privKeySpec);
DSAParams params = ((DSAPrivateKey) priv).getParams();
// Calculate public key Y
BigInteger y = params.getG().modPow(((DSAPrivateKey) priv).getX(),
params.getP());
pubKeySpec = new DSAPublicKeySpec(y, params.getP(), params.getQ(),
params.getG());
pub = kf.generatePublic(pubKeySpec);
}
return new KeyPair(pub, priv);
}
/*
* Trilead compatibility methods
*/
public static Object convertToTrilead(PublicKey pk) {
if (pk instanceof RSAPublicKey) {
return new com.trilead.ssh2.signature.RSAPublicKey(
((RSAPublicKey) pk).getPublicExponent(),
((RSAPublicKey) pk).getModulus());
} else if (pk instanceof DSAPublicKey) {
DSAParams dp = ((DSAPublicKey) pk).getParams();
return new com.trilead.ssh2.signature.DSAPublicKey(
dp.getP(), dp.getQ(), dp.getG(), ((DSAPublicKey) pk).getY());
}
throw new IllegalArgumentException("PublicKey is not RSA or DSA format");
}
public static Object convertToTrilead(PrivateKey priv, PublicKey pub) {
if (priv instanceof RSAPrivateKey) {
return new com.trilead.ssh2.signature.RSAPrivateKey(
((RSAPrivateKey) priv).getPrivateExponent(),
((RSAPublicKey) pub).getPublicExponent(),
((RSAPrivateKey) priv).getModulus());
} else if (priv instanceof DSAPrivateKey) {
DSAParams dp = ((DSAPrivateKey) priv).getParams();
return new com.trilead.ssh2.signature.DSAPrivateKey(
dp.getP(), dp.getQ(), dp.getG(), ((DSAPublicKey) pub).getY(),
((DSAPrivateKey) priv).getX());
}
throw new IllegalArgumentException("Key is not RSA or DSA format");
}
/*
* OpenSSH compatibility methods
*/
public static String convertToOpenSSHFormat(PublicKey pk, String origNickname) throws IOException, InvalidKeyException {
String nickname = origNickname;
if (nickname == null)
nickname = "connectbot@android";
if (pk instanceof RSAPublicKey) {
String data = "ssh-rsa ";
data += String.valueOf(Base64.encode(RSASHA1Verify.encodeSSHRSAPublicKey(
(com.trilead.ssh2.signature.RSAPublicKey)convertToTrilead(pk))));
return data + " " + nickname;
} else if (pk instanceof DSAPublicKey) {
String data = "ssh-dss ";
data += String.valueOf(Base64.encode(DSASHA1Verify.encodeSSHDSAPublicKey(
(com.trilead.ssh2.signature.DSAPublicKey)convertToTrilead(pk))));
return data + " " + nickname;
}
throw new InvalidKeyException("Unknown key type");
}
/*
* OpenSSH compatibility methods
*/
/**
* @param trileadKey
* @return OpenSSH-encoded pubkey
*/
public static byte[] extractOpenSSHPublic(Object trileadKey) {
try {
if (trileadKey instanceof com.trilead.ssh2.signature.RSAPrivateKey)
return RSASHA1Verify.encodeSSHRSAPublicKey(
((com.trilead.ssh2.signature.RSAPrivateKey) trileadKey).getPublicKey());
else if (trileadKey instanceof com.trilead.ssh2.signature.DSAPrivateKey)
return DSASHA1Verify.encodeSSHDSAPublicKey(
((com.trilead.ssh2.signature.DSAPrivateKey) trileadKey).getPublicKey());
else
return null;
} catch (IOException e) {
return null;
}
}
public static String exportPEM(PrivateKey key, String secret) throws NoSuchAlgorithmException, InvalidParameterSpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, InvalidKeySpecException, IllegalBlockSizeException, IOException {
StringBuilder sb = new StringBuilder();
byte[] data = key.getEncoded();
sb.append(PKCS8_START);
sb.append('\n');
if (secret != null) {
byte[] salt = new byte[8];
SecureRandom random = new SecureRandom();
random.nextBytes(salt);
PBEParameterSpec defParams = new PBEParameterSpec(salt, 1);
AlgorithmParameters params = AlgorithmParameters.getInstance(key.getAlgorithm());
params.init(defParams);
PBEKeySpec pbeSpec = new PBEKeySpec(secret.toCharArray());
SecretKeyFactory keyFact = SecretKeyFactory.getInstance(key.getAlgorithm());
Cipher cipher = Cipher.getInstance(key.getAlgorithm());
cipher.init(Cipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), params);
byte[] wrappedKey = cipher.wrap(key);
EncryptedPrivateKeyInfo pinfo = new EncryptedPrivateKeyInfo(params, wrappedKey);
data = pinfo.getEncoded();
sb.append("Proc-Type: 4,ENCRYPTED\n");
sb.append("DEK-Info: DES-EDE3-CBC,");
sb.append(encodeHex(salt));
sb.append("\n\n");
}
int i = sb.length();
sb.append(Base64.encode(data));
for (i += 63; i < sb.length(); i += 64) {
sb.insert(i, "\n");
}
sb.append('\n');
sb.append(PKCS8_END);
sb.append('\n');
return sb.toString();
}
private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
protected static String encodeHex(byte[] bytes) {
final char[] hex = new char[bytes.length * 2];
int i = 0;
for (byte b : bytes) {
hex[i++] = HEX_DIGITS[(b >> 4) & 0x0f];
hex[i++] = HEX_DIGITS[b & 0x0f];
}
return String.valueOf(hex);
}
}
| Java |
/*
* 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.util;
import org.connectbot.R;
import android.app.Dialog;
import android.content.Context;
import android.view.View;
public class EntropyDialog extends Dialog implements OnEntropyGatheredListener {
public EntropyDialog(Context context) {
super(context);
this.setContentView(R.layout.dia_gatherentropy);
this.setTitle(R.string.pubkey_gather_entropy);
((EntropyView) findViewById(R.id.entropy)).addOnEntropyGatheredListener(this);
}
public EntropyDialog(Context context, View view) {
super(context);
this.setContentView(view);
this.setTitle(R.string.pubkey_gather_entropy);
((EntropyView) findViewById(R.id.entropy)).addOnEntropyGatheredListener(this);
}
public void onEntropyGathered(byte[] entropy) {
this.dismiss();
}
}
| Java |
/*
* 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.util;
import java.util.LinkedList;
import java.util.List;
import org.connectbot.bean.PubkeyBean;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
/**
* Public Key Encryption database. Contains private and public key pairs
* for public key authentication.
*
* @author Kenny Root
*/
public class PubkeyDatabase extends RobustSQLiteOpenHelper {
public final static String TAG = "ConnectBot.PubkeyDatabase";
public final static String DB_NAME = "pubkeys";
public final static int DB_VERSION = 2;
public final static String TABLE_PUBKEYS = "pubkeys";
public final static String FIELD_PUBKEY_NICKNAME = "nickname";
public final static String FIELD_PUBKEY_TYPE = "type";
public final static String FIELD_PUBKEY_PRIVATE = "private";
public final static String FIELD_PUBKEY_PUBLIC = "public";
public final static String FIELD_PUBKEY_ENCRYPTED = "encrypted";
public final static String FIELD_PUBKEY_STARTUP = "startup";
public final static String FIELD_PUBKEY_CONFIRMUSE = "confirmuse";
public final static String FIELD_PUBKEY_LIFETIME = "lifetime";
public final static String KEY_TYPE_RSA = "RSA",
KEY_TYPE_DSA = "DSA",
KEY_TYPE_IMPORTED = "IMPORTED";
private Context context;
static {
addTableName(TABLE_PUBKEYS);
}
public PubkeyDatabase(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
super.onCreate(db);
db.execSQL("CREATE TABLE " + TABLE_PUBKEYS
+ " (_id INTEGER PRIMARY KEY, "
+ FIELD_PUBKEY_NICKNAME + " TEXT, "
+ FIELD_PUBKEY_TYPE + " TEXT, "
+ FIELD_PUBKEY_PRIVATE + " BLOB, "
+ FIELD_PUBKEY_PUBLIC + " BLOB, "
+ FIELD_PUBKEY_ENCRYPTED + " INTEGER, "
+ FIELD_PUBKEY_STARTUP + " INTEGER, "
+ FIELD_PUBKEY_CONFIRMUSE + " INTEGER DEFAULT 0, "
+ FIELD_PUBKEY_LIFETIME + " INTEGER DEFAULT 0)");
}
@Override
public void onRobustUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) throws SQLiteException {
switch (oldVersion) {
case 1:
db.execSQL("ALTER TABLE " + TABLE_PUBKEYS
+ " ADD COLUMN " + FIELD_PUBKEY_CONFIRMUSE + " INTEGER DEFAULT 0");
db.execSQL("ALTER TABLE " + TABLE_PUBKEYS
+ " ADD COLUMN " + FIELD_PUBKEY_LIFETIME + " INTEGER DEFAULT 0");
}
}
/**
* Delete a specific host by its <code>_id</code> value.
*/
public void deletePubkey(PubkeyBean pubkey) {
HostDatabase hostdb = new HostDatabase(context);
hostdb.stopUsingPubkey(pubkey.getId());
hostdb.close();
SQLiteDatabase db = getWritableDatabase();
db.delete(TABLE_PUBKEYS, "_id = ?", new String[] { Long.toString(pubkey.getId()) });
db.close();
}
/**
* Return a cursor that contains information about all known hosts.
*/
/*
public Cursor allPubkeys() {
SQLiteDatabase db = this.getReadableDatabase();
return db.query(TABLE_PUBKEYS, new String[] { "_id",
FIELD_PUBKEY_NICKNAME, FIELD_PUBKEY_TYPE, FIELD_PUBKEY_PRIVATE,
FIELD_PUBKEY_PUBLIC, FIELD_PUBKEY_ENCRYPTED, FIELD_PUBKEY_STARTUP },
null, null, null, null, null);
}*/
public List<PubkeyBean> allPubkeys() {
return getPubkeys(null, null);
}
public List<PubkeyBean> getAllStartPubkeys() {
return getPubkeys(FIELD_PUBKEY_STARTUP + " = 1 AND " + FIELD_PUBKEY_ENCRYPTED + " = 0", null);
}
private List<PubkeyBean> getPubkeys(String selection, String[] selectionArgs) {
SQLiteDatabase db = getReadableDatabase();
List<PubkeyBean> pubkeys = new LinkedList<PubkeyBean>();
Cursor c = db.query(TABLE_PUBKEYS, null, selection, selectionArgs, null, null, null);
if (c != null) {
final int COL_ID = c.getColumnIndexOrThrow("_id"),
COL_NICKNAME = c.getColumnIndexOrThrow(FIELD_PUBKEY_NICKNAME),
COL_TYPE = c.getColumnIndexOrThrow(FIELD_PUBKEY_TYPE),
COL_PRIVATE = c.getColumnIndexOrThrow(FIELD_PUBKEY_PRIVATE),
COL_PUBLIC = c.getColumnIndexOrThrow(FIELD_PUBKEY_PUBLIC),
COL_ENCRYPTED = c.getColumnIndexOrThrow(FIELD_PUBKEY_ENCRYPTED),
COL_STARTUP = c.getColumnIndexOrThrow(FIELD_PUBKEY_STARTUP),
COL_CONFIRMUSE = c.getColumnIndexOrThrow(FIELD_PUBKEY_CONFIRMUSE),
COL_LIFETIME = c.getColumnIndexOrThrow(FIELD_PUBKEY_LIFETIME);
while (c.moveToNext()) {
PubkeyBean pubkey = new PubkeyBean();
pubkey.setId(c.getLong(COL_ID));
pubkey.setNickname(c.getString(COL_NICKNAME));
pubkey.setType(c.getString(COL_TYPE));
pubkey.setPrivateKey(c.getBlob(COL_PRIVATE));
pubkey.setPublicKey(c.getBlob(COL_PUBLIC));
pubkey.setEncrypted(c.getInt(COL_ENCRYPTED) > 0);
pubkey.setStartup(c.getInt(COL_STARTUP) > 0);
pubkey.setConfirmUse(c.getInt(COL_CONFIRMUSE) > 0);
pubkey.setLifetime(c.getInt(COL_LIFETIME));
pubkeys.add(pubkey);
}
c.close();
}
db.close();
return pubkeys;
}
/**
* @param hostId
* @return
*/
public PubkeyBean findPubkeyById(long pubkeyId) {
SQLiteDatabase db = getReadableDatabase();
Cursor c = db.query(TABLE_PUBKEYS, null,
"_id = ?", new String[] { String.valueOf(pubkeyId) },
null, null, null);
PubkeyBean pubkey = null;
if (c != null) {
if (c.moveToFirst())
pubkey = createPubkeyBean(c);
c.close();
}
db.close();
return pubkey;
}
private PubkeyBean createPubkeyBean(Cursor c) {
PubkeyBean pubkey = new PubkeyBean();
pubkey.setId(c.getLong(c.getColumnIndexOrThrow("_id")));
pubkey.setNickname(c.getString(c.getColumnIndexOrThrow(FIELD_PUBKEY_NICKNAME)));
pubkey.setType(c.getString(c.getColumnIndexOrThrow(FIELD_PUBKEY_TYPE)));
pubkey.setPrivateKey(c.getBlob(c.getColumnIndexOrThrow(FIELD_PUBKEY_PRIVATE)));
pubkey.setPublicKey(c.getBlob(c.getColumnIndexOrThrow(FIELD_PUBKEY_PUBLIC)));
pubkey.setEncrypted(c.getInt(c.getColumnIndexOrThrow(FIELD_PUBKEY_ENCRYPTED)) > 0);
pubkey.setStartup(c.getInt(c.getColumnIndexOrThrow(FIELD_PUBKEY_STARTUP)) > 0);
pubkey.setConfirmUse(c.getInt(c.getColumnIndexOrThrow(FIELD_PUBKEY_CONFIRMUSE)) > 0);
pubkey.setLifetime(c.getInt(c.getColumnIndexOrThrow(FIELD_PUBKEY_LIFETIME)));
return pubkey;
}
/**
* Pull all values for a given column as a list of Strings, probably for use
* in a ListPreference. Sorted by <code>_id</code> ascending.
*/
public List<CharSequence> allValues(String column) {
List<CharSequence> list = new LinkedList<CharSequence>();
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.query(TABLE_PUBKEYS, new String[] { "_id", column },
null, null, null, null, "_id ASC");
if (c != null) {
int COL = c.getColumnIndexOrThrow(column);
while (c.moveToNext())
list.add(c.getString(COL));
c.close();
}
db.close();
return list;
}
public String getNickname(long id) {
String nickname = null;
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.query(TABLE_PUBKEYS, new String[] { "_id",
FIELD_PUBKEY_NICKNAME }, "_id = ?",
new String[] { Long.toString(id) }, null, null, null);
if (c != null) {
if (c.moveToFirst())
nickname = c.getString(c.getColumnIndexOrThrow(FIELD_PUBKEY_NICKNAME));
c.close();
}
db.close();
return nickname;
}
/*
public void setOnStart(long id, boolean onStart) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(FIELD_PUBKEY_STARTUP, onStart ? 1 : 0);
db.update(TABLE_PUBKEYS, values, "_id = ?", new String[] { Long.toString(id) });
}
public boolean changePassword(long id, String oldPassword, String newPassword) throws NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, InvalidKeyException, BadPaddingException {
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.query(TABLE_PUBKEYS, new String[] { FIELD_PUBKEY_TYPE,
FIELD_PUBKEY_PRIVATE, FIELD_PUBKEY_ENCRYPTED },
"_id = ?", new String[] { String.valueOf(id) },
null, null, null);
if (!c.moveToFirst())
return false;
String keyType = c.getString(0);
byte[] encPriv = c.getBlob(1);
c.close();
PrivateKey priv;
try {
priv = PubkeyUtils.decodePrivate(encPriv, keyType, oldPassword);
} catch (InvalidKeyException e) {
return false;
} catch (BadPaddingException e) {
return false;
} catch (InvalidKeySpecException e) {
return false;
}
ContentValues values = new ContentValues();
values.put(FIELD_PUBKEY_PRIVATE, PubkeyUtils.getEncodedPrivate(priv, newPassword));
values.put(FIELD_PUBKEY_ENCRYPTED, newPassword.length() > 0 ? 1 : 0);
db.update(TABLE_PUBKEYS, values, "_id = ?", new String[] { String.valueOf(id) });
return true;
}
*/
/**
* @param pubkey
*/
public PubkeyBean savePubkey(PubkeyBean pubkey) {
SQLiteDatabase db = this.getWritableDatabase();
boolean success = false;
ContentValues values = pubkey.getValues();
if (pubkey.getId() > 0) {
values.remove("_id");
if (db.update(TABLE_PUBKEYS, values, "_id = ?", new String[] { String.valueOf(pubkey.getId()) }) > 0)
success = true;
}
if (!success) {
long id = db.insert(TABLE_PUBKEYS, null, pubkey.getValues());
pubkey.setId(id);
}
db.close();
return pubkey;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.