code
stringlengths
3
1.18M
language
stringclasses
1 value
package com.ch_linghu.fanfoudroid.app; import android.app.Activity; import android.content.Intent; import android.widget.Toast; import com.ch_linghu.fanfoudroid.LoginActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.fanfou.RefuseError; import com.ch_linghu.fanfoudroid.http.HttpAuthException; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.HttpRefusedException; import com.ch_linghu.fanfoudroid.http.HttpServerException; public class ExceptionHandler { private Activity mActivity; public ExceptionHandler(Activity activity) { mActivity = activity; } public void handle(HttpException e) { Throwable cause = e.getCause(); if (null == cause) return; // Handle Different Exception if (cause instanceof HttpAuthException) { // 用户名/密码错误 Toast.makeText(mActivity, R.string.error_not_authorized, Toast.LENGTH_LONG).show(); Intent intent = new Intent(mActivity, LoginActivity.class); mActivity.startActivity(intent); // redirect to the login activity } else if (cause instanceof HttpServerException) { // 服务器暂时无法响应 Toast.makeText(mActivity, R.string.error_not_authorized, Toast.LENGTH_LONG).show(); } else if (cause instanceof HttpAuthException) { //FIXME: 集中处理用户名/密码验证错误,返回到登录界面 } else if (cause instanceof HttpRefusedException) { // 服务器拒绝请求,如没有权限查看某用户信息 RefuseError error = ((HttpRefusedException) cause).getError(); switch (error.getErrorCode()) { // TODO: finish it case -1: default: Toast.makeText(mActivity, error.getMessage(), Toast.LENGTH_LONG).show(); break; } } } private void handleCause() { } }
Java
package com.ch_linghu.fanfoudroid; import java.util.ArrayList; import java.util.List; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.hardware.SensorManager; import android.util.Log; import android.widget.RemoteViews; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; 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.service.TwitterService; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.util.TextHelper; public class FanfouWidget extends AppWidgetProvider { public final String TAG = "FanfouWidget"; public final String NEXTACTION = "com.ch_linghu.fanfoudroid.FanfouWidget.NEXT"; public final String PREACTION = "com.ch_linghu.fanfoudroid.FanfouWidget.PREV"; private static List<Tweet> tweets; private SensorManager sensorManager; private static int position = 0; class CacheCallback implements ImageLoaderCallback { private RemoteViews updateViews; CacheCallback(RemoteViews updateViews) { this.updateViews = updateViews; } @Override public void refresh(String url, Bitmap bitmap) { updateViews.setImageViewBitmap(R.id.status_image, bitmap); } } @Override public void onUpdate(Context context, AppWidgetManager appwidgetmanager, int[] appWidgetIds) { Log.d(TAG, "onUpdate"); TwitterService.setWidgetStatus(true); // if (!isRunning(context, WidgetService.class.getName())) { // Intent i = new Intent(context, WidgetService.class); // context.startService(i); // } update(context); } private void update(Context context) { fetchMessages(); position = 0; refreshView(context, NEXTACTION); } private TwitterDatabase getDb() { return TwitterApplication.mDb; } public String getUserId() { return TwitterApplication.getMyselfId(); } private void fetchMessages() { if (tweets == null) { tweets = new ArrayList<Tweet>(); } else { tweets.clear(); } Cursor cursor = getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_HOME); if (cursor != null) { if (cursor.moveToFirst()) { do { Tweet tweet = StatusTable.parseCursor(cursor); tweets.add(tweet); } while (cursor.moveToNext()); } } Log.d(TAG, "Tweets size " + tweets.size()); } private void refreshView(Context context) { ComponentName fanfouWidget = new ComponentName(context, FanfouWidget.class); AppWidgetManager manager = AppWidgetManager.getInstance(context); manager.updateAppWidget(fanfouWidget, buildLogin(context)); } private RemoteViews buildLogin(Context context) { RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_initial_layout); updateViews.setTextViewText(R.id.status_text, TextHelper.getSimpleTweetText("请登录")); updateViews.setTextViewText(R.id.status_screen_name,""); updateViews.setTextViewText(R.id.tweet_source,""); updateViews.setTextViewText(R.id.tweet_created_at, ""); return updateViews; } private void refreshView(Context context, String action) { // 某些情况下,tweets会为null if (tweets == null) { fetchMessages(); } // 防止引发IndexOutOfBoundsException if (tweets.size() != 0) { if (action.equals(NEXTACTION)) { --position; } else if (action.equals(PREACTION)) { ++position; } // Log.d(TAG, "Tweets size =" + tweets.size()); if (position >= tweets.size() || position < 0) { position = 0; } // Log.d(TAG, "position=" + position); ComponentName fanfouWidget = new ComponentName(context, FanfouWidget.class); AppWidgetManager manager = AppWidgetManager.getInstance(context); manager.updateAppWidget(fanfouWidget, buildUpdate(context)); } } public RemoteViews buildUpdate(Context context) { RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_initial_layout); Tweet t = tweets.get(position); Log.d(TAG, "tweet=" + t); updateViews.setTextViewText(R.id.status_screen_name, t.screenName); updateViews.setTextViewText(R.id.status_text, TextHelper.getSimpleTweetText(t.text)); updateViews.setTextViewText(R.id.tweet_source, context.getString(R.string.tweet_source_prefix) + t.source); updateViews.setTextViewText(R.id.tweet_created_at, DateTimeHelper.getRelativeDate(t.createdAt)); updateViews.setImageViewBitmap(R.id.status_image, TwitterApplication.mImageLoader.get( t.profileImageUrl, new CacheCallback(updateViews))); Intent inext = new Intent(context, FanfouWidget.class); inext.setAction(NEXTACTION); PendingIntent pinext = PendingIntent.getBroadcast(context, 0, inext, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.btn_next, pinext); Intent ipre = new Intent(context, FanfouWidget.class); ipre.setAction(PREACTION); PendingIntent pipre = PendingIntent.getBroadcast(context, 0, ipre, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.btn_pre, pipre); Intent write = WriteActivity.createNewTweetIntent(""); PendingIntent piwrite = PendingIntent.getActivity(context, 0, write, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.write_message, piwrite); Intent home = TwitterActivity.createIntent(context); PendingIntent pihome = PendingIntent.getActivity(context, 0, home, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.logo_image, pihome); Intent status = StatusActivity.createIntent(t); PendingIntent pistatus = PendingIntent.getActivity(context, 0, status, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.main_body, pistatus); return updateViews; } @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "OnReceive"); // FIXME: NullPointerException Log.i(TAG, context.getApplicationContext().toString()); if (!TwitterApplication.mApi.isLoggedIn()) { refreshView(context); } else { super.onReceive(context, intent); String action = intent.getAction(); if (NEXTACTION.equals(action) || PREACTION.equals(action)) { refreshView(context, intent.getAction()); } else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { update(context); } } } /** * * @param c * @param serviceName * @return */ @Deprecated public boolean isRunning(Context c, String serviceName) { ActivityManager myAM = (ActivityManager) c .getSystemService(Context.ACTIVITY_SERVICE); ArrayList<RunningServiceInfo> runningServices = (ArrayList<RunningServiceInfo>) myAM .getRunningServices(40); // 获取最多40个当前正在运行的服务,放进ArrList里,以现在手机的处理能力,要是超过40个服务,估计已经卡死,所以不用考虑超过40个该怎么办 int servicesSize = runningServices.size(); for (int i = 0; i < servicesSize; i++)// 循环枚举对比 { if (runningServices.get(i).service.getClassName().toString() .equals(serviceName)) { return true; } } return false; } @Override public void onDeleted(Context context, int[] appWidgetIds) { Log.d(TAG, "onDeleted"); } @Override public void onEnabled(Context context) { Log.d(TAG, "onEnabled"); TwitterService.setWidgetStatus(true); } @Override public void onDisabled(Context context) { Log.d(TAG, "onDisabled"); TwitterService.setWidgetStatus(false); } }
Java
package com.ch_linghu.fanfoudroid; import java.text.MessageFormat; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.provider.BaseColumns; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.db.UserInfoTable; import com.ch_linghu.fanfoudroid.fanfou.User; 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; /** * * @author Dino 2011-02-26 */ // public class ProfileActivity extends WithHeaderActivity { public class ProfileActivity extends BaseActivity { private static final String TAG = "ProfileActivity"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.PROFILE"; private static final String STATUS_COUNT = "status_count"; private static final String EXTRA_USER = "user"; private static final String FANFOUROOT = "http://fanfou.com/"; private static final String USER_ID = "userid"; private static final String USER_NAME = "userName"; private GenericTask profileInfoTask;// 获取用户信息 private GenericTask setFollowingTask; private GenericTask cancelFollowingTask; private String userId; private String userName; private String myself; private User profileInfo;// 用户信息 private ImageView profileImageView;// 头像 private TextView profileName;// 名称 private TextView profileScreenName;// 昵称 private TextView userLocation;// 地址 private TextView userUrl;// url private TextView userInfo;// 自述 private TextView friendsCount;// 好友 private TextView followersCount;// 收听 private TextView statusCount;// 消息 private TextView favouritesCount;// 收藏 private TextView isFollowingText;// 是否关注 private Button followingBtn;// 收听/取消关注按钮 private Button sendMentionBtn;// 发送留言按钮 private Button sendDmBtn;// 发送私信按钮 private ProgressDialog dialog; // 请稍候 private RelativeLayout friendsLayout; private LinearLayout followersLayout; private LinearLayout statusesLayout; private LinearLayout favouritesLayout; private NavBar mNavBar; private Feedback mFeedback; private TwitterDatabase db; public static Intent createIntent(String userId) { Intent intent = new Intent(LAUNCH_ACTION); intent.putExtra(USER_ID, userId); return intent; } private ImageLoaderCallback callback = new ImageLoaderCallback() { @Override public void refresh(String url, Bitmap bitmap) { profileImageView.setImageBitmap(bitmap); } }; @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "OnCreate start"); if (super._onCreate(savedInstanceState)) { setContentView(R.layout.profile); Intent intent = getIntent(); Bundle extras = intent.getExtras(); myself = TwitterApplication.getMyselfId(); if (extras != null) { this.userId = extras.getString(USER_ID); this.userName = extras.getString(USER_NAME); } else { this.userId = myself; this.userName = TwitterApplication.getMyselfName(); } Uri data = intent.getData(); if (data != null) { userId = data.getLastPathSegment(); } // 初始化控件 initControls(); Log.d(TAG, "the userid is " + userId); db = this.getDb(); draw(); return true; } else { return false; } } private void initControls() { mNavBar = new NavBar(NavBar.HEADER_STYLE_HOME, this); mNavBar.setHeaderTitle(""); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); sendMentionBtn = (Button) findViewById(R.id.sendmetion_btn); sendDmBtn = (Button) findViewById(R.id.senddm_btn); profileImageView = (ImageView) findViewById(R.id.profileimage); profileName = (TextView) findViewById(R.id.profilename); profileScreenName = (TextView) findViewById(R.id.profilescreenname); userLocation = (TextView) findViewById(R.id.user_location); userUrl = (TextView) findViewById(R.id.user_url); userInfo = (TextView) findViewById(R.id.tweet_user_info); friendsCount = (TextView) findViewById(R.id.friends_count); followersCount = (TextView) findViewById(R.id.followers_count); TextView friendsCountTitle = (TextView) findViewById(R.id.friends_count_title); TextView followersCountTitle = (TextView) findViewById(R.id.followers_count_title); String who; if (userId.equals(myself)) { who = "我"; } else { who = "ta"; } friendsCountTitle.setText(MessageFormat.format( getString(R.string.profile_friends_count_title), who)); followersCountTitle.setText(MessageFormat.format( getString(R.string.profile_followers_count_title), who)); statusCount = (TextView) findViewById(R.id.statuses_count); favouritesCount = (TextView) findViewById(R.id.favourites_count); friendsLayout = (RelativeLayout) findViewById(R.id.friendsLayout); followersLayout = (LinearLayout) findViewById(R.id.followersLayout); statusesLayout = (LinearLayout) findViewById(R.id.statusesLayout); favouritesLayout = (LinearLayout) findViewById(R.id.favouritesLayout); isFollowingText = (TextView) findViewById(R.id.isfollowing_text); followingBtn = (Button) findViewById(R.id.following_btn); // 为按钮面板添加事件 friendsLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 在没有得到profileInfo时,不允许点击事件生效 if (profileInfo == null) { return; } String showName; if (!TextUtils.isEmpty(profileInfo.getScreenName())) { showName = profileInfo.getScreenName(); } else { showName = profileInfo.getName(); } Intent intent = FollowingActivity .createIntent(userId, showName); intent.setClass(ProfileActivity.this, FollowingActivity.class); startActivity(intent); } }); followersLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 在没有得到profileInfo时,不允许点击事件生效 if (profileInfo == null) { return; } String showName; if (!TextUtils.isEmpty(profileInfo.getScreenName())) { showName = profileInfo.getScreenName(); } else { showName = profileInfo.getName(); } Intent intent = FollowersActivity .createIntent(userId, showName); intent.setClass(ProfileActivity.this, FollowersActivity.class); startActivity(intent); } }); statusesLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 在没有得到profileInfo时,不允许点击事件生效 if (profileInfo == null) { return; } String showName; if (!TextUtils.isEmpty(profileInfo.getScreenName())) { showName = profileInfo.getScreenName(); } else { showName = profileInfo.getName(); } Intent intent = UserTimelineActivity.createIntent( profileInfo.getId(), showName); launchActivity(intent); } }); favouritesLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 在没有得到profileInfo时,不允许点击事件生效 if (profileInfo == null) { return; } Intent intent = FavoritesActivity.createIntent(userId, profileInfo.getName()); intent.setClass(ProfileActivity.this, FavoritesActivity.class); startActivity(intent); } }); // 刷新 View.OnClickListener refreshListener = new View.OnClickListener() { @Override public void onClick(View v) { doGetProfileInfo(); } }; mNavBar.getRefreshButton().setOnClickListener(refreshListener); } private void draw() { Log.d(TAG, "draw"); bindProfileInfo(); // doGetProfileInfo(); } @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."); } /** * 从数据库获取,如果数据库不存在则创建 */ private void bindProfileInfo() { dialog = ProgressDialog.show(ProfileActivity.this, "请稍候", "正在加载信息..."); if (null != db && db.existsUser(userId)) { Cursor cursor = db.getUserInfoById(userId); profileInfo = User.parseUser(cursor); cursor.close(); if (profileInfo == null) { Log.w(TAG, "cannot get userinfo from userinfotable the id is" + userId); } bindControl(); if (dialog != null) { dialog.dismiss(); } } else { doGetProfileInfo(); } } private void doGetProfileInfo() { mFeedback.start(""); if (profileInfoTask != null && profileInfoTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { profileInfoTask = new GetProfileTask(); profileInfoTask.setListener(profileInfoTaskListener); TaskParams params = new TaskParams(); profileInfoTask.execute(params); } } private void bindControl() { if (profileInfo.getId().equals(myself)) { sendMentionBtn.setVisibility(View.GONE); sendDmBtn.setVisibility(View.GONE); } else { // 发送留言 sendMentionBtn.setVisibility(View.VISIBLE); sendMentionBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = WriteActivity.createNewTweetIntent(String .format("@%s ", profileInfo.getScreenName())); startActivity(intent); } }); // 发送私信 sendDmBtn.setVisibility(View.VISIBLE); sendDmBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = WriteDmActivity.createIntent(profileInfo .getId()); startActivity(intent); } }); } if (userId.equals(myself)) { mNavBar.setHeaderTitle("我" + getString(R.string.cmenu_user_profile_prefix)); } else { mNavBar.setHeaderTitle(profileInfo.getScreenName() + getString(R.string.cmenu_user_profile_prefix)); } profileImageView .setImageBitmap(TwitterApplication.mImageLoader .get(profileInfo.getProfileImageURL().toString(), callback)); profileName.setText(profileInfo.getId()); profileScreenName.setText(profileInfo.getScreenName()); if (profileInfo.getId().equals(myself)) { isFollowingText.setText(R.string.profile_isyou); followingBtn.setVisibility(View.GONE); } else if (profileInfo.isFollowing()) { isFollowingText.setText(R.string.profile_isfollowing); followingBtn.setVisibility(View.VISIBLE); followingBtn.setText(R.string.user_label_unfollow); followingBtn.setOnClickListener(cancelFollowingListener); followingBtn.setCompoundDrawablesWithIntrinsicBounds(getResources() .getDrawable(R.drawable.ic_unfollow), null, null, null); } else { isFollowingText.setText(R.string.profile_notfollowing); followingBtn.setVisibility(View.VISIBLE); followingBtn.setText(R.string.user_label_follow); followingBtn.setOnClickListener(setfollowingListener); followingBtn.setCompoundDrawablesWithIntrinsicBounds(getResources() .getDrawable(R.drawable.ic_follow), null, null, null); } String location = profileInfo.getLocation(); if (location == null || location.length() == 0) { location = getResources().getString(R.string.profile_location_null); } userLocation.setText(location); if (profileInfo.getURL() != null) { userUrl.setText(profileInfo.getURL().toString()); } else { userUrl.setText(FANFOUROOT + profileInfo.getId()); } String description = profileInfo.getDescription(); if (description == null || description.length() == 0) { description = getResources().getString( R.string.profile_description_null); } userInfo.setText(description); friendsCount.setText(String.valueOf(profileInfo.getFriendsCount())); followersCount.setText(String.valueOf(profileInfo.getFollowersCount())); statusCount.setText(String.valueOf(profileInfo.getStatusesCount())); favouritesCount .setText(String.valueOf(profileInfo.getFavouritesCount())); } private TaskListener profileInfoTaskListener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { // 加载成功 if (result == TaskResult.OK) { mFeedback.success(""); // 绑定控件 bindControl(); if (dialog != null) { dialog.dismiss(); } } } @Override public String getName() { return "GetProfileInfo"; } }; /** * 更新数据库中的用户 * * @return */ private boolean updateUser() { ContentValues v = new ContentValues(); v.put(BaseColumns._ID, profileInfo.getName()); v.put(UserInfoTable.FIELD_USER_NAME, profileInfo.getName()); v.put(UserInfoTable.FIELD_USER_SCREEN_NAME, profileInfo.getScreenName()); v.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, profileInfo .getProfileImageURL().toString()); v.put(UserInfoTable.FIELD_LOCALTION, profileInfo.getLocation()); v.put(UserInfoTable.FIELD_DESCRIPTION, profileInfo.getDescription()); v.put(UserInfoTable.FIELD_PROTECTED, profileInfo.isProtected()); v.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, profileInfo.getFollowersCount()); v.put(UserInfoTable.FIELD_LAST_STATUS, profileInfo.getStatusSource()); v.put(UserInfoTable.FIELD_FRIENDS_COUNT, profileInfo.getFriendsCount()); v.put(UserInfoTable.FIELD_FAVORITES_COUNT, profileInfo.getFavouritesCount()); v.put(UserInfoTable.FIELD_STATUSES_COUNT, profileInfo.getStatusesCount()); v.put(UserInfoTable.FIELD_FOLLOWING, profileInfo.isFollowing()); if (profileInfo.getURL() != null) { v.put(UserInfoTable.FIELD_URL, profileInfo.getURL().toString()); } return db.updateUser(profileInfo.getId(), v); } /** * 获取用户信息task * * @author Dino * */ private class GetProfileTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.v(TAG, "get profile task"); try { profileInfo = getApi().showUser(userId); mFeedback.update(80); if (profileInfo != null) { if (null != db && !db.existsUser(userId)) { com.ch_linghu.fanfoudroid.data.User userinfodb = profileInfo .parseUser(); db.createUserInfo(userinfodb); } else { // 更新用户 updateUser(); } } } catch (HttpException e) { Log.e(TAG, e.getMessage()); return TaskResult.FAILED; } mFeedback.update(99); return TaskResult.OK; } } /** * 设置关注监听 */ private OnClickListener setfollowingListener = new OnClickListener() { @Override public void onClick(View v) { Builder diaBuilder = new AlertDialog.Builder(ProfileActivity.this) .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(); } }; /* * 取消关注监听 */ private OnClickListener cancelFollowingListener = new OnClickListener() { @Override public void onClick(View v) { Builder diaBuilder = new AlertDialog.Builder(ProfileActivity.this) .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(); cancelFollowingTask.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 { 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(getBaseContext(), "关注成功", Toast.LENGTH_SHORT) .show(); } else if (result == TaskResult.FAILED) { Toast.makeText(getBaseContext(), "关注失败", Toast.LENGTH_SHORT) .show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; /** * 取消关注 * * @author Dino * */ private class CancelFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { 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(getBaseContext(), "取消关注成功", Toast.LENGTH_SHORT) .show(); } else if (result == TaskResult.FAILED) { Toast.makeText(getBaseContext(), "取消关注失败", Toast.LENGTH_SHORT) .show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; }
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.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.MediaStore; import android.provider.MediaStore.MediaColumns; import android.text.Editable; import android.text.Selection; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.app.ImageManager; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.http.HttpClient; 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; import com.ch_linghu.fanfoudroid.util.FileHelper; import com.ch_linghu.fanfoudroid.util.TextHelper; public class WriteActivity extends BaseActivity { // FIXME: for debug, delete me private long startTime = -1; private long endTime = -1; public static final String NEW_TWEET_ACTION = "com.ch_linghu.fanfoudroid.NEW"; public static final String REPLY_TWEET_ACTION = "com.ch_linghu.fanfoudroid.REPLY"; public static final String REPOST_TWEET_ACTION = "com.ch_linghu.fanfoudroid.REPOST"; public static final String EXTRA_REPLY_TO_NAME = "reply_to_name"; public static final String EXTRA_REPLY_ID = "reply_id"; public static final String EXTRA_REPOST_ID = "repost_status_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"; private static final int REQUEST_IMAGE_CAPTURE = 2; private static final int REQUEST_PHOTO_LIBRARY = 3; // View private TweetEdit mTweetEdit; private EditText mTweetEditText; private TextView mProgressText; private ImageButton mLocationButton; private ImageButton chooseImagesButton; private ImageButton mCameraButton; private ProgressDialog dialog; private NavBar mNavbar; // Picture private boolean withPic=false ; private File mFile; private ImageView mPreview; private ImageView imageDelete; private static final int MAX_BITMAP_SIZE = 400; private File mImageFile; private Uri mImageUri; // Task private GenericTask mSendTask; private TaskListener mSendTaskListener = new TaskAdapter() { @Override public void onPreExecute(GenericTask task) { onSendBegin(); } @Override public void onPostExecute(GenericTask task, TaskResult result) { endTime = System.currentTimeMillis(); Log.d("LDS", "Sended a status in " + (endTime - startTime)); if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { onSendSuccess(); } else if (result == TaskResult.IO_ERROR) { onSendFailure(); } } @Override public String getName() { // TODO Auto-generated method stub return "SendTask"; } }; private String _reply_id; private String _repost_id; private String _reply_to_name; // sub menu protected void openImageCaptureMenu() { try { // TODO: API < 1.6, images size too small mImageFile = new File(FileHelper.getBasePath(), "upload.jpg"); mImageUri = Uri.fromFile(mImageFile); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri); startActivityForResult(intent, REQUEST_IMAGE_CAPTURE); } catch (Exception e) { Log.e(TAG, e.getMessage()); } } protected void openPhotoLibraryMenu() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); startActivityForResult(intent, REQUEST_PHOTO_LIBRARY); } /** * @deprecated 已废弃, 分解成两个按钮 */ 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) { switch (item) { case 0: openImageCaptureMenu(); break; case 1: openPhotoLibraryMenu(); } } }); AlertDialog alert = builder.create(); alert.show(); } private String getRealPathFromURI(Uri contentUri) { String[] proj = { MediaColumns.DATA }; Cursor cursor = managedQuery(contentUri, proj, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } private void getPic(Intent intent, Uri uri) { // layout for picture mode changeStyleWithPic(); withPic = true; mFile = null; mImageUri = uri; if (uri.getScheme().equals("content")) { mFile = new File(getRealPathFromURI(mImageUri)); } else { mFile = new File(mImageUri.getPath()); } // TODO:想将图片放在EditText左边 mPreview.setImageBitmap(createThumbnailBitmap(mImageUri, MAX_BITMAP_SIZE)); if (mFile == null) { updateProgress("Could not locate picture file. Sorry!"); disableEntry(); } } private File bitmapToFile(Bitmap bitmap) { try { File file = new File(FileHelper.getBasePath(), "upload.jpg"); FileOutputStream out = new FileOutputStream(file); if (bitmap.compress(Bitmap.CompressFormat.JPEG, ImageManager.DEFAULT_COMPRESS_QUALITY, out)) { out.flush(); out.close(); } return file; } catch (FileNotFoundException e) { Log.e(TAG, "Sorry, the file can not be created. " + e.getMessage()); return null; } catch (IOException e) { Log.e(TAG, "IOException occurred when save upload file. " + e.getMessage()); return null; } } private void changeStyleWithPic() { // 修改布局 ,以前 图片居中,现在在左边 // mPreview.setLayoutParams( // new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, // LayoutParams.FILL_PARENT) // ); mPreview.setVisibility(View.VISIBLE); imageDelete.setVisibility(View.VISIBLE); mTweetEditText.setLayoutParams(new LinearLayout.LayoutParams( LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 2f)); } /** * 制作微缩图 * * @param uri * @param size * @return */ private Bitmap createThumbnailBitmap(Uri uri, int size) { InputStream input = null; try { input = getContentResolver().openInputStream(uri); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(input, null, options); input.close(); // Compute the scale. int scale = 1; while ((options.outWidth / scale > size) || (options.outHeight / scale > size)) { scale *= 2; } options.inJustDecodeBounds = false; options.inSampleSize = scale; input = getContentResolver().openInputStream(uri); return BitmapFactory.decodeStream(input, null, options); } catch (IOException e) { Log.w(TAG, e); return null; } finally { if (input != null) { try { input.close(); } catch (IOException e) { Log.w(TAG, e); } } } } @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { // init View setContentView(R.layout.write); mNavbar = new NavBar(NavBar.HEADER_STYLE_WRITE, this); // Intent & Action & Extras Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType(); Bundle extras = intent.getExtras(); String text = null; Uri uri = null; if (extras != null) { String subject = extras.getString(Intent.EXTRA_SUBJECT); text = extras.getString(Intent.EXTRA_TEXT); uri = (Uri) (extras.get(Intent.EXTRA_STREAM)); if (!TextUtils.isEmpty(subject)) { text = subject + " " + text; } if ((type != null && type.startsWith("text")) && uri != null) { text = text + " " + uri.toString(); uri = null; } } _reply_id = null; _repost_id = null; _reply_to_name = null; // View mProgressText = (TextView) findViewById(R.id.progress_text); mTweetEditText = (EditText) findViewById(R.id.tweet_edit); // TODO: @某人-- 类似饭否自动补全 ImageButton mAddUserButton = (ImageButton) findViewById(R.id.add_user); mAddUserButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int start = mTweetEditText.getSelectionStart(); int end = mTweetEditText.getSelectionEnd(); mTweetEditText.getText().replace(Math.min(start, end), Math.max(start, end), "@"); } }); // 插入图片 chooseImagesButton = (ImageButton) findViewById(R.id.choose_images_button); chooseImagesButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.d(TAG, "chooseImagesButton onClick"); openPhotoLibraryMenu(); } }); // 打开相机 mCameraButton = (ImageButton) findViewById(R.id.camera_button); mCameraButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Log.d(TAG, "mCameraButton onClick"); openImageCaptureMenu(); } }); // With picture imageDelete = (ImageView) findViewById(R.id.image_delete); imageDelete.setOnClickListener(deleteListener); mPreview = (ImageView) findViewById(R.id.preview); if (Intent.ACTION_SEND.equals(intent.getAction()) && uri != null) { getPic(intent, uri); } // Update status mTweetEdit = new TweetEdit(mTweetEditText, (TextView) findViewById(R.id.chars_text)); if (TwitterApplication.mPref.getBoolean(Preferences.USE_ENTER_SEND, false)){ mTweetEdit.setOnKeyListener(tweetEnterHandler); } mTweetEdit.addTextChangedListener(new MyTextWatcher( WriteActivity.this)); if (NEW_TWEET_ACTION.equals(action) || Intent.ACTION_SEND.equals(action)){ if (!TextUtils.isEmpty(text)){ //始终将光标置于最末尾,以方便回复消息时保持@用户在最前面 EditText inputField = mTweetEdit.getEditText(); inputField.setTextKeepState(text); Editable etext = inputField.getText(); int position = etext.length(); Selection.setSelection(etext, position); } }else if (REPLY_TWEET_ACTION.equals(action)) { _reply_id = intent.getStringExtra(EXTRA_REPLY_ID); _reply_to_name = intent.getStringExtra(EXTRA_REPLY_TO_NAME); if (!TextUtils.isEmpty(text)){ String reply_to_name = "@"+_reply_to_name + " "; String other_replies = ""; for (String mention : TextHelper.getMentions(text)){ //获取名字时不包括自己和回复对象 if (!mention.equals(TwitterApplication.getMyselfName()) && !mention.equals(_reply_to_name)){ other_replies += "@"+mention+" "; } } EditText inputField = mTweetEdit.getEditText(); inputField.setTextKeepState(reply_to_name + other_replies); //将除了reply_to_name的其他名字默认选中 Editable etext = inputField.getText(); int start = reply_to_name.length(); int stop = etext.length(); Selection.setSelection(etext, start, stop); } }else if (REPOST_TWEET_ACTION.equals(action)) { if (!TextUtils.isEmpty(text)){ // 如果是转发消息,则根据用户习惯,将光标放置在转发消息的头部或尾部 SharedPreferences prefereces = getPreferences(); boolean isAppendToTheBeginning = prefereces.getBoolean( Preferences.RT_INSERT_APPEND, true); EditText inputField = mTweetEdit.getEditText(); inputField.setTextKeepState(text); Editable etext = inputField.getText(); int position = (isAppendToTheBeginning) ? 0 : etext.length(); Selection.setSelection(etext, position); } } mLocationButton = (ImageButton) findViewById(R.id.location_button); mLocationButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Toast.makeText(WriteActivity.this, "LBS地理定位功能开发中, 敬请期待", Toast.LENGTH_SHORT).show(); } }); Button mTopSendButton = (Button) findViewById(R.id.top_send_btn); mTopSendButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { doSend(); } }); return true; } else { return false; } } private View.OnClickListener deleteListener = new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = getIntent(); intent.setAction(null); withPic = false; mPreview.setVisibility(View.INVISIBLE); imageDelete.setVisibility(View.INVISIBLE); } }; @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). if (dialog != null) { dialog.dismiss(); } 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(Intent.EXTRA_TEXT, text); intent.putExtra(Intent.EXTRA_SUBJECT, ""); return intent; } public static Intent createNewReplyIntent(String tweetText, String screenName, String replyId) { Intent intent = new Intent(WriteActivity.REPLY_TWEET_ACTION); intent.putExtra(Intent.EXTRA_SUBJECT, ""); intent.putExtra(Intent.EXTRA_TEXT, TextHelper.getSimpleTweetText(tweetText)); intent.putExtra(WriteActivity.EXTRA_REPLY_TO_NAME, screenName); intent.putExtra(WriteActivity.EXTRA_REPLY_ID, replyId); return intent; } public static Intent createNewRepostIntent(Context content, String tweetText, String screenName, String repostId) { SharedPreferences mPreferences = PreferenceManager .getDefaultSharedPreferences(content); String prefix = mPreferences.getString(Preferences.RT_PREFIX_KEY, content.getString(R.string.pref_rt_prefix_default)); String retweet = " " + prefix + " @" + screenName + " " + TextHelper.getSimpleTweetText(tweetText); Intent intent = new Intent(WriteActivity.REPOST_TWEET_ACTION); intent.putExtra(Intent.EXTRA_SUBJECT, ""); intent.putExtra(Intent.EXTRA_TEXT, retweet); intent.putExtra(WriteActivity.EXTRA_REPOST_ID, repostId); return intent; } public static Intent createImageIntent(Activity activity, Uri uri) { Intent intent = new Intent(Intent.ACTION_SEND); intent.putExtra(Intent.EXTRA_STREAM, uri); try { WriteActivity writeActivity = (WriteActivity) activity; intent.putExtra(Intent.EXTRA_TEXT, writeActivity.mTweetEdit.getText()); intent.putExtra(WriteActivity.EXTRA_REPLY_TO_NAME, writeActivity._reply_to_name); intent.putExtra(WriteActivity.EXTRA_REPLY_ID, writeActivity._reply_id); intent.putExtra(WriteActivity.EXTRA_REPOST_ID, writeActivity._repost_id); } catch (ClassCastException e) { // do nothing } return intent; } private class MyTextWatcher implements TextWatcher { private WriteActivity _activity; public MyTextWatcher(WriteActivity activity) { _activity = activity; } @Override public void afterTextChanged(Editable s) { if (s.length() == 0) { _activity._reply_id = null; _activity._reply_to_name = null; _activity._repost_id = null; } } @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 View.OnKeyListener tweetEnterHandler = 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) { WriteActivity t = (WriteActivity) (v.getContext()); doSend(); } return true; } return false; } }; private void doSend() { Log.d(TAG, "dosend "+withPic); startTime = System.currentTimeMillis(); Log.d(TAG, String.format("doSend, reply_id=%s", _reply_id)); if (mSendTask != null && mSendTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { String status = mTweetEdit.getText().toString(); if (!TextUtils.isEmpty(status) || withPic) { int mode = SendTask.TYPE_NORMAL; if (withPic) { mode = SendTask.TYPE_PHOTO; } else if (null != _reply_id) { mode = SendTask.TYPE_REPLY; } else if (null != _repost_id) { mode = SendTask.TYPE_REPOST; } mSendTask = new SendTask(); mSendTask.setListener(mSendTaskListener); TaskParams params = new TaskParams(); params.put("mode", mode); mSendTask.execute(params); } else { updateProgress(getString(R.string.page_text_is_null)); } } } private class SendTask extends GenericTask { public static final int TYPE_NORMAL = 0; public static final int TYPE_REPLY = 1; public static final int TYPE_REPOST = 2; public static final int TYPE_PHOTO = 3; @Override protected TaskResult _doInBackground(TaskParams... params) { TaskParams param = params[0]; try { String status = mTweetEdit.getText().toString(); int mode = param.getInt("mode"); Log.d(TAG, "Send Status. Mode : " + mode); // Send status in different way switch (mode) { case TYPE_REPLY: // 增加容错性,即使reply_id为空依然允许发送 if (null == WriteActivity.this._reply_id) { Log.e(TAG, "Cann't send status in REPLY mode, reply_id is null"); } getApi().updateStatus(status, WriteActivity.this._reply_id); break; case TYPE_REPOST: // 增加容错性,即使repost_id为空依然允许发送 if (null == WriteActivity.this._repost_id) { Log.e(TAG, "Cann't send status in REPOST mode, repost_id is null"); } getApi().repost(status, WriteActivity.this._repost_id); break; case TYPE_PHOTO: if (null != mFile) { // Compress image try { mFile = getImageManager().compressImage(mFile, 100); //ImageManager.DEFAULT_COMPRESS_QUALITY); } catch (IOException ioe) { Log.e(TAG, "Cann't compress images."); } getApi().updateStatus(status, mFile); } else { Log.e(TAG, "Cann't send status in PICTURE mode, photo is null"); } break; case TYPE_NORMAL: default: getApi().updateStatus(status); // just send a status break; } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); if (e.getStatusCode() == HttpClient.NOT_AUTHORIZED) { return TaskResult.AUTH_ERROR; } return TaskResult.IO_ERROR; } return TaskResult.OK; } private ImageManager getImageManager() { return TwitterApplication.mImageLoader.getImageManager(); } } private void onSendBegin() { disableEntry(); dialog = ProgressDialog.show(WriteActivity.this, "", getString(R.string.page_status_updating), true); if (dialog != null) { dialog.setCancelable(false); } updateProgress(getString(R.string.page_status_updating)); } private void onSendSuccess() { if (dialog != null) { dialog.setMessage(getString(R.string.page_status_update_success)); dialog.dismiss(); } _reply_id = null; _repost_id = null; updateProgress(getString(R.string.page_status_update_success)); enableEntry(); // FIXME: 不理解这段代码的含义,暂时注释掉 // try { // Thread.currentThread(); // Thread.sleep(500); // updateProgress(""); // } catch (InterruptedException e) { // Log.d(TAG, e.getMessage()); // } updateProgress(""); // 发送成功就自动关闭界面 finish(); // 关闭软键盘 InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mTweetEdit.getEditText().getWindowToken(), 0); } private void onSendFailure() { dialog.setMessage(getString(R.string.page_status_unable_to_update)); dialog.dismiss(); updateProgress(getString(R.string.page_status_unable_to_update)); enableEntry(); } private void enableEntry() { mTweetEdit.setEnabled(true); mLocationButton.setEnabled(true); chooseImagesButton.setEnabled(true); } private void disableEntry() { mTweetEdit.setEnabled(false); mLocationButton.setEnabled(false); chooseImagesButton.setEnabled(false); } // UI helpers. private void updateProgress(String progress) { mProgressText.setText(progress); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { Intent intent = WriteActivity.createImageIntent(this, mImageUri); //照相完后不重新起一个WriteActivity getPic(intent, mImageUri); /*intent.setClass(this, WriteActivity.class); startActivity(intent); // 打开发送图片界面后将自身关闭 finish();*/ } else if (requestCode == REQUEST_PHOTO_LIBRARY && resultCode == RESULT_OK) { mImageUri = data.getData(); Intent intent = WriteActivity.createImageIntent(this, mImageUri); //选图片后不重新起一个WriteActivity getPic(intent, mImageUri); /*intent.setClass(this, WriteActivity.class); startActivity(intent); // 打开发送图片界面后将自身关闭 finish();*/ } } }
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 com.ch_linghu.fanfoudroid.app.Preferences; import android.app.Activity; import android.content.ComponentName; import android.content.pm.ActivityInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class AboutActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); if (TwitterApplication.mPref.getBoolean( Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } //set real version ComponentName comp = new ComponentName(this, getClass()); PackageInfo pinfo = null; try { pinfo = getPackageManager().getPackageInfo(comp.getPackageName(), 0); } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } TextView version = (TextView)findViewById(R.id.version); version.setText(String.format("v %s", pinfo.versionName)); //bind button click event Button okBtn = (Button)findViewById(R.id.ok_btn); okBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } }
Java
package com.ch_linghu.fanfoudroid.dao; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Database Helper * * @see SQLiteDatabase */ public class SQLiteTemplate { /** * Default Primary key */ protected String mPrimaryKey = "_id"; /** * SQLiteDatabase Open Helper */ protected SQLiteOpenHelper mDatabaseOpenHelper; /** * Construct * * @param databaseOpenHelper */ public SQLiteTemplate(SQLiteOpenHelper databaseOpenHelper) { mDatabaseOpenHelper = databaseOpenHelper; } /** * Construct * * @param databaseOpenHelper * @param primaryKey */ public SQLiteTemplate(SQLiteOpenHelper databaseOpenHelper, String primaryKey) { this(databaseOpenHelper); setPrimaryKey(primaryKey); } /** * 根据某一个字段和值删除一行数据, 如 name="jack" * * @param table * @param field * @param value * @return */ public int deleteByField(String table, String field, String value) { return getDb(true).delete(table, field + "=?", new String[] { value }); } /** * 根据主键删除一行数据 * * @param table * @param id * @return */ public int deleteById(String table, String id) { return deleteByField(table, mPrimaryKey, id); } /** * 根据主键更新一行数据 * * @param table * @param id * @param values * @return */ public int updateById(String table, String id, ContentValues values) { return getDb(true).update(table, values, mPrimaryKey + "=?", new String[] { id }); } /** * 根据主键查看某条数据是否存在 * * @param table * @param id * @return */ public boolean isExistsById(String table, String id) { return isExistsByField(table, mPrimaryKey, id); } /** * 根据某字段/值查看某条数据是否存在 * * @param status * @return */ public boolean isExistsByField(String table, String field, String value) { StringBuilder sql = new StringBuilder(); sql.append("SELECT COUNT(*) FROM ").append(table).append(" WHERE ") .append(field).append(" =?"); return isExistsBySQL(sql.toString(), new String[] { value }); } /** * 使用SQL语句查看某条数据是否存在 * * @param sql * @param selectionArgs * @return */ public boolean isExistsBySQL(String sql, String[] selectionArgs) { boolean result = false; final Cursor c = getDb(false).rawQuery(sql, selectionArgs); try { if (c.moveToFirst()) { result = (c.getInt(0) > 0); } } finally { c.close(); } return result; } /** * Query for cursor * * @param <T> * @param rowMapper * @return a cursor * * @see SQLiteDatabase#query(String, String[], String, String[], String, * String, String, String) */ public <T> T queryForObject(RowMapper<T> rowMapper, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) { T object = null; final Cursor c = getDb(false).query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit); try { if (c.moveToFirst()) { object = rowMapper.mapRow(c, c.getCount()); } } finally { c.close(); } return object; } /** * Query for list * * @param <T> * @param rowMapper * @return list of object * * @see SQLiteDatabase#query(String, String[], String, String[], String, * String, String, String) */ public <T> List<T> queryForList(RowMapper<T> rowMapper, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) { List<T> list = new ArrayList<T>(); final Cursor c = getDb(false).query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit); try { while (c.moveToNext()) { list.add(rowMapper.mapRow(c, 1)); } } finally { c.close(); } return list; } /** * Get Primary Key * * @return */ public String getPrimaryKey() { return mPrimaryKey; } /** * Set Primary Key * * @param primaryKey */ public void setPrimaryKey(String primaryKey) { this.mPrimaryKey = primaryKey; } /** * Get Database Connection * * @param writeable * @return * @see SQLiteOpenHelper#getWritableDatabase(); * @see SQLiteOpenHelper#getReadableDatabase(); */ public SQLiteDatabase getDb(boolean writeable) { if (writeable) { return mDatabaseOpenHelper.getWritableDatabase(); } else { return mDatabaseOpenHelper.getReadableDatabase(); } } /** * Some as Spring JDBC RowMapper * * @see org.springframework.jdbc.core.RowMapper * @see com.ch_linghu.fanfoudroid.db.dao.SqliteTemplate * @param <T> */ public interface RowMapper<T> { public T mapRow(Cursor cursor, int rowNum); } }
Java
package com.ch_linghu.fanfoudroid.dao; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.text.TextUtils; import android.util.Log; import com.ch_linghu.fanfoudroid.dao.SQLiteTemplate.RowMapper; import com.ch_linghu.fanfoudroid.data2.Photo; import com.ch_linghu.fanfoudroid.data2.Status; import com.ch_linghu.fanfoudroid.data2.User; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.db2.FanContent; import com.ch_linghu.fanfoudroid.db2.FanContent.StatusesPropertyTable; import com.ch_linghu.fanfoudroid.db2.FanDatabase; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.db2.FanContent.*; public class StatusDAO { private static final String TAG = "StatusDAO"; private SQLiteTemplate mSqlTemplate; public StatusDAO(Context context) { mSqlTemplate = new SQLiteTemplate(FanDatabase.getInstance(context) .getSQLiteOpenHelper()); } /** * Insert a Status * * 若报 SQLiteconstraintexception 异常, 检查是否某not null字段为空 * * @param status * @param isUnread * @return */ public long insertStatus(Status status) { if (!isExists(status)) { return mSqlTemplate.getDb(true).insert(StatusesTable.TABLE_NAME, null, statusToContentValues(status)); } else { Log.e(TAG, status.getId() + " is exists."); return -1; } } // TODO: public int insertStatuses(List<Status> statuses) { int result = 0; SQLiteDatabase db = mSqlTemplate.getDb(true); try { db.beginTransaction(); for (int i = statuses.size() - 1; i >= 0; i--) { Status status = statuses.get(i); long id = db.insertWithOnConflict(StatusesTable.TABLE_NAME, null, statusToContentValues(status), SQLiteDatabase.CONFLICT_IGNORE); if (-1 == id) { Log.e(TAG, "cann't insert the tweet : " + status.toString()); } else { ++result; Log.v(TAG, String.format( "Insert a status into database : %s", status.toString())); } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } return result; } /** * Delete a status * * @param statusId * @param owner_id * owner id * @param type * status type * @return * @see StatusDAO#deleteStatus(Status) */ public int deleteStatus(String statusId, String owner_id, int type) { //FIXME: 数据模型改变后这里的逻辑需要完全重写,目前仅保证编译可通过 String where = StatusesTable.Columns.ID + " =? "; String[] binds; if (!TextUtils.isEmpty(owner_id)) { where += " AND " + StatusesPropertyTable.Columns.OWNER_ID + " = ? "; binds = new String[] { statusId, owner_id }; } else { binds = new String[] { statusId }; } if (-1 != type) { where += " AND " + StatusesPropertyTable.Columns.TYPE + " = " + type; } return mSqlTemplate.getDb(true).delete(StatusesTable.TABLE_NAME, where.toString(), binds); } /** * Delete a Status * * @param status * @return * @see StatusDAO#deleteStatus(String, String, int) */ public int deleteStatus(Status status) { return deleteStatus(status.getId(), status.getOwnerId(), status.getType()); } /** * Find a status by status ID * * @param statusId * @return */ public Status fetchStatus(String statusId) { return mSqlTemplate.queryForObject(mRowMapper, StatusesTable.TABLE_NAME, null, StatusesTable.Columns.ID + " = ?", new String[] { statusId }, null, null, "created_at DESC", "1"); } /** * Find user's statuses * * @param userId * user id * @param statusType * status type, see {@link StatusTable#TYPE_USER}... * @return list of statuses */ public List<Status> fetchStatuses(String userId, int statusType) { return mSqlTemplate.queryForList(mRowMapper, FanContent.StatusesTable.TABLE_NAME, null, StatusesPropertyTable.Columns.OWNER_ID + " = ? AND " + StatusesPropertyTable.Columns.TYPE + " = " + statusType, new String[] { userId }, null, null, "created_at DESC", null); } /** * @see StatusDAO#fetchStatuses(String, int) */ public List<Status> fetchStatuses(String userId, String statusType) { return fetchStatuses(userId, Integer.parseInt(statusType)); } /** * Update by using {@link ContentValues} * * @param statusId * @param newValues * @return */ public int updateStatus(String statusId, ContentValues values) { return mSqlTemplate.updateById(FanContent.StatusesTable.TABLE_NAME, statusId, values); } /** * Update by using {@link Status} * * @param status * @return */ public int updateStatus(Status status) { return updateStatus(status.getId(), statusToContentValues(status)); } /** * Check if status exists * * FIXME: 取消使用Query * * @param status * @return */ public boolean isExists(Status status) { StringBuilder sql = new StringBuilder(); sql.append("SELECT COUNT(*) FROM ").append(FanContent.StatusesTable.TABLE_NAME) .append(" WHERE ").append(StatusesTable.Columns.ID).append(" =? AND ") .append(StatusesPropertyTable.Columns.OWNER_ID).append(" =? AND ") .append(StatusesPropertyTable.Columns.TYPE).append(" = ") .append(status.getType()); return mSqlTemplate.isExistsBySQL(sql.toString(), new String[] { status.getId(), status.getUser().getId() }); } /** * Status -> ContentValues * * @param status * @param isUnread * @return */ private ContentValues statusToContentValues(Status status) { final ContentValues v = new ContentValues(); v.put(StatusesTable.Columns.ID, status.getId()); v.put(StatusesPropertyTable.Columns.TYPE, status.getType()); v.put(StatusesTable.Columns.TEXT, status.getText()); v.put(StatusesPropertyTable.Columns.OWNER_ID, status.getOwnerId()); v.put(StatusesTable.Columns.FAVORITED, status.isFavorited() + ""); v.put(StatusesTable.Columns.TRUNCATED, status.isTruncated()); // TODO: v.put(StatusesTable.Columns.IN_REPLY_TO_STATUS_ID, status.getInReplyToStatusId()); v.put(StatusesTable.Columns.IN_REPLY_TO_USER_ID, status.getInReplyToUserId()); // v.put(StatusTable.Columns.IN_REPLY_TO_SCREEN_NAME, // status.getInReplyToScreenName()); // v.put(IS_REPLY, status.isReply()); v.put(StatusesTable.Columns.CREATED_AT, TwitterDatabase.DB_DATE_FORMATTER.format(status.getCreatedAt())); v.put(StatusesTable.Columns.SOURCE, status.getSource()); // v.put(StatusTable.Columns.IS_UNREAD, status.isUnRead()); final User user = status.getUser(); if (user != null) { v.put(UserTable.Columns.USER_ID, user.getId()); v.put(UserTable.Columns.SCREEN_NAME, user.getScreenName()); v.put(UserTable.Columns.PROFILE_IMAGE_URL, user.getProfileImageUrl()); } final Photo photo = status.getPhotoUrl(); /*if (photo != null) { v.put(StatusTable.Columns.PIC_THUMB, photo.getThumburl()); v.put(StatusTable.Columns.PIC_MID, photo.getImageurl()); v.put(StatusTable.Columns.PIC_ORIG, photo.getLargeurl()); }*/ return v; } private static final RowMapper<Status> mRowMapper = new RowMapper<Status>() { @Override public Status mapRow(Cursor cursor, int rowNum) { Photo photo = new Photo(); /*photo.setImageurl(cursor.getString(cursor .getColumnIndex(StatusTable.Columns.PIC_MID))); photo.setLargeurl(cursor.getString(cursor .getColumnIndex(StatusTable.Columns.PIC_ORIG))); photo.setThumburl(cursor.getString(cursor .getColumnIndex(StatusTable.Columns.PIC_THUMB))); */ User user = new User(); user.setScreenName(cursor.getString(cursor .getColumnIndex(UserTable.Columns.SCREEN_NAME))); user.setId(cursor.getString(cursor .getColumnIndex(UserTable.Columns.USER_ID))); user.setProfileImageUrl(cursor.getString(cursor .getColumnIndex(UserTable.Columns.PROFILE_IMAGE_URL))); Status status = new Status(); status.setPhotoUrl(photo); status.setUser(user); status.setOwnerId(cursor.getString(cursor .getColumnIndex(StatusesPropertyTable.Columns.OWNER_ID))); // TODO: 将数据库中的statusType改成Int类型 status.setType(cursor.getInt(cursor .getColumnIndex(StatusesPropertyTable.Columns.TYPE))); status.setId(cursor.getString(cursor .getColumnIndex(StatusesTable.Columns.ID))); status.setCreatedAt(DateTimeHelper.parseDateTimeFromSqlite(cursor .getString(cursor.getColumnIndex(StatusesTable.Columns.CREATED_AT)))); // TODO: 更改favorite 在数据库类型为boolean后改为 " != 0 " status.setFavorited(cursor.getString( cursor.getColumnIndex(StatusesTable.Columns.FAVORITED)) .equals("true")); status.setText(cursor.getString(cursor .getColumnIndex(StatusesTable.Columns.TEXT))); status.setSource(cursor.getString(cursor .getColumnIndex(StatusesTable.Columns.SOURCE))); // status.setInReplyToScreenName(cursor.getString(cursor // .getColumnIndex(StatusTable.IN_REPLY_TO_SCREEN_NAME))); status.setInReplyToStatusId(cursor.getString(cursor .getColumnIndex(StatusesTable.Columns.IN_REPLY_TO_STATUS_ID))); status.setInReplyToUserId(cursor.getString(cursor .getColumnIndex(StatusesTable.Columns.IN_REPLY_TO_USER_ID))); status.setTruncated(cursor.getInt(cursor .getColumnIndex(StatusesTable.Columns.TRUNCATED)) != 0); // status.setUnRead(cursor.getInt(cursor // .getColumnIndex(StatusTable.Columns.IS_UNREAD)) != 0); return status; } }; }
Java
package com.ch_linghu.fanfoudroid.task; public enum TaskResult { OK, FAILED, CANCELLED, NOT_FOLLOWED_ERROR, IO_ERROR, AUTH_ERROR }
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; 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; 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; 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; 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.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; 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
/* * 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
/* * 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.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; 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.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.TwitterCursorBaseActivity; public class TwitterActivity extends TwitterCursorBaseActivity { private static final String TAG = "TwitterActivity"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.TWEETS"; protected GenericTask mDeleteTask; 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(); } } }; 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("饭否fanfou.com"); //仅在这个页面进行schedule的处理 manageUpdateChecks(); return true; } else { return false; } } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { mDeleteTask.cancel(true); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } // Menu. @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } private int CONTEXT_DELETE_ID = getLastContextMenuId() + 1; @Override protected int getLastContextMenuId() { return CONTEXT_DELETE_ID; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; Tweet tweet = getContextItemTweet(info.position); if (null != tweet) {// 当按钮为 刷新/更多的时候为空 if (tweet.userId.equals(TwitterApplication.getMyselfId())) { menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete); } } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); Tweet tweet = getContextItemTweet(info.position); if (tweet == null) { Log.w(TAG, "Selected item not available."); return super.onContextItemSelected(item); } if (item.getItemId() == CONTEXT_DELETE_ID) { doDelete(tweet.id); return true; } else { return super.onContextItemSelected(item); } } @SuppressWarnings("deprecation") @Override protected Cursor fetchMessages() { return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_HOME); } @Override protected String getActivityTitle() { return getResources().getString(R.string.page_title_home); } @Override protected void markAllRead() { getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_HOME); } // hasRetrieveListTask interface @Override public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) { // 获取消息的时候,将status里获取的user也存储到数据库 // ::MARK:: for (Tweet t : tweets) { getDb().createWeiboUserInfo(t.user); } return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_HOME, isUnread); } @Override public String fetchMaxId() { return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_HOME); } @Override public List<Status> getMessageSinceId(String maxId) throws HttpException { if (maxId != null) { return getApi().getFriendsTimeline(new Paging(maxId)); } else { return getApi().getFriendsTimeline(); } } public void onDeleteFailure() { Log.e(TAG, "Delete failed"); } public void onDeleteSuccess() { mTweetAdapter.refresh(); } 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 String fetchMinId() { return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_HOME); } @Override public List<Status> getMoreMessageFromId(String minId) throws HttpException { Paging paging = new Paging(1, 20); paging.setMaxId(minId); return getApi().getFriendsTimeline(paging); } @Override public int getDatabaseType() { return StatusTable.TYPE_HOME; } @Override public String getUserId() { return TwitterApplication.getMyselfId(); } }
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
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
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.widget.ListAdapter; public interface TweetAdapter extends ListAdapter{ void refresh(); }
Java
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 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 android.content.Context; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.MotionEvent; public interface Widget { Context getContext(); // TEMP public static interface OnGestureListener { /** * @param e1 * The first down motion event that started the fling. * @param e2 * The move motion event that triggered the current onFling. * @param velocityX * The velocity of this fling measured in pixels per second * along the x axis. * @param velocityY * The velocity of this fling measured in pixels per second * along the y axis. * @return true if the event is consumed, else false * * @see SimpleOnGestureListener#onFling */ boolean onFlingDown(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY); boolean onFlingUp(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY); boolean onFlingLeft(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY); boolean onFlingRight(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY); } public static interface OnRefreshListener { void onRefresh(); } }
Java
package com.ch_linghu.fanfoudroid.ui.module; import com.ch_linghu.fanfoudroid.R; import android.app.Activity; import android.util.Log; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; /** * FlingGestureLIstener, 封装 {@link SimpleOnGestureListener} . * 主要用于识别类似向上下或向左右滑动等基本手势. * * 该类主要解决了与ListView自带的上下滑动冲突问题. * 解决方法为将listView的onTouchListener进行覆盖:<code> * FlingGestureListener gListener = new FlingGestureListener(this, * MyActivityFlipper.create(this)); * myListView.setOnTouchListener(gListener); * </code> * * 该类一般和实现了 {@link Widget.OnGestureListener} 接口的类共同协作. * 在识别到手势后会自动调用其相关的回调方法, 以实现手势触发事件效果. * * @see Widget.OnGestureListener * */ public class FlingGestureListener extends SimpleOnGestureListener implements OnTouchListener { private static final String TAG = "FlipperGestureListener"; private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_MAX_DISTANCE = 400; private static final int SWIPE_THRESHOLD_VELOCITY = 200; private Widget.OnGestureListener mListener; private GestureDetector gDetector; private Activity activity; public FlingGestureListener(Activity activity, Widget.OnGestureListener listener) { this(activity, listener, null); } public FlingGestureListener(Activity activity, Widget.OnGestureListener listener, GestureDetector gDetector) { if (gDetector == null) { gDetector = new GestureDetector(activity, this); } this.gDetector = gDetector; mListener = listener; this.activity = activity; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { Log.d(TAG, "On fling"); boolean result = super.onFling(e1, e2, velocityX, velocityY); float xDistance = Math.abs(e1.getX() - e2.getX()); float yDistance = Math.abs(e1.getY() - e2.getY()); velocityX = Math.abs(velocityX); velocityY = Math.abs(velocityY); try { if (xDistance > SWIPE_MAX_DISTANCE || yDistance > SWIPE_MAX_DISTANCE) { Log.d(TAG, "OFF_PATH"); return result; } if (velocityX > SWIPE_THRESHOLD_VELOCITY && xDistance > SWIPE_MIN_DISTANCE) { if (e1.getX() > e2.getX()) { Log.d(TAG, "<------"); result = mListener.onFlingLeft(e1, e1, velocityX, velocityY); activity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out); } else { Log.d(TAG, "------>"); result = mListener.onFlingRight(e1, e1, velocityX, velocityY); activity.overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out); } } else if (velocityY > SWIPE_THRESHOLD_VELOCITY && yDistance > SWIPE_MIN_DISTANCE) { if (e1.getY() > e2.getY()) { Log.d(TAG, "up"); result = mListener.onFlingUp(e1, e1, velocityX, velocityY); } else { Log.d(TAG, "down"); result = mListener.onFlingDown(e1, e1, velocityX, velocityY); } } else { Log.d(TAG, "not hint"); } } catch (Exception e) { e.printStackTrace(); Log.e(TAG, "onFling error " + e.getMessage()); } return result; } @Override public void onLongPress(MotionEvent e) { // TODO Auto-generated method stub super.onLongPress(e); } @Override public boolean onTouch(View v, MotionEvent event) { Log.d(TAG, "On Touch"); // Within the MyGestureListener class you can now manage the // event.getAction() codes. // Note that we are now calling the gesture Detectors onTouchEvent. // And given we've set this class as the GestureDetectors listener // the onFling, onSingleTap etc methods will be executed. return gDetector.onTouchEvent(event); } public GestureDetector getDetector() { return gDetector; } }
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 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
/* * 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.ui.module; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.view.Gravity; import android.view.View; import android.view.WindowManager.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.GridView; import android.widget.SimpleAdapter; import android.widget.Toast; import com.ch_linghu.fanfoudroid.BrowseActivity; import com.ch_linghu.fanfoudroid.DmActivity; import com.ch_linghu.fanfoudroid.FavoritesActivity; import com.ch_linghu.fanfoudroid.FollowersActivity; import com.ch_linghu.fanfoudroid.FollowingActivity; import com.ch_linghu.fanfoudroid.MentionActivity; import com.ch_linghu.fanfoudroid.ProfileActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.UserTimelineActivity; /** * 顶部主菜单切换浮动层 * * @author lds * */ public class MenuDialog extends Dialog { private static final int PAGE_MINE = 0; private static final int PAGE_PROFILE = 1; private static final int PAGE_FOLLOWERS = 2; private static final int PAGE_FOLLOWING = 3; private static final int PAGE_HOME = 4; private static final int PAGE_MENTIONS = 5; private static final int PAGE_BROWSE = 6; private static final int PAGE_FAVORITES = 7; private static final int PAGE_MESSAGE = 8; private List<int[]> pages = new ArrayList<int[]>(); { pages.add(new int[] { R.drawable.menu_tweets, R.string.pages_mine }); pages.add(new int[] { R.drawable.menu_profile, R.string.pages_profile }); pages.add(new int[] { R.drawable.menu_followers, R.string.pages_followers }); pages.add(new int[] { R.drawable.menu_following, R.string.pages_following }); pages.add(new int[] { R.drawable.menu_list, R.string.pages_home }); pages.add(new int[] { R.drawable.menu_mentions, R.string.pages_mentions }); pages.add(new int[] { R.drawable.menu_listed, R.string.pages_browse }); pages.add(new int[] { R.drawable.menu_favorites, R.string.pages_search }); pages.add(new int[] { R.drawable.menu_create_list, R.string.pages_message }); }; private GridView gridview; public MenuDialog(Context context, boolean cancelable, OnCancelListener cancelListener) { super(context, cancelable, cancelListener); // TODO Auto-generated constructor stub } public MenuDialog(Context context, int theme) { super(context, theme); // TODO Auto-generated constructor stub } public MenuDialog(Context context) { super(context, R.style.Theme_Transparent); setContentView(R.layout.menu_dialog); // setTitle("Custom Dialog"); setCanceledOnTouchOutside(true); // 设置window属性 LayoutParams a = getWindow().getAttributes(); a.gravity = Gravity.TOP; a.dimAmount = 0; // 去背景遮盖 getWindow().setAttributes(a); initMenu(); } public void setPosition(int x, int y) { LayoutParams a = getWindow().getAttributes(); if (-1 != x) a.x = x; if (-1 != y) a.y = y; getWindow().setAttributes(a); } private void goTo(Class<?> cls, Intent intent) { if (getOwnerActivity().getClass() != cls) { dismiss(); intent.setClass(getContext(), cls); getContext().startActivity(intent); } else { String msg = getContext().getString(R.string.page_status_same_page); Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show(); } } private void goTo(Class<?> cls){ Intent intent = new Intent(); goTo(cls, intent); } private void initMenu() { // 准备要添加的数据条目 List<Map<String, Object>> items = new ArrayList<Map<String, Object>>(); for (int[] item : pages) { Map<String, Object> map = new HashMap<String, Object>(); map.put("image", item[0]); map.put("title", getContext().getString(item[1]) ); items.add(map); } // 实例化一个适配器 SimpleAdapter adapter = new SimpleAdapter(getContext(), items, // data R.layout.menu_item, // grid item layout new String[] { "title", "image" }, // data's key new int[] { R.id.item_text, R.id.item_image }); // item view id // 获得GridView实例 gridview = (GridView) findViewById(R.id.mygridview); // 将GridView和数据适配器关联 gridview.setAdapter(adapter); } public void bindEvent(Activity activity) { setOwnerActivity(activity); // 绑定监听器 gridview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { switch (position) { case PAGE_MINE: String user = TwitterApplication.getMyselfId(); String name = TwitterApplication.getMyselfName(); Intent intent = UserTimelineActivity.createIntent(user, name); goTo(UserTimelineActivity.class, intent); break; case PAGE_PROFILE: goTo(ProfileActivity.class); break; case PAGE_FOLLOWERS: goTo(FollowersActivity.class); break; case PAGE_FOLLOWING: goTo(FollowingActivity.class); break; case PAGE_HOME: goTo(TwitterActivity.class); break; case PAGE_MENTIONS: goTo(MentionActivity.class); break; case PAGE_BROWSE: goTo(BrowseActivity.class); break; case PAGE_FAVORITES: goTo(FavoritesActivity.class); break; case PAGE_MESSAGE: goTo(DmActivity.class); break; } } }); Button close_button = (Button) findViewById(R.id.close_menu); close_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); } }
Java
/** * */ package com.ch_linghu.fanfoudroid.ui.module; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; 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.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.db.UserInfoTable; public class UserCursorAdapter extends CursorAdapter implements TweetAdapter { private static final String TAG = "TweetCursorAdapter"; private Context mContext; public UserCursorAdapter(Context context, Cursor cursor) { super(context, cursor); mContext = context; if (context != null) { mInflater = LayoutInflater.from(context); } if (cursor != null) { mScreenNametColumn=cursor.getColumnIndexOrThrow(UserInfoTable.FIELD_USER_SCREEN_NAME); mUserIdColumn=cursor.getColumnIndexOrThrow(UserInfoTable._ID); mProfileImageUrlColumn=cursor.getColumnIndexOrThrow(UserInfoTable.FIELD_PROFILE_IMAGE_URL); // mLastStatusColumn=cursor.getColumnIndexOrThrow(UserInfoTable.FIELD_LAST_STATUS); } mMetaBuilder = new StringBuilder(); } private LayoutInflater mInflater; private int mScreenNametColumn; private int mUserIdColumn; private int mProfileImageUrlColumn; //private int mLastStatusColumn; private StringBuilder mMetaBuilder; private ImageLoaderCallback callback = new ImageLoaderCallback(){ @Override public void refresh(String url, Bitmap bitmap) { UserCursorAdapter.this.refresh(); } }; @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater.inflate(R.layout.follower_item, parent, false); Log.d(TAG,"load newView"); UserCursorAdapter.ViewHolder holder = new ViewHolder(); holder.screenName=(TextView) view.findViewById(R.id.screen_name); holder.profileImage=(ImageView)view.findViewById(R.id.profile_image); //holder.lastStatus=(TextView) view.findViewById(R.id.last_status); holder.userId=(TextView) view.findViewById(R.id.user_id); view.setTag(holder); return view; } private static class ViewHolder { public TextView screenName; public TextView userId; public TextView lastStatus; public ImageView profileImage; } @Override public void bindView(View view, Context context, Cursor cursor) { UserCursorAdapter.ViewHolder holder = (UserCursorAdapter.ViewHolder) view .getTag(); Log.d(TAG, "cursor count="+cursor.getCount()); Log.d(TAG,"holder is null?"+(holder==null?"yes":"no")); SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);; boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true); String profileImageUrl = cursor.getString(mProfileImageUrlColumn); if (useProfileImage){ if (!TextUtils.isEmpty(profileImageUrl)) { holder.profileImage.setImageBitmap(TwitterApplication.mImageLoader .get(profileImageUrl, callback)); } }else{ holder.profileImage.setVisibility(View.GONE); } holder.screenName.setText(cursor.getString(mScreenNametColumn)); holder.userId.setText(cursor.getString(mUserIdColumn)); } @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 android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.graphics.Color; import android.text.Layout; import android.text.Spannable; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.text.style.URLSpan; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.Preferences; public class MyTextView extends TextView { private static float mFontSize = 15; private static boolean mFontSizeChanged = true; public MyTextView(Context context) { super(context, null); } public MyTextView(Context context, AttributeSet attrs) { super(context, attrs); setLinksClickable(false); Resources res = getResources(); int color = res.getColor(R.color.link_color); setLinkTextColor(color); initFontSize(); } public void initFontSize() { if ( mFontSizeChanged ) { mFontSize = getFontSizeFromPreferences(mFontSize); setFontSizeChanged(false); // reset } setTextSize(mFontSize); } private float getFontSizeFromPreferences(float defaultValue) { SharedPreferences preferences = TwitterApplication.mPref; if (preferences.contains(Preferences.UI_FONT_SIZE)) { Log.v("DEBUG", preferences.getString(Preferences.UI_FONT_SIZE, "null") + " CHANGE FONT SIZE"); return Float.parseFloat(preferences.getString( Preferences.UI_FONT_SIZE, "14")); } return defaultValue; } private URLSpan mCurrentLink; private ForegroundColorSpan mLinkFocusStyle = new ForegroundColorSpan( Color.RED); @Override public boolean onTouchEvent(MotionEvent event) { CharSequence text = getText(); int action = event.getAction(); if (!(text instanceof Spannable)) { return super.onTouchEvent(event); } Spannable buffer = (Spannable) text; if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_MOVE) { TextView widget = this; int x = (int) event.getX(); int y = (int) event.getY(); x -= widget.getTotalPaddingLeft(); y -= widget.getTotalPaddingTop(); x += widget.getScrollX(); y += widget.getScrollY(); Layout layout = widget.getLayout(); int line = layout.getLineForVertical(y); int off = layout.getOffsetForHorizontal(line, x); URLSpan[] link = buffer.getSpans(off, off, URLSpan.class); if (link.length != 0) { if (action == MotionEvent.ACTION_UP) { if (mCurrentLink == link[0]) { link[0].onClick(widget); } mCurrentLink = null; buffer.removeSpan(mLinkFocusStyle); } else if (action == MotionEvent.ACTION_DOWN) { mCurrentLink = link[0]; buffer.setSpan(mLinkFocusStyle, buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0]), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } return true; } } mCurrentLink = null; buffer.removeSpan(mLinkFocusStyle); return super.onTouchEvent(event); } public static void setFontSizeChanged(boolean isChanged) { mFontSizeChanged = isChanged; } @Override public void onWindowFocusChanged(boolean hasWindowFocus) { super.onWindowFocusChanged(hasWindowFocus); } }
Java
package com.ch_linghu.fanfoudroid.ui.module; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Intent; import android.util.Log; import android.view.Gravity; import android.widget.ImageView; import android.widget.Toast; import android.widget.ViewSwitcher.ViewFactory; import com.ch_linghu.fanfoudroid.R; /** * ActivityFlipper, 和 {@link ViewFactory} 类似, 只是设计用于切换activity. * * 切换的前后顺序取决与注册时的先后顺序 * * USAGE: <code> * ActivityFlipper mFlipper = new ActivityFlipper(this); * mFlipper.addActivity(TwitterActivity.class); * mFlipper.addActivity(MentionActivity.class); * mFlipper.addActivity(DmActivity.class); * * // switch activity * mFlipper.setCurrentActivity(TwitterActivity.class); * mFlipper.showNext(); * mFlipper.showPrevious(); * * // or without set current activity * mFlipper.showNextOf(TwitterActivity.class); * mFlipper.showPreviousOf(TwitterActivity.class); * * // or auto mode, use the context as current activity * mFlipper.autoShowNext(); * mFlipper.autoShowPrevious(); * * // set toast * mFlipper.setToastResource(new int[] { * R.drawable.point_left, * R.drawable.point_center, * R.drawable.point_right * }); * * // set Animation * mFlipper.setInAnimation(R.anim.push_left_in); * mFlipper.setOutAnimation(R.anim.push_left_out); * mFlipper.setPreviousInAnimation(R.anim.push_right_in); * mFlipper.setPreviousOutAnimation(R.anim.push_right_out); * </code> * */ public class ActivityFlipper implements IFlipper { private static final String TAG = "ActivityFlipper"; private static final int SHOW_NEXT = 0; private static final int SHOW_PROVIOUS = 1; private int mDirection = SHOW_NEXT; private boolean mToastEnabled = false; private int[] mToastResourcesMap = new int[]{}; private boolean mAnimationEnabled = false; private int mNextInAnimation = -1; private int mNextOutAnimation = -1; private int mPreviousInAnimation = -1; private int mPreviousOutAnimation = -1; private Activity mActivity; private List<Class<?>> mActivities = new ArrayList<Class<?>>();; private int mWhichActivity = 0; public ActivityFlipper() { } public ActivityFlipper(Activity activity) { mActivity = activity; } /** * Launch Activity * * @param cls * class of activity */ public void launchActivity(Class<?> cls) { Log.v(TAG, "launch activity :" + cls.getName()); Intent intent = new Intent(); intent.setClass(mActivity, cls); mActivity.startActivity(intent); } public void setToastResource(int[] resourceIds) { mToastEnabled = true; mToastResourcesMap = resourceIds; } private void maybeShowToast(int whichActicity) { if (mToastEnabled && whichActicity < mToastResourcesMap.length) { final Toast myToast = new Toast(mActivity); final ImageView myView = new ImageView(mActivity); myView.setImageResource(mToastResourcesMap[whichActicity]); myToast.setView(myView); myToast.setDuration(Toast.LENGTH_SHORT); myToast.setGravity(Gravity.BOTTOM | Gravity.CENTER, 0, 0); myToast.show(); } } private void maybeShowAnimation(int whichActivity) { if (mAnimationEnabled) { boolean showPrevious = (mDirection == SHOW_PROVIOUS); if (showPrevious && mPreviousInAnimation != -1 && mPreviousOutAnimation != -1) { mActivity.overridePendingTransition( mPreviousInAnimation, mPreviousOutAnimation); return; // use Previous Animation } if (mNextInAnimation != -1 && mNextOutAnimation != -1) { mActivity.overridePendingTransition( mNextInAnimation, mNextOutAnimation); } } } /** * Launch Activity by index * * @param whichActivity * the index of Activity */ private void launchActivity(int whichActivity) { launchActivity(mActivities.get(whichActivity)); maybeShowToast(whichActivity); maybeShowAnimation(whichActivity); } /** * Add Activity NOTE: 添加的顺序很重要 * * @param cls * class of activity */ public void addActivity(Class<?> cls) { mActivities.add(cls); } /** * Get index of the Activity * * @param cls * class of activity * @return */ private int getIndexOf(Class<?> cls) { int index = mActivities.indexOf(cls); if (-1 == index) { Log.e(TAG, "No such activity: " + cls.getName()); } return index; } @SuppressWarnings("unused") private Class<?> getActivityAt(int index) { if (index > 0 && index < mActivities.size()) { return mActivities.get(index); } return null; } /** * Show next activity(already setCurrentActivity) */ @Override public void showNext() { mDirection = SHOW_NEXT; setDisplayedActivity(mWhichActivity + 1, true); } /** * Show next activity of * * @param cls * class of activity */ public void showNextOf(Class<?> cls) { setCurrentActivity(cls); showNext(); } /** * Show next activity(use current context as a activity) */ public void autoShowNext() { showNextOf(mActivity.getClass()); } /** * Show previous activity(already setCurrentActivity) */ @Override public void showPrevious() { mDirection = SHOW_PROVIOUS; setDisplayedActivity(mWhichActivity - 1, true); } /** * Show previous activity of * * @param cls * class of activity */ public void showPreviousOf(Class<?> cls) { setCurrentActivity(cls); showPrevious(); } /** * Show previous activity(use current context as a activity) */ public void autoShowPrevious() { showPreviousOf(mActivity.getClass()); } /** * Sets which child view will be displayed * * @param whichActivity * the index of the child view to display * @param display * display immediately */ public void setDisplayedActivity(int whichActivity, boolean display) { mWhichActivity = whichActivity; if (whichActivity >= getCount()) { mWhichActivity = 0; } else if (whichActivity < 0) { mWhichActivity = getCount() - 1; } if (display) { launchActivity(mWhichActivity); } } /** * Set current Activity * * @param cls * class of activity */ public void setCurrentActivity(Class<?> cls) { setDisplayedActivity(getIndexOf(cls), false); } public void setInAnimation(int resourceId) { setEnableAnimation(true); mNextInAnimation = resourceId; } public void setOutAnimation(int resourceId) { setEnableAnimation(true); mNextOutAnimation = resourceId; } public void setPreviousInAnimation(int resourceId) { mPreviousInAnimation = resourceId; } public void setPreviousOutAnimation(int resourceId) { mPreviousOutAnimation = resourceId; } public void setEnableAnimation(boolean enable) { mAnimationEnabled = enable; } /** * Count activities * * @return the number of activities */ public int getCount() { return mActivities.size(); } }
Java
package com.ch_linghu.fanfoudroid.ui.module; import java.util.List; import android.app.Activity; import android.content.Context; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; import com.ch_linghu.fanfoudroid.R; public class SimpleFeedback implements Feedback, Widget { private static final String TAG = "SimpleFeedback"; public static final int MAX = 100; private ProgressBar mProgress = null; private ProgressBar mLoadingProgress = null; public SimpleFeedback(Context context) { mProgress = (ProgressBar) ((Activity) context) .findViewById(R.id.progress_bar); mLoadingProgress = (ProgressBar) ((Activity) context) .findViewById(R.id.top_refresh_progressBar); } @Override public void start(CharSequence text) { mProgress.setProgress(20); mLoadingProgress.setVisibility(View.VISIBLE); } @Override public void success(CharSequence text) { mProgress.setProgress(100); mLoadingProgress.setVisibility(View.GONE); resetProgressBar(); } @Override public void failed(CharSequence text) { resetProgressBar(); showMessage(text); } @Override public void cancel(CharSequence text) { } @Override public void update(Object arg0) { if (arg0 instanceof Integer) { mProgress.setProgress((Integer) arg0); } else if (arg0 instanceof CharSequence) { showMessage((String) arg0); } } @Override public void setIndeterminate(boolean indeterminate) { mProgress.setIndeterminate(indeterminate); } @Override public Context getContext() { if (mProgress != null) { return mProgress.getContext(); } if (mLoadingProgress != null) { return mLoadingProgress.getContext(); } return null; } @Override public boolean isAvailable() { if (null == mProgress) { Log.e(TAG, "R.id.progress_bar is missing"); return false; } if (null == mLoadingProgress) { Log.e(TAG, "R.id.top_refresh_progressBar is missing"); return false; } return true; } /** * @param total 0~100 * @param maxSize max size of list * @param list * @return */ public static int calProgressBySize(int total, int maxSize, List<?> list) { if (null != list) { return (MAX - (int)Math.floor(list.size() * (total/maxSize))); } return MAX; } private void resetProgressBar() { if (mProgress.isIndeterminate()) { //TODO: 第二次不会出现 mProgress.setIndeterminate(false); } mProgress.setProgress(0); } private void showMessage(CharSequence text) { Toast.makeText(getContext(), text, Toast.LENGTH_LONG).show(); } }
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; 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.content.Context; import android.util.Log; public class FeedbackFactory { private static final String TAG = "FeedbackFactory"; public static enum FeedbackType { DIALOG, PROGRESS, REFRESH }; public static Feedback create(Context context, FeedbackType type) { Feedback feedback = null; switch (type) { case PROGRESS: feedback = new SimpleFeedback(context); break; } if (null == feedback || !feedback.isAvailable()) { feedback = new FeedbackAdapter(context); Log.e(TAG, type + " feedback is not available."); } return feedback; } public static class FeedbackAdapter implements Feedback { public FeedbackAdapter(Context context) {} @Override public void start(CharSequence text) {} @Override public void cancel(CharSequence text) {} @Override public void success(CharSequence text) {} @Override public void failed(CharSequence text) {} @Override public void update(Object arg0) {} @Override public boolean isAvailable() { return true; } @Override public void setIndeterminate(boolean indeterminate) {} } }
Java
package com.ch_linghu.fanfoudroid.ui.base; import android.app.Activity; import android.content.Intent; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.BitmapDrawable; import android.text.TextPaint; import android.util.Log; import android.view.View; import android.view.ViewGroup; 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.RelativeLayout.LayoutParams; 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.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.MenuDialog; import com.ch_linghu.fanfoudroid.ui.module.NavBar; /** * @deprecated 使用 {@link NavBar} 代替 */ public class WithHeaderActivity extends BaseActivity { private static final String TAG = "WithHeaderActivity"; 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; protected ImageView refreshButton; protected ImageButton searchButton; protected ImageButton writeButton; protected TextView titleButton; protected Button backButton; protected ImageButton homeButton; protected MenuDialog dialog; protected EditText searchEdit; protected Feedback mFeedback; // FIXME: 刷新动画二选一, DELETE ME protected AnimationDrawable mRefreshAnimation; protected ProgressBar mProgress = null; protected ProgressBar mLoadingProgress = null; //搜索硬按键行为 @Override public boolean onSearchRequested() { Intent intent = new Intent(); intent.setClass(this, SearchActivity.class); startActivity(intent); return true; } // LOGO按钮 protected void addTitleButton() { titleButton = (TextView) findViewById(R.id.title); titleButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int top = titleButton.getTop(); int height = titleButton.getHeight(); int x = top + height; if (null == dialog) { Log.d(TAG, "Create menu dialog."); dialog = new MenuDialog(WithHeaderActivity.this); dialog.bindEvent(WithHeaderActivity.this); dialog.setPosition(-1, x); } // toggle dialog if (dialog.isShowing()) { dialog.dismiss(); //没机会触发 } else { dialog.show(); } } }); } protected void setHeaderTitle(String title) { titleButton.setBackgroundDrawable( new BitmapDrawable()); titleButton.setText(title); LayoutParams lp = new LayoutParams(android.view.ViewGroup.LayoutParams.WRAP_CONTENT,android.view.ViewGroup.LayoutParams.WRAP_CONTENT); lp.setMargins(3, 12, 0, 0); titleButton.setLayoutParams(lp); // 中文粗体 TextPaint tp = titleButton.getPaint(); tp.setFakeBoldText(true); } protected void setHeaderTitle(int resource) { titleButton.setBackgroundResource(resource); } // 刷新 protected void addRefreshButton() { final Activity that = this; refreshButton = (ImageView) findViewById(R.id.top_refresh); // FIXME: 暂时取消旋转效果, 测试ProgressBar //refreshButton.setBackgroundResource(R.drawable.top_refresh); //mRefreshAnimation = (AnimationDrawable) refreshButton.getBackground(); // FIXME: DELETE ME mProgress = (ProgressBar) findViewById(R.id.progress_bar); mLoadingProgress = (ProgressBar) findViewById(R.id.top_refresh_progressBar); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); refreshButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (that instanceof Refreshable) { ((Refreshable) that).doRetrieve(); } else { Log.e(TAG, "The current view " + that.getClass().getName() + " cann't be retrieved"); } } }); } /** * @param v * @deprecated use {@link WithHeaderActivity#setRefreshAnimation(boolean)} */ protected void animRotate(View v) { setRefreshAnimation(true); } /** * @param progress 0~100 * @deprecated use feedback */ public void setGlobalProgress(int progress) { if ( null != mProgress) { mProgress.setProgress(progress); } } /** * 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"); } } // 搜索 protected void addSearchButton() { searchButton = (ImageButton) findViewById(R.id.search); searchButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // // 旋转动画 // Animation anim = AnimationUtils.loadAnimation(v.getContext(), // R.anim.scale_lite); // v.startAnimation(anim); //go to SearchActivity startSearch(); } }); } // 这个方法会在SearchActivity里重写 protected boolean startSearch() { Intent intent = new Intent(); intent.setClass(this, SearchActivity.class); startActivity(intent); return true; } //搜索框 protected void addSearchBox() { searchEdit = (EditText) findViewById(R.id.search_edit); } // 撰写 protected void addWriteButton() { writeButton = (ImageButton) findViewById(R.id.writeMessage); writeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // 动画 Animation anim = AnimationUtils.loadAnimation(v.getContext(), R.anim.scale_lite); v.startAnimation(anim); // forward to write activity Intent intent = new Intent(); intent.setClass(v.getContext(), WriteActivity.class); v.getContext().startActivity(intent); } }); } // 回首页 protected void addHomeButton() { homeButton = (ImageButton) findViewById(R.id.home); homeButton.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); } }); } // 返回 protected void addBackButton() { backButton = (Button) findViewById(R.id.top_back); // 中文粗体 // TextPaint tp = backButton.getPaint(); // tp.setFakeBoldText(true); backButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Go back to previous activity finish(); } }); } protected void initHeader(int style) { //FIXME: android 1.6似乎不支持addHeaderView中使用的方法 // 来增加header,造成header无法显示和使用。 // 改用在layout xml里include的方法来确保显示 switch (style) { case HEADER_STYLE_HOME: //addHeaderView(R.layout.header); addTitleButton(); addWriteButton(); addSearchButton(); addRefreshButton(); break; case HEADER_STYLE_BACK: //addHeaderView(R.layout.header_back); addBackButton(); addWriteButton(); addSearchButton(); addRefreshButton(); break; case HEADER_STYLE_WRITE: //addHeaderView(R.layout.header_write); addBackButton(); //addHomeButton(); break; case HEADER_STYLE_SEARCH: //addHeaderView(R.layout.header_search); addBackButton(); addSearchBox(); addSearchButton(); break; } } private void addHeaderView(int resource) { // find content root view ViewGroup root = (ViewGroup) getWindow().getDecorView(); ViewGroup content = (ViewGroup) root.getChildAt(0); View header = View.inflate(WithHeaderActivity.this, resource, null); // LayoutParams params = new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT); content.addView(header, 0); } @Override protected void onDestroy() { // dismiss dialog before destroy // to avoid android.view.WindowLeaked Exception if (dialog != null){ dialog.dismiss(); } super.onDestroy(); } }
Java
package com.ch_linghu.fanfoudroid.ui.base; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.data.Tweet; 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.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskManager; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter; public abstract class UserArrayBaseActivity extends UserListBaseActivity { static final String TAG = "UserArrayBaseActivity"; // Views. protected ListView mUserList; protected UserArrayAdapter mUserListAdapter; protected TextView loadMoreBtn; protected ProgressBar loadMoreGIF; protected TextView loadMoreBtnTop; protected ProgressBar loadMoreGIFTop; protected static int lastPosition = 0; // Tasks. protected TaskManager taskManager = new TaskManager(); private GenericTask mRetrieveTask; private GenericTask mFollowersRetrieveTask; private GenericTask mGetMoreTask;// 每次100用户 public abstract Paging getCurrentPage();// 加载 public abstract Paging getNextPage();// 加载 // protected abstract String[] getIds(); protected abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers( String userId, Paging page) throws HttpException; private ArrayList<com.ch_linghu.fanfoudroid.data.User> allUserList; @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { doRetrieve();// 加载第一页 return true; } else { return false; } } @Override public void doRetrieve() { Log.d(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mRetrieveTask = new RetrieveTask(); mRetrieveTask.setFeedback(mFeedback); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); // Add Task to manager taskManager.addTask(mRetrieveTask); } } private TaskListener mRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "RetrieveTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { draw(); } updateProgress(""); } @Override public void onPreExecute(GenericTask task) { onRetrieveBegin(); } @Override public void onProgressUpdate(GenericTask task, Object param) { Log.d(TAG, "onProgressUpdate"); draw(); } }; public void updateProgress(String progress) { mProgressText.setText(progress); } public void onRetrieveBegin() { updateProgress(getString(R.string.page_status_refreshing)); } /** * TODO:从API获取当前Followers * * @author Dino * */ private class RetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.d(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null; try { usersList = getUsers(getUserId(), getCurrentPage()); } catch (HttpException e) { e.printStackTrace(); return TaskResult.IO_ERROR; } publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList)); for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } allUserList.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } return TaskResult.OK; } } @Override protected int getLayoutId() { return R.layout.follower; } @Override protected void setupState() { setTitle(getActivityTitle()); mUserList = (ListView) findViewById(R.id.follower_list); setupListHeader(true); mUserListAdapter = new UserArrayAdapter(this); mUserList.setAdapter(mUserListAdapter); allUserList = new ArrayList<com.ch_linghu.fanfoudroid.data.User>(); } @Override protected String getActivityTitle() { // TODO Auto-generated method stub return null; } @Override protected boolean useBasicMenu() { return true; } @Override protected User getContextItemUser(int position) { // position = position - 1; // 加入footer跳过footer if (position < mUserListAdapter.getCount()) { User item = (User) mUserListAdapter.getItem(position); if (item == null) { return null; } else { return item; } } else { return null; } } /** * TODO:不知道啥用 */ @Override protected void updateTweet(Tweet tweet) { // TODO Auto-generated method stub } @Override protected ListView getUserList() { return mUserList; } @Override protected TweetAdapter getUserAdapter() { return mUserListAdapter; } /** * 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用 */ protected void setupListHeader(boolean addFooter) { // Add footer to Listview View footer = View.inflate(this, R.layout.listview_footer, null); mUserList.addFooterView(footer, null, true); // Find View loadMoreBtn = (TextView) findViewById(R.id.ask_for_more); loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar); } @Override protected void specialItemClicked(int position) { if (position == mUserList.getCount() - 1) { // footer loadMoreGIF.setVisibility(View.VISIBLE); doGetMore(); } } public void doGetMore() { Log.d(TAG, "Attempting getMore."); mFeedback.start(""); if (mGetMoreTask != null && mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mGetMoreTask = new GetMoreTask(); mGetMoreTask.setListener(getMoreListener); mGetMoreTask.execute(); // Add Task to manager taskManager.addTask(mGetMoreTask); } } private TaskListener getMoreListener = new TaskAdapter() { @Override public String getName() { return "getMore"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { super.onPostExecute(task, result); draw(); mFeedback.success(""); loadMoreGIF.setVisibility(View.GONE); } }; /** * TODO:需要重写,获取下一批用户,按页分100页一次 * * @author Dino * */ private class GetMoreTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.d(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null; try { usersList = getUsers(getUserId(), getNextPage()); mFeedback.update(60); } catch (HttpException e) { e.printStackTrace(); return TaskResult.IO_ERROR; } // 将获取到的数据(保存/更新)到数据库 getDb().syncWeiboUsers(usersList); mFeedback.update(100 - (int) Math.floor(usersList.size() * 2)); for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } allUserList.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } mFeedback.update(99); return TaskResult.OK; } } public void draw() { mUserListAdapter.refresh(allUserList); } }
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.ui.base; import java.util.ArrayList; import java.util.List; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.db.UserInfoTable; 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.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskManager; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.ui.module.UserCursorAdapter; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; /** * TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现 */ public abstract class UserCursorBaseActivity extends UserListBaseActivity { /** * 第一种方案:(采取第一种) 暂不放在数据库中,直接从Api读取。 * * 第二种方案: 麻烦的是api数据与数据库同步,当收听人数比较多的时候,一次性读取太费流量 按照饭否api每次分页100人 * 当收听数<100时先从数据库一次性根据API返回的ID列表读取数据,如果数据库中的收听数<总数,那么从API中读取所有用户信息并同步到数据库中。 * 当收听数>100时采取分页加载,先按照id * 获取数据库里前100用户,如果用户数量<100则从api中加载,从page=1开始下载,同步到数据库中,单击更多继续从数据库中加载 * 当数据库中的数据读取到最后一页后,则从api中加载并更新到数据库中。 单击刷新按钮则从api加载并同步到数据库中 * */ static final String TAG = "UserCursorBaseActivity"; // Views. protected ListView mUserList; protected UserCursorAdapter mUserListAdapter; protected TextView loadMoreBtn; protected ProgressBar loadMoreGIF; protected TextView loadMoreBtnTop; protected ProgressBar loadMoreGIFTop; protected static int lastPosition = 0; // Tasks. protected TaskManager taskManager = new TaskManager(); private GenericTask mRetrieveTask; private GenericTask mFollowersRetrieveTask; private GenericTask mGetMoreTask;// 每次十个用户 protected abstract String getUserId();// 获得用户id private TaskListener mRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "RetrieveTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { SharedPreferences.Editor editor = getPreferences().edit(); editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); // TODO: 1. StatusType(DONE) ; 2. 只有在取回的数据大于MAX时才做GC, // 因为小于时可以保证数据的连续性 // FIXME: gc需要带owner // getDb().gc(getDatabaseType()); // GC draw(); goTop(); } else { // Do nothing. } // loadMoreGIFTop.setVisibility(View.GONE); updateProgress(""); } @Override public void onPreExecute(GenericTask task) { onRetrieveBegin(); } @Override public void onProgressUpdate(GenericTask task, Object param) { Log.d(TAG, "onProgressUpdate"); draw(); } }; private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "FollowerRetrieve"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { SharedPreferences sp = getPreferences(); SharedPreferences.Editor editor = sp.edit(); editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); } else { // Do nothing. } } }; // Refresh data at startup if last refresh was this long ago or greater. private static final long REFRESH_THRESHOLD = 5 * 60 * 1000; // Refresh followers if last refresh was this long ago or greater. private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000; abstract protected Cursor fetchUsers(); public abstract int getDatabaseType(); public abstract String fetchMaxId(); public abstract String fetchMinId(); public abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers() throws HttpException; public abstract void addUsers( ArrayList<com.ch_linghu.fanfoudroid.data.User> tusers); // public abstract List<Status> getMessageSinceId(String maxId) // throws WeiboException; public abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUserSinceId( String maxId) throws HttpException; public abstract List<Status> getMoreMessageFromId(String minId) throws HttpException; public abstract Paging getNextPage();// 下一页数 public abstract Paging getCurrentPage();// 当前页数 protected abstract String[] getIds(); public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1; // public static final int CONTEXT_AT_ID = Menu.FIRST + 2; public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3; public static final int CONTEXT_DM_ID = Menu.FIRST + 4; public static final int CONTEXT_MORE_ID = Menu.FIRST + 5; public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6; public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7; @Override protected void setupState() { Cursor cursor; cursor = fetchUsers(); // setTitle(getActivityTitle()); startManagingCursor(cursor); mUserList = (ListView) findViewById(R.id.follower_list); // TODO: 需处理没有数据时的情况 Log.d("LDS", cursor.getCount() + " cursor count"); setupListHeader(true); mUserListAdapter = new UserCursorAdapter(this, cursor); mUserList.setAdapter(mUserListAdapter); // ? registerOnClickListener(mTweetList); } /** * 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用 */ protected void setupListHeader(boolean addFooter) { // Add footer to Listview View footer = View.inflate(this, R.layout.listview_footer, null); mUserList.addFooterView(footer, null, true); // Find View loadMoreBtn = (TextView) findViewById(R.id.ask_for_more); loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar); // loadMoreBtnTop = (TextView)findViewById(R.id.ask_for_more_header); // loadMoreGIFTop = // (ProgressBar)findViewById(R.id.rectangleProgressBar_header); // loadMoreAnimation = (AnimationDrawable) // loadMoreGIF.getIndeterminateDrawable(); } @Override protected void specialItemClicked(int position) { if (position == mUserList.getCount() - 1) { // footer loadMoreGIF.setVisibility(View.VISIBLE); doGetMore(); } } @Override protected int getLayoutId() { return R.layout.follower; } @Override protected ListView getUserList() { return mUserList; } @Override protected TweetAdapter getUserAdapter() { return mUserListAdapter; } @Override protected boolean useBasicMenu() { return true; } protected User getContextItemUser(int position) { // position = position - 1; // 加入footer跳过footer if (position < mUserListAdapter.getCount()) { Cursor cursor = (Cursor) mUserListAdapter.getItem(position); if (cursor == null) { return null; } else { return UserInfoTable.parseCursor(cursor); } } else { return null; } } @Override protected void updateTweet(Tweet tweet) { // TODO: updateTweet() 在哪里调用的? 目前尚只支持: // updateTweet(String tweetId, ContentValues values) // setFavorited(String tweetId, String isFavorited) // 看是否还需要增加updateTweet(Tweet tweet)方法 // 对所有相关表的对应消息都进行刷新(如果存在的话) // getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet); } @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { goTop(); // skip the header boolean shouldRetrieve = false; // FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新 long lastRefreshTime = mPreferences.getLong( Preferences.LAST_TWEET_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 * (Utils.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; } */ shouldRetrieve = true; if (shouldRetrieve) { doRetrieve(); } long lastFollowersRefreshTime = mPreferences.getLong( Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0); diff = nowTime - lastFollowersRefreshTime; Log.d(TAG, "Last followers refresh was " + diff + " ms ago."); /* * if (diff > FOLLOWERS_REFRESH_THRESHOLD && (mRetrieveTask == null * || mRetrieveTask.getStatus() != GenericTask.Status.RUNNING)) { * Log.d(TAG, "Refresh followers."); doRetrieveFollowers(); } */ return true; } else { return false; } } @Override protected void onResume() { Log.d(TAG, "onResume."); if (lastPosition != 0) { mUserList.setSelection(lastPosition); } 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 onRestoreInstanceState(Bundle bundle) { super.onRestoreInstanceState(bundle); // mTweetEdit.updateCharsRemain(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); super.onDestroy(); taskManager.cancelAll(); } @Override protected void onPause() { Log.d(TAG, "onPause."); super.onPause(); lastPosition = mUserList.getFirstVisiblePosition(); } @Override protected void onRestart() { Log.d(TAG, "onRestart."); super.onRestart(); } @Override protected void onStart() { Log.d(TAG, "onStart."); super.onStart(); } @Override protected void onStop() { Log.d(TAG, "onStop."); super.onStop(); } // UI helpers. @Override protected String getActivityTitle() { // TODO Auto-generated method stub return null; } @Override protected void adapterRefresh() { mUserListAdapter.notifyDataSetChanged(); mUserListAdapter.refresh(); } // Retrieve interface public void updateProgress(String progress) { mProgressText.setText(progress); } public void draw() { mUserListAdapter.refresh(); } public void goTop() { Log.d(TAG, "goTop."); mUserList.setSelection(1); } private void doRetrieveFollowers() { Log.d(TAG, "Attempting followers retrieve."); if (mFollowersRetrieveTask != null && mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mFollowersRetrieveTask = new FollowersRetrieveTask(); mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener); mFollowersRetrieveTask.execute(); taskManager.addTask(mFollowersRetrieveTask); // Don't need to cancel FollowersTask (assuming it ends properly). mFollowersRetrieveTask.setCancelable(false); } } public void onRetrieveBegin() { updateProgress(getString(R.string.page_status_refreshing)); } public void doRetrieve() { Log.d(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mRetrieveTask = new RetrieveTask(); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.setFeedback(mFeedback); mRetrieveTask.execute(); // Add Task to manager taskManager.addTask(mRetrieveTask); } } /** * TODO:从API获取当前Followers,并同步到数据库 * * @author Dino * */ private class RetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.d(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null; try { usersList = getApi().getFollowersList(getUserId(), getCurrentPage()); } catch (HttpException e) { e.printStackTrace(); } publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList)); ArrayList<User> users = new ArrayList<User>(); for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } users.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } addUsers(users); return TaskResult.OK; } } private class FollowersRetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { Log.d(TAG, "load FollowersErtrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> t_users = getUsers(); getDb().syncWeiboUsers(t_users); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } /** * TODO:需要重写,获取下一批用户,按页分100页一次 * * @author Dino * */ private class GetMoreTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.d(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null; try { usersList = getApi().getFollowersList(getUserId(), getNextPage()); } catch (HttpException e) { e.printStackTrace(); } publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList)); ArrayList<User> users = new ArrayList<User>(); for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } users.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } addUsers(users); return TaskResult.OK; } } private TaskListener getMoreListener = new TaskAdapter() { @Override public String getName() { return "getMore"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { super.onPostExecute(task, result); draw(); loadMoreGIF.setVisibility(View.GONE); } }; public void doGetMore() { Log.d(TAG, "Attempting getMore."); if (mGetMoreTask != null && mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mGetMoreTask = new GetMoreTask(); mGetMoreTask.setFeedback(mFeedback); mGetMoreTask.setListener(getMoreListener); mGetMoreTask.execute(); // Add Task to manager taskManager.addTask(mGetMoreTask); } } }
Java
package com.ch_linghu.fanfoudroid.ui.base; public interface Refreshable { void doRetrieve(); }
Java
package com.ch_linghu.fanfoudroid.ui.base; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.ch_linghu.fanfoudroid.AboutActivity; import com.ch_linghu.fanfoudroid.LoginActivity; import com.ch_linghu.fanfoudroid.PreferencesActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.fanfou.Weibo; import com.ch_linghu.fanfoudroid.service.TwitterService; /** * A BaseActivity has common routines and variables for an Activity that * contains a list of tweets and a text input field. * * Not the cleanest design, but works okay for several Activities in this app. */ public class BaseActivity extends Activity { private static final String TAG = "BaseActivity"; protected SharedPreferences mPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); _onCreate(savedInstanceState); } // 因为onCreate方法无法返回状态,因此无法进行状态判断, // 为了能对上层返回的信息进行判断处理,我们使用_onCreate代替真正的 // onCreate进行工作。onCreate仅在顶层调用_onCreate。 protected boolean _onCreate(Bundle savedInstanceState) { if (TwitterApplication.mPref.getBoolean( Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } if (!checkIsLogedIn()) { return false; } else { PreferenceManager.setDefaultValues(this, R.xml.preferences, false); mPreferences = TwitterApplication.mPref; // PreferenceManager.getDefaultSharedPreferences(this); return true; } } protected void handleLoggedOut() { if (isTaskRoot()) { showLogin(); } else { setResult(RESULT_LOGOUT); } finish(); } public TwitterDatabase getDb() { return TwitterApplication.mDb; } public Weibo getApi() { return TwitterApplication.mApi; } public SharedPreferences getPreferences() { return mPreferences; } @Override protected void onDestroy() { super.onDestroy(); } protected boolean isLoggedIn() { return getApi().isLoggedIn(); } private static final int RESULT_LOGOUT = RESULT_FIRST_USER + 1; // Retrieve interface // public ImageManager getImageManager() { // return TwitterApplication.mImageManager; // } private void _logout() { TwitterService.unschedule(BaseActivity.this); getDb().clearData(); getApi().reset(); // Clear SharedPreferences SharedPreferences.Editor editor = mPreferences.edit(); editor.clear(); editor.commit(); // TODO: 提供用户手动情况所有缓存选项 TwitterApplication.mImageLoader.getImageManager().clear(); // TODO: cancel notifications. TwitterService.unschedule(BaseActivity.this); handleLoggedOut(); } public void logout() { Dialog dialog = new AlertDialog.Builder(BaseActivity.this) .setTitle("提示").setMessage("确实要注销吗?") .setPositiveButton("确定", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { _logout(); } }).setNegativeButton("取消", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create(); dialog.show(); } protected void showLogin() { Intent intent = new Intent(this, LoginActivity.class); // TODO: might be a hack? intent.putExtra(Intent.EXTRA_INTENT, getIntent()); startActivity(intent); } protected void manageUpdateChecks() { //检查后台更新状态设置 boolean isUpdateEnabled = mPreferences.getBoolean( Preferences.CHECK_UPDATES_KEY, false); if (isUpdateEnabled) { TwitterService.schedule(this); } else if (!TwitterService.isWidgetEnabled()) { TwitterService.unschedule(this); } //检查强制竖屏设置 boolean isOrientationPortrait = mPreferences.getBoolean( Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false); if (isOrientationPortrait) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); } } // Menus. protected static final int OPTIONS_MENU_ID_LOGOUT = 1; protected static final int OPTIONS_MENU_ID_PREFERENCES = 2; protected static final int OPTIONS_MENU_ID_ABOUT = 3; protected static final int OPTIONS_MENU_ID_SEARCH = 4; protected static final int OPTIONS_MENU_ID_REPLIES = 5; protected static final int OPTIONS_MENU_ID_DM = 6; protected static final int OPTIONS_MENU_ID_TWEETS = 7; protected static final int OPTIONS_MENU_ID_TOGGLE_REPLIES = 8; protected static final int OPTIONS_MENU_ID_FOLLOW = 9; protected static final int OPTIONS_MENU_ID_UNFOLLOW = 10; protected static final int OPTIONS_MENU_ID_IMAGE_CAPTURE = 11; protected static final int OPTIONS_MENU_ID_PHOTO_LIBRARY = 12; protected static final int OPTIONS_MENU_ID_EXIT = 13; /** * 如果增加了Option Menu常量的数量,则必须重载此方法, 以保证其他人使用常量时不产生重复 * * @return 最大的Option Menu常量 */ protected int getLastOptionMenuId() { return OPTIONS_MENU_ID_EXIT; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // SubMenu submenu = // menu.addSubMenu(R.string.write_label_insert_picture); // submenu.setIcon(android.R.drawable.ic_menu_gallery); // // submenu.add(0, OPTIONS_MENU_ID_IMAGE_CAPTURE, 0, // R.string.write_label_take_a_picture); // submenu.add(0, OPTIONS_MENU_ID_PHOTO_LIBRARY, 0, // R.string.write_label_choose_a_picture); // // MenuItem item = menu.add(0, OPTIONS_MENU_ID_SEARCH, 0, // R.string.omenu_search); // item.setIcon(android.R.drawable.ic_search_category_default); // item.setAlphabeticShortcut(SearchManager.MENU_KEY); MenuItem item; item = menu.add(0, OPTIONS_MENU_ID_PREFERENCES, 0, R.string.omenu_settings); item.setIcon(android.R.drawable.ic_menu_preferences); item = menu.add(0, OPTIONS_MENU_ID_LOGOUT, 0, R.string.omenu_signout); item.setIcon(android.R.drawable.ic_menu_revert); item = menu.add(0, OPTIONS_MENU_ID_ABOUT, 0, R.string.omenu_about); item.setIcon(android.R.drawable.ic_menu_info_details); item = menu.add(0, OPTIONS_MENU_ID_EXIT, 0, R.string.omenu_exit); item.setIcon(android.R.drawable.ic_menu_rotate); return true; } protected static final int REQUEST_CODE_LAUNCH_ACTIVITY = 0; protected static final int REQUEST_CODE_PREFERENCES = 1; @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case OPTIONS_MENU_ID_LOGOUT: logout(); return true; case OPTIONS_MENU_ID_SEARCH: onSearchRequested(); return true; case OPTIONS_MENU_ID_PREFERENCES: Intent launchPreferencesIntent = new Intent().setClass(this, PreferencesActivity.class); startActivityForResult(launchPreferencesIntent, REQUEST_CODE_PREFERENCES); return true; case OPTIONS_MENU_ID_ABOUT: //AboutDialog.show(this); Intent intent = new Intent().setClass(this, AboutActivity.class); startActivity(intent); return true; case OPTIONS_MENU_ID_EXIT: exit(); return true; } return super.onOptionsItemSelected(item); } protected void exit() { TwitterService.unschedule(this); Intent i = new Intent(Intent.ACTION_MAIN); i.addCategory(Intent.CATEGORY_HOME); startActivity(i); } protected void launchActivity(Intent intent) { // TODO: probably don't need this result chaining to finish upon logout. // since the subclasses have to check in onResume. startActivityForResult(intent, REQUEST_CODE_LAUNCH_ACTIVITY); } protected void launchDefaultActivity() { Intent intent = new Intent(); intent.setClass(this, TwitterActivity.class); startActivity(intent); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_PREFERENCES && resultCode == RESULT_OK) { manageUpdateChecks(); } else if (requestCode == REQUEST_CODE_LAUNCH_ACTIVITY && resultCode == RESULT_LOGOUT) { Log.d(TAG, "Result logout."); handleLoggedOut(); } } protected boolean checkIsLogedIn() { if (!getApi().isLoggedIn()) { Log.d(TAG, "Not logged in."); handleLoggedOut(); return false; } return true; } public static boolean isTrue(Bundle bundle, String key) { return bundle != null && bundle.containsKey(key) && bundle.getBoolean(key); } }
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.ui.base; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ListView; import android.widget.ProgressBar; 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.data.Tweet; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.fanfou.IDs; import com.ch_linghu.fanfoudroid.fanfou.Status; 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.TaskManager; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.module.FlingGestureListener; import com.ch_linghu.fanfoudroid.ui.module.MyActivityFlipper; import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.ui.module.TweetCursorAdapter; import com.ch_linghu.fanfoudroid.ui.module.Widget; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.util.DebugTimer; import com.hlidskialf.android.hardware.ShakeListener; /** * TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现 */ public abstract class TwitterCursorBaseActivity extends TwitterListBaseActivity { static final String TAG = "TwitterCursorBaseActivity"; // Views. protected ListView mTweetList; protected TweetCursorAdapter mTweetAdapter; protected View mListHeader; protected View mListFooter; protected TextView loadMoreBtn; protected ProgressBar loadMoreGIF; protected TextView loadMoreBtnTop; protected ProgressBar loadMoreGIFTop; protected static int lastPosition = 0; protected ShakeListener mShaker = null; // Tasks. protected TaskManager taskManager = new TaskManager(); private GenericTask mRetrieveTask; private GenericTask mFollowersRetrieveTask; private GenericTask mGetMoreTask; private int mRetrieveCount = 0; private TaskListener mRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "RetrieveTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { mFeedback.failed("登录信息出错"); logout(); } else if (result == TaskResult.OK) { // TODO: XML处理, GC压力 SharedPreferences.Editor editor = getPreferences().edit(); editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); // TODO: 1. StatusType(DONE) ; if (mRetrieveCount >= StatusTable.MAX_ROW_NUM) { // 只有在取回的数据大于MAX时才做GC, 因为小于时可以保证数据的连续性 getDb().gc(getUserId(), getDatabaseType()); // GC } draw(); if (task == mRetrieveTask) { goTop(); } } else if (result == TaskResult.IO_ERROR) { // FIXME: bad smell if (task == mRetrieveTask) { mFeedback.failed(((RetrieveTask) task).getErrorMsg()); } else if (task == mGetMoreTask) { mFeedback.failed(((GetMoreTask) task).getErrorMsg()); } } else { // do nothing } // 刷新按钮停止旋转 loadMoreGIFTop.setVisibility(View.GONE); loadMoreGIF.setVisibility(View.GONE); // DEBUG if (TwitterApplication.DEBUG) { DebugTimer.stop(); Log.v("DEBUG", DebugTimer.getProfileAsString()); } } @Override public void onPreExecute(GenericTask task) { mRetrieveCount = 0; if (TwitterApplication.DEBUG) { DebugTimer.start(); } } @Override public void onProgressUpdate(GenericTask task, Object param) { Log.d(TAG, "onProgressUpdate"); draw(); } }; private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "FollowerRetrieve"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { SharedPreferences sp = getPreferences(); SharedPreferences.Editor editor = sp.edit(); editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); } else { // Do nothing. } } }; // Refresh data at startup if last refresh was this long ago or greater. private static final long REFRESH_THRESHOLD = 5 * 60 * 1000; // Refresh followers if last refresh was this long ago or greater. private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000; abstract protected void markAllRead(); abstract protected Cursor fetchMessages(); public abstract int getDatabaseType(); public abstract String getUserId(); public abstract String fetchMaxId(); public abstract String fetchMinId(); public abstract int addMessages(ArrayList<Tweet> tweets, boolean isUnread); public abstract List<Status> getMessageSinceId(String maxId) throws HttpException; public abstract List<Status> getMoreMessageFromId(String minId) throws HttpException; public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1; // public static final int CONTEXT_AT_ID = Menu.FIRST + 2; public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3; public static final int CONTEXT_DM_ID = Menu.FIRST + 4; public static final int CONTEXT_MORE_ID = Menu.FIRST + 5; public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6; public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7; @Override protected void setupState() { Cursor cursor; cursor = fetchMessages(); // getDb().fetchMentions(); setTitle(getActivityTitle()); startManagingCursor(cursor); mTweetList = (ListView) findViewById(R.id.tweet_list); // TODO: 需处理没有数据时的情况 Log.d("LDS", cursor.getCount() + " cursor count"); setupListHeader(true); mTweetAdapter = new TweetCursorAdapter(this, cursor); mTweetList.setAdapter(mTweetAdapter); // ? registerOnClickListener(mTweetList); } /** * 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用 */ protected void setupListHeader(boolean addFooter) { // Add Header to ListView mListHeader = View.inflate(this, R.layout.listview_header, null); mTweetList.addHeaderView(mListHeader, null, true); // Add Footer to ListView mListFooter = View.inflate(this, R.layout.listview_footer, null); mTweetList.addFooterView(mListFooter, null, true); // Find View loadMoreBtn = (TextView) findViewById(R.id.ask_for_more); loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar); loadMoreBtnTop = (TextView) findViewById(R.id.ask_for_more_header); loadMoreGIFTop = (ProgressBar) findViewById(R.id.rectangleProgressBar_header); } @Override protected void specialItemClicked(int position) { // 注意 mTweetAdapter.getCount 和 mTweetList.getCount的区别 // 前者仅包含数据的数量(不包括foot和head),后者包含foot和head // 因此在同时存在foot和head的情况下,list.count = adapter.count + 2 if (position == 0) { // 第一个Item(header) loadMoreGIFTop.setVisibility(View.VISIBLE); doRetrieve(); } else if (position == mTweetList.getCount() - 1) { // 最后一个Item(footer) loadMoreGIF.setVisibility(View.VISIBLE); doGetMore(); } } @Override protected int getLayoutId() { return R.layout.main; } @Override protected ListView getTweetList() { return mTweetList; } @Override protected TweetAdapter getTweetAdapter() { return mTweetAdapter; } @Override protected boolean useBasicMenu() { return true; } @Override protected Tweet getContextItemTweet(int position) { position = position - 1; // 因为List加了Header和footer,所以要跳过第一个以及忽略最后一个 if (position >= 0 && position < mTweetAdapter.getCount()) { Cursor cursor = (Cursor) mTweetAdapter.getItem(position); if (cursor == null) { return null; } else { return StatusTable.parseCursor(cursor); } } else { return null; } } @Override protected void updateTweet(Tweet tweet) { // TODO: updateTweet() 在哪里调用的? 目前尚只支持: // updateTweet(String tweetId, ContentValues values) // setFavorited(String tweetId, String isFavorited) // 看是否还需要增加updateTweet(Tweet tweet)方法 // 对所有相关表的对应消息都进行刷新(如果存在的话) // getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet); } @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { goTop(); // skip the header // Mark all as read. // getDb().markAllMentionsRead(); markAllRead(); boolean shouldRetrieve = false; // FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新 long lastRefreshTime = mPreferences.getLong( Preferences.LAST_TWEET_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(); } long lastFollowersRefreshTime = mPreferences.getLong( Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0); diff = nowTime - lastFollowersRefreshTime; Log.d(TAG, "Last followers refresh was " + diff + " ms ago."); // FIXME: 目前还没有对Followers列表做逻辑处理,因此暂时去除对Followers的获取。 // 未来需要实现@用户提示时,对Follower操作需要做一次review和refactoring // 现在频繁会出现主键冲突的问题。 // // Should Refresh Followers // if (diff > FOLLOWERS_REFRESH_THRESHOLD // && (mRetrieveTask == null || mRetrieveTask.getStatus() != // GenericTask.Status.RUNNING)) { // Log.d(TAG, "Refresh followers."); // doRetrieveFollowers(); // } // 手势识别 registerGestureListener(); //晃动刷新 registerShakeListener(); return true; } else { return false; } } @Override protected void onResume() { Log.d(TAG, "onResume."); if (lastPosition != 0) { mTweetList.setSelection(lastPosition); } if (mShaker != null){ mShaker.resume(); } 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 onRestoreInstanceState(Bundle bundle) { super.onRestoreInstanceState(bundle); // mTweetEdit.updateCharsRemain(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); super.onDestroy(); taskManager.cancelAll(); } @Override protected void onPause() { Log.d(TAG, "onPause."); if (mShaker != null){ mShaker.pause(); } super.onPause(); lastPosition = mTweetList.getFirstVisiblePosition(); } @Override protected void onRestart() { Log.d(TAG, "onRestart."); super.onRestart(); } @Override protected void onStart() { Log.d(TAG, "onStart."); super.onStart(); } @Override protected void onStop() { Log.d(TAG, "onStop."); super.onStop(); } // UI helpers. @Override protected String getActivityTitle() { return null; } @Override protected void adapterRefresh() { mTweetAdapter.notifyDataSetChanged(); mTweetAdapter.refresh(); } // Retrieve interface public void updateProgress(String progress) { mProgressText.setText(progress); } public void draw() { mTweetAdapter.refresh(); } public void goTop() { Log.d(TAG, "goTop."); mTweetList.setSelection(1); } private void doRetrieveFollowers() { Log.d(TAG, "Attempting followers retrieve."); if (mFollowersRetrieveTask != null && mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mFollowersRetrieveTask = new FollowersRetrieveTask(); mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener); mFollowersRetrieveTask.execute(); taskManager.addTask(mFollowersRetrieveTask); // Don't need to cancel FollowersTask (assuming it ends properly). mFollowersRetrieveTask.setCancelable(false); } } public void doRetrieve() { Log.d(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mRetrieveTask = new RetrieveTask(); mRetrieveTask.setFeedback(mFeedback); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); // Add Task to manager taskManager.addTask(mRetrieveTask); } } private class RetrieveTask extends GenericTask { private String _errorMsg; public String getErrorMsg() { return _errorMsg; } @Override protected TaskResult _doInBackground(TaskParams... params) { List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList; try { String maxId = fetchMaxId(); // getDb().fetchMaxMentionId(); statusList = getMessageSinceId(maxId); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); _errorMsg = e.getMessage(); return TaskResult.IO_ERROR; } ArrayList<Tweet> tweets = new ArrayList<Tweet>(); for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) { if (isCancelled()) { return TaskResult.CANCELLED; } tweets.add(Tweet.create(status)); if (isCancelled()) { return TaskResult.CANCELLED; } } publishProgress(SimpleFeedback.calProgressBySize(40, 20, tweets)); mRetrieveCount = addMessages(tweets, false); return TaskResult.OK; } } private class FollowersRetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { // TODO: 目前仅做新API兼容性改动,待完善Follower处理 IDs followers = getApi().getFollowersIDs(); List<String> followerIds = Arrays.asList(followers.getIDs()); getDb().syncFollowers(followerIds); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } // GET MORE TASK private class GetMoreTask extends GenericTask { private String _errorMsg; public String getErrorMsg() { return _errorMsg; } @Override protected TaskResult _doInBackground(TaskParams... params) { List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList; String minId = fetchMinId(); // getDb().fetchMaxMentionId(); if (minId == null) { return TaskResult.FAILED; } try { statusList = getMoreMessageFromId(minId); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); _errorMsg = e.getMessage(); return TaskResult.IO_ERROR; } if (statusList == null) { return TaskResult.FAILED; } ArrayList<Tweet> tweets = new ArrayList<Tweet>(); publishProgress(SimpleFeedback.calProgressBySize(40, 20, tweets)); for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) { if (isCancelled()) { return TaskResult.CANCELLED; } tweets.add(Tweet.create(status)); if (isCancelled()) { return TaskResult.CANCELLED; } } addMessages(tweets, false); // getDb().addMentions(tweets, false); return TaskResult.OK; } } public void doGetMore() { Log.d(TAG, "Attempting getMore."); if (mGetMoreTask != null && mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mGetMoreTask = new GetMoreTask(); mGetMoreTask.setFeedback(mFeedback); mGetMoreTask.setListener(mRetrieveTaskListener); mGetMoreTask.execute(); // Add Task to manager taskManager.addTask(mGetMoreTask); } } //////////////////// Gesture test ///////////////////////////////////// private static boolean useGestrue; { useGestrue = TwitterApplication.mPref.getBoolean( Preferences.USE_GESTRUE, false); if (useGestrue) { Log.v(TAG, "Using Gestrue!"); } else { Log.v(TAG, "Not Using Gestrue!"); } } //////////////////// Gesture test ///////////////////////////////////// private static boolean useShake; { useShake = TwitterApplication.mPref.getBoolean( Preferences.USE_SHAKE, false); if (useShake) { Log.v(TAG, "Using Shake to refresh!"); } else { Log.v(TAG, "Not Using Shake!"); } } protected FlingGestureListener myGestureListener = null; @Override public boolean onTouchEvent(MotionEvent event) { if (useGestrue && myGestureListener != null) { return myGestureListener.getDetector().onTouchEvent(event); } return super.onTouchEvent(event); } // use it in _onCreate private void registerGestureListener() { if (useGestrue) { myGestureListener = new FlingGestureListener(this, MyActivityFlipper.create(this)); getTweetList().setOnTouchListener(myGestureListener); } } // use it in _onCreate private void registerShakeListener() { if (useShake){ mShaker = new ShakeListener(this); mShaker.setOnShakeListener(new ShakeListener.OnShakeListener() { @Override public void onShake() { doRetrieve(); } }); } } }
Java
package com.ch_linghu.fanfoudroid.ui.base; import android.app.ListActivity; /** * TODO: 准备重构现有的几个ListActivity * * 目前几个ListActivity存在的问题是 : * 1. 因为要实现[刷新]这些功能, 父类设定了子类继承时必须要实现的方法, * 而刷新/获取其实更多的时候可以理解成是ListView的层面, 这在于讨论到底是一个"可刷新的Activity" * 还是一个拥有"可刷新的ListView"的Activity, 如果改成后者, 则只要在父类拥有一个实现了可刷新接口的ListView即可, * 而无需强制要求子类去直接实现某些方法. * 2. 父类过于专制, 比如getLayoutId()等抽象方法的存在只是为了在父类进行setContentView, 而此类方法可以下放到子类去自行实现, * 诸如此类的, 应该下放给子类更自由的空间. 理想状态为不使用抽象类. * 3. 随着功能扩展, 需要将几个不同的ListActivity子类重复的部分重新抽象到父类来, 已减少代码重复. * 4. TwitterList和UserList代码存在重复现象, 可抽象. * 5. TwitterList目前过于依赖Cursor类型的List, 而没有Array类型的抽象类. * */ public class BaseListActivity extends ListActivity { }
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. */ /** * AbstractTwitterListBaseLine用于抽象tweets List的展现 * UI基本元素要求:一个ListView用于tweet列表 * 一个ProgressText用于提示信息 */ package com.ch_linghu.fanfoudroid.ui.base; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.DmActivity; import com.ch_linghu.fanfoudroid.MentionActivity; import com.ch_linghu.fanfoudroid.ProfileActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.StatusActivity; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.WriteActivity; import com.ch_linghu.fanfoudroid.WriteDmActivity; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Tweet; 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.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.TweetAdapter; public abstract class TwitterListBaseActivity extends BaseActivity implements Refreshable { static final String TAG = "TwitterListBaseActivity"; protected TextView mProgressText; protected Feedback mFeedback; protected NavBar mNavbar; protected static final int STATE_ALL = 0; protected static final String SIS_RUNNING_KEY = "running"; // Tasks. protected GenericTask mFavTask; 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(); } } }; static final int DIALOG_WRITE_ID = 0; abstract protected int getLayoutId(); abstract protected ListView getTweetList(); abstract protected TweetAdapter getTweetAdapter(); abstract protected void setupState(); abstract protected String getActivityTitle(); abstract protected boolean useBasicMenu(); abstract protected Tweet getContextItemTweet(int position); abstract protected void updateTweet(Tweet tweet); public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1; // public static final int CONTEXT_AT_ID = Menu.FIRST + 2; public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3; public static final int CONTEXT_DM_ID = Menu.FIRST + 4; public static final int CONTEXT_MORE_ID = Menu.FIRST + 5; public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6; public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7; /** * 如果增加了Context Menu常量的数量,则必须重载此方法, * 以保证其他人使用常量时不产生重复 * @return 最大的Context Menu常量 */ protected int getLastContextMenuId(){ return CONTEXT_DEL_FAV_ID; } @Override protected boolean _onCreate(Bundle savedInstanceState){ if (super._onCreate(savedInstanceState)){ setContentView(getLayoutId()); mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); mPreferences.getInt(Preferences.TWITTER_ACTIVITY_STATE_KEY, STATE_ALL); // 提示栏 mProgressText = (TextView) findViewById(R.id.progress_text); setupState(); registerForContextMenu(getTweetList()); registerOnClickListener(getTweetList()); return true; } else { return false; } } @Override protected void onResume() { super.onResume(); checkIsLogedIn(); } @Override protected void onDestroy() { super.onDestroy(); if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { mFavTask.cancel(true); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { Log.d("FLING", "onContextItemSelected"); super.onCreateContextMenu(menu, v, menuInfo); if (useBasicMenu()){ AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; Tweet tweet = getContextItemTweet(info.position); if (tweet == null) { Log.w(TAG, "Selected item not available."); return; } menu.add(0, CONTEXT_MORE_ID, 0, tweet.screenName + getResources().getString(R.string.cmenu_user_profile_prefix)); menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply); menu.add(0, CONTEXT_RETWEET_ID, 0, R.string.cmenu_retweet); menu.add(0, CONTEXT_DM_ID, 0, R.string.cmenu_direct_message); if (tweet.favorited.equals("true")) { menu.add(0, CONTEXT_DEL_FAV_ID, 0, R.string.cmenu_del_fav); } else { menu.add(0, CONTEXT_ADD_FAV_ID, 0, R.string.cmenu_add_fav); } } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); Tweet tweet = getContextItemTweet(info.position); if (tweet == null) { Log.w(TAG, "Selected item not available."); return super.onContextItemSelected(item); } switch (item.getItemId()) { case CONTEXT_MORE_ID: launchActivity(ProfileActivity.createIntent(tweet.userId)); return true; case CONTEXT_REPLY_ID: { // TODO: this isn't quite perfect. It leaves extra empty spaces if // you perform the reply action again. Intent intent = WriteActivity.createNewReplyIntent(tweet.text, tweet.screenName, tweet.id); startActivity(intent); return true; } case CONTEXT_RETWEET_ID: Intent intent = WriteActivity.createNewRepostIntent(this, tweet.text, tweet.screenName, tweet.id); startActivity(intent); return true; case CONTEXT_DM_ID: launchActivity(WriteDmActivity.createIntent(tweet.userId)); return true; case CONTEXT_ADD_FAV_ID: doFavorite("add", tweet.id); return true; case CONTEXT_DEL_FAV_ID: doFavorite("del", tweet.id); return true; default: return super.onContextItemSelected(item); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case OPTIONS_MENU_ID_TWEETS: launchActivity(TwitterActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_REPLIES: launchActivity(MentionActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_DM: launchActivity(DmActivity.createIntent()); return true; } return super.onOptionsItemSelected(item); } protected void draw() { getTweetAdapter().refresh(); } protected void goTop() { getTweetList().setSelection(1); } protected void adapterRefresh(){ getTweetAdapter().refresh(); } // for HasFavorite interface public void doFavorite(String action, String id) { if (!TextUtils.isEmpty(id)) { if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mFavTask = new TweetCommonTask.FavoriteTask(this); mFavTask.setListener(mFavTaskListener); TaskParams params = new TaskParams(); params.put("action", action); params.put("id", id); mFavTask.execute(params); } } } public void onFavSuccess() { // updateProgress(getString(R.string.refreshing)); adapterRefresh(); } public void onFavFailure() { // updateProgress(getString(R.string.refreshing)); } protected void specialItemClicked(int position){ } protected void registerOnClickListener(ListView listView) { listView.setOnItemClickListener(new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Tweet tweet = getContextItemTweet(position); if (tweet == null) { Log.w(TAG, "Selected item not available."); specialItemClicked(position); }else{ launchActivity(StatusActivity.createIntent(tweet)); } } }); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } }
Java
package com.ch_linghu.fanfoudroid.ui.base; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.DmActivity; import com.ch_linghu.fanfoudroid.MentionActivity; import com.ch_linghu.fanfoudroid.ProfileActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.UserTimelineActivity; import com.ch_linghu.fanfoudroid.WriteActivity; import com.ch_linghu.fanfoudroid.WriteDmActivity; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.User; 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.task.TweetCommonTask; 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.TweetAdapter; public abstract class UserListBaseActivity extends BaseActivity implements Refreshable { static final String TAG = "TwitterListBaseActivity"; protected TextView mProgressText; protected NavBar mNavbar; protected Feedback mFeedback; protected static final int STATE_ALL = 0; protected static final String SIS_RUNNING_KEY = "running"; private static final String USER_ID = "userId"; // Tasks. protected GenericTask mFavTask; 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(); } } }; static final int DIALOG_WRITE_ID = 0; abstract protected int getLayoutId(); abstract protected ListView getUserList(); abstract protected TweetAdapter getUserAdapter(); abstract protected void setupState(); abstract protected String getActivityTitle(); abstract protected boolean useBasicMenu(); abstract protected User getContextItemUser(int position); abstract protected void updateTweet(Tweet tweet); protected abstract String getUserId();// 获得用户id public static final int CONTENT_PROFILE_ID = Menu.FIRST + 1; public static final int CONTENT_STATUS_ID = Menu.FIRST + 2; public static final int CONTENT_DEL_FRIEND = Menu.FIRST + 3; public static final int CONTENT_ADD_FRIEND = Menu.FIRST + 4; public static final int CONTENT_SEND_DM = Menu.FIRST + 5; public static final int CONTENT_SEND_MENTION = Menu.FIRST + 6; /** * 如果增加了Context Menu常量的数量,则必须重载此方法, 以保证其他人使用常量时不产生重复 * * @return 最大的Context Menu常量 */ // protected int getLastContextMenuId(){ // return CONTEXT_DEL_FAV_ID; // } @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)) { setContentView(getLayoutId()); mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); mPreferences.getInt(Preferences.TWITTER_ACTIVITY_STATE_KEY, STATE_ALL); mProgressText = (TextView) findViewById(R.id.progress_text); setupState(); registerForContextMenu(getUserList()); registerOnClickListener(getUserList()); return true; } else { return false; } } @Override protected void onResume() { super.onResume(); checkIsLogedIn(); } @Override protected void onDestroy() { super.onDestroy(); if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { mFavTask.cancel(true); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if (useBasicMenu()) { AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; User user = getContextItemUser(info.position); if (user == null) { Log.w(TAG, "Selected item not available."); return; } menu.add(0, CONTENT_PROFILE_ID, 0, user.screenName + getResources().getString( R.string.cmenu_user_profile_prefix)); menu.add(0, CONTENT_STATUS_ID, 0, user.screenName + getResources().getString(R.string.cmenu_user_status)); menu.add(0, CONTENT_SEND_MENTION, 0, getResources().getString(R.string.cmenu_user_send_prefix) + user.screenName + getResources().getString( R.string.cmenu_user_sendmention_suffix)); menu.add(0, CONTENT_SEND_DM, 0, getResources().getString(R.string.cmenu_user_send_prefix) + user.screenName + getResources().getString( R.string.cmenu_user_senddm_suffix)); } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); User user = getContextItemUser(info.position); if (user == null) { Log.w(TAG, "Selected item not available."); return super.onContextItemSelected(item); } switch (item.getItemId()) { case CONTENT_PROFILE_ID: launchActivity(ProfileActivity.createIntent(user.id)); return true; case CONTENT_STATUS_ID: launchActivity(UserTimelineActivity .createIntent(user.id, user.name)); return true; case CONTENT_DEL_FRIEND: delFriend(user.id); return true; case CONTENT_ADD_FRIEND: addFriend(user.id); return true; case CONTENT_SEND_MENTION: launchActivity(WriteActivity.createNewTweetIntent(String.format( "@%s ", user.screenName))); return true; case CONTENT_SEND_DM: launchActivity(WriteDmActivity.createIntent(user.id)); return true; default: return super.onContextItemSelected(item); } } /** * 取消关注 * * @param id */ private void delFriend(final String id) { Builder diaBuilder = new AlertDialog.Builder(UserListBaseActivity.this) .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(getBaseContext(), "取消关注成功", Toast.LENGTH_SHORT) .show(); } else if (result == TaskResult.FAILED) { Toast.makeText(getBaseContext(), "取消关注失败", 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(UserListBaseActivity.this) .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(getBaseContext(), "关注成功", Toast.LENGTH_SHORT) .show(); } else if (result == TaskResult.FAILED) { Toast.makeText(getBaseContext(), "关注失败", Toast.LENGTH_SHORT) .show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case OPTIONS_MENU_ID_TWEETS: launchActivity(TwitterActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_REPLIES: launchActivity(MentionActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_DM: launchActivity(DmActivity.createIntent()); return true; } return super.onOptionsItemSelected(item); } private void draw() { getUserAdapter().refresh(); } private void goTop() { getUserList().setSelection(0); } protected void adapterRefresh() { getUserAdapter().refresh(); } // for HasFavorite interface public void doFavorite(String action, String id) { if (!TextUtils.isEmpty(id)) { if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mFavTask = new TweetCommonTask.FavoriteTask(this); mFavTask.setFeedback(mFeedback); mFavTask.setListener(mFavTaskListener); TaskParams params = new TaskParams(); params.put("action", action); params.put("id", id); mFavTask.execute(params); } } } public void onFavSuccess() { // updateProgress(getString(R.string.refreshing)); adapterRefresh(); } public void onFavFailure() { // updateProgress(getString(R.string.refreshing)); } protected void specialItemClicked(int position) { } /* * TODO:单击列表项 */ protected void registerOnClickListener(ListView listView) { listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //Toast.makeText(getBaseContext(), "选择第"+position+"个列表",Toast.LENGTH_SHORT).show(); User user = getContextItemUser(position); if (user == null) { Log.w(TAG, "selected item not available"); specialItemClicked(position); } else { launchActivity(ProfileActivity.createIntent(user.id)); } } }); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } }
Java
/*** Copyright (c) 2008-2009 CommonsWare, LLC Portions (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.commonsware.cwac.sacklist; import java.util.ArrayList; import java.util.List; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; /** * Adapter that simply returns row views from a list. * * If you supply a size, you must implement newView(), to * create a required view. The adapter will then cache these * views. * * If you supply a list of views in the constructor, that * list will be used directly. If any elements in the list * are null, then newView() will be called just for those * slots. * * Subclasses may also wish to override areAllItemsEnabled() * (default: false) and isEnabled() (default: false), if some * of their rows should be selectable. * * It is assumed each view is unique, and therefore will not * get recycled. * * Note that this adapter is not designed for long lists. It * is more for screens that should behave like a list. This * is particularly useful if you combine this with other * adapters (e.g., SectionedAdapter) that might have an * arbitrary number of rows, so it all appears seamless. */ public class SackOfViewsAdapter extends BaseAdapter { private List<View> views=null; /** * Constructor creating an empty list of views, but with * a specified count. Subclasses must override newView(). */ public SackOfViewsAdapter(int count) { super(); views=new ArrayList<View>(count); for (int i=0;i<count;i++) { views.add(null); } } /** * Constructor wrapping a supplied list of views. * Subclasses must override newView() if any of the elements * in the list are null. */ public SackOfViewsAdapter(List<View> views) { super(); this.views=views; } /** * Get the data item associated with the specified * position in the data set. * @param position Position of the item whose data we want */ @Override public Object getItem(int position) { return(views.get(position)); } /** * How many items are in the data set represented by this * Adapter. */ @Override public int getCount() { return(views.size()); } /** * Returns the number of types of Views that will be * created by getView(). */ @Override public int getViewTypeCount() { return(getCount()); } /** * Get the type of View that will be created by getView() * for the specified item. * @param position Position of the item whose data we want */ @Override public int getItemViewType(int position) { return(position); } /** * Are all items in this ListAdapter enabled? If yes it * means all items are selectable and clickable. */ @Override public boolean areAllItemsEnabled() { return(false); } /** * Returns true if the item at the specified position is * not a separator. * @param position Position of the item whose data we want */ @Override public boolean isEnabled(int position) { return(false); } /** * Get a View that displays the data at the specified * position in the data set. * @param position Position of the item whose data we want * @param convertView View to recycle, if not null * @param parent ViewGroup containing the returned View */ @Override public View getView(int position, View convertView, ViewGroup parent) { View result=views.get(position); if (result==null) { result=newView(position, parent); views.set(position, result); } return(result); } /** * Get the row id associated with the specified position * in the list. * @param position Position of the item whose data we want */ @Override public long getItemId(int position) { return(position); } /** * Create a new View to go into the list at the specified * position. * @param position Position of the item whose data we want * @param parent ViewGroup containing the returned View */ protected View newView(int position, ViewGroup parent) { throw new RuntimeException("You must override newView()!"); } }
Java
/*** Copyright (c) 2008-2009 CommonsWare, LLC Portions (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.commonsware.cwac.merge; import java.util.ArrayList; import java.util.List; import android.database.DataSetObserver; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.SectionIndexer; import com.commonsware.cwac.sacklist.SackOfViewsAdapter; /** * Adapter that merges multiple child adapters and views * into a single contiguous whole. * * Adapters used as pieces within MergeAdapter must * have view type IDs monotonically increasing from 0. Ideally, * adapters also have distinct ranges for their row ids, as * returned by getItemId(). * */ public class MergeAdapter extends BaseAdapter implements SectionIndexer { private ArrayList<ListAdapter> pieces=new ArrayList<ListAdapter>(); /** * Stock constructor, simply chaining to the superclass. */ public MergeAdapter() { super(); } /** * Adds a new adapter to the roster of things to appear * in the aggregate list. * @param adapter Source for row views for this section */ public void addAdapter(ListAdapter adapter) { pieces.add(adapter); adapter.registerDataSetObserver(new CascadeDataSetObserver()); } /** * Adds a new View to the roster of things to appear * in the aggregate list. * @param view Single view to add */ public void addView(View view) { addView(view, false); } /** * Adds a new View to the roster of things to appear * in the aggregate list. * @param view Single view to add * @param enabled false if views are disabled, true if enabled */ public void addView(View view, boolean enabled) { ArrayList<View> list=new ArrayList<View>(1); list.add(view); addViews(list, enabled); } /** * Adds a list of views to the roster of things to appear * in the aggregate list. * @param views List of views to add */ public void addViews(List<View> views) { addViews(views, false); } /** * Adds a list of views to the roster of things to appear * in the aggregate list. * @param views List of views to add * @param enabled false if views are disabled, true if enabled */ public void addViews(List<View> views, boolean enabled) { if (enabled) { addAdapter(new EnabledSackAdapter(views)); } else { addAdapter(new SackOfViewsAdapter(views)); } } /** * Get the data item associated with the specified * position in the data set. * @param position Position of the item whose data we want */ @Override public Object getItem(int position) { for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { return(piece.getItem(position)); } position-=size; } return(null); } /** * Get the adapter associated with the specified * position in the data set. * @param position Position of the item whose adapter we want */ public ListAdapter getAdapter(int position) { for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { return(piece); } position-=size; } return(null); } /** * How many items are in the data set represented by this * Adapter. */ @Override public int getCount() { int total=0; for (ListAdapter piece : pieces) { total+=piece.getCount(); } return(total); } /** * Returns the number of types of Views that will be * created by getView(). */ @Override public int getViewTypeCount() { int total=0; for (ListAdapter piece : pieces) { total+=piece.getViewTypeCount(); } return(Math.max(total, 1)); // needed for setListAdapter() before content add' } /** * Get the type of View that will be created by getView() * for the specified item. * @param position Position of the item whose data we want */ @Override public int getItemViewType(int position) { int typeOffset=0; int result=-1; for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { result=typeOffset+piece.getItemViewType(position); break; } position-=size; typeOffset+=piece.getViewTypeCount(); } return(result); } /** * Are all items in this ListAdapter enabled? If yes it * means all items are selectable and clickable. */ @Override public boolean areAllItemsEnabled() { return(false); } /** * Returns true if the item at the specified position is * not a separator. * @param position Position of the item whose data we want */ @Override public boolean isEnabled(int position) { for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { return(piece.isEnabled(position)); } position-=size; } return(false); } /** * Get a View that displays the data at the specified * position in the data set. * @param position Position of the item whose data we want * @param convertView View to recycle, if not null * @param parent ViewGroup containing the returned View */ @Override public View getView(int position, View convertView, ViewGroup parent) { for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { return(piece.getView(position, convertView, parent)); } position-=size; } return(null); } /** * Get the row id associated with the specified position * in the list. * @param position Position of the item whose data we want */ @Override public long getItemId(int position) { for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { return(piece.getItemId(position)); } position-=size; } return(-1); } @Override public int getPositionForSection(int section) { int position=0; for (ListAdapter piece : pieces) { if (piece instanceof SectionIndexer) { Object[] sections=((SectionIndexer)piece).getSections(); int numSections=0; if (sections!=null) { numSections=sections.length; } if (section<numSections) { return(position+((SectionIndexer)piece).getPositionForSection(section)); } else if (sections!=null) { section-=numSections; } } position+=piece.getCount(); } return(0); } @Override public int getSectionForPosition(int position) { int section=0; for (ListAdapter piece : pieces) { int size=piece.getCount(); if (position<size) { if (piece instanceof SectionIndexer) { return(section+((SectionIndexer)piece).getSectionForPosition(position)); } return(0); } else { if (piece instanceof SectionIndexer) { Object[] sections=((SectionIndexer)piece).getSections(); if (sections!=null) { section+=sections.length; } } } position-=size; } return(0); } @Override public Object[] getSections() { ArrayList<Object> sections=new ArrayList<Object>(); for (ListAdapter piece : pieces) { if (piece instanceof SectionIndexer) { Object[] curSections=((SectionIndexer)piece).getSections(); if (curSections!=null) { for (Object section : curSections) { sections.add(section); } } } } if (sections.size()==0) { return(null); } return(sections.toArray(new Object[0])); } private static class EnabledSackAdapter extends SackOfViewsAdapter { public EnabledSackAdapter(List<View> views) { super(views); } @Override public boolean areAllItemsEnabled() { return(true); } @Override public boolean isEnabled(int position) { return(true); } } private class CascadeDataSetObserver extends DataSetObserver { @Override public void onChanged() { notifyDataSetChanged(); } @Override public void onInvalidated() { notifyDataSetInvalidated(); } } }
Java
package com.hlidskialf.android.hardware; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; public class ShakeListener implements SensorEventListener { private static final int FORCE_THRESHOLD = 350; private static final int TIME_THRESHOLD = 100; private static final int SHAKE_TIMEOUT = 500; private static final int SHAKE_DURATION = 1000; private static final int SHAKE_COUNT = 3; private SensorManager mSensorMgr; private Sensor mSensor; private float mLastX = -1.0f, mLastY = -1.0f, mLastZ = -1.0f; private long mLastTime; private OnShakeListener mShakeListener; private Context mContext; private int mShakeCount = 0; private long mLastShake; private long mLastForce; public interface OnShakeListener { public void onShake(); } public ShakeListener(Context context) { mContext = context; resume(); } public void setOnShakeListener(OnShakeListener listener) { mShakeListener = listener; } public void resume() { mSensorMgr = (SensorManager) mContext .getSystemService(Context.SENSOR_SERVICE); mSensor = mSensorMgr .getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER); if (mSensorMgr == null) { throw new UnsupportedOperationException("Sensors not supported"); } boolean supported = mSensorMgr.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_GAME); if (!supported) { mSensorMgr.unregisterListener(this, mSensor); throw new UnsupportedOperationException( "Accelerometer not supported"); } } public void pause() { if (mSensorMgr != null) { mSensorMgr.unregisterListener(this, mSensor); mSensorMgr = null; } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } @Override public void onSensorChanged(SensorEvent event) { Sensor sensor = event.sensor; float[] values = event.values; if (sensor.getType() != SensorManager.SENSOR_ACCELEROMETER) return; long now = System.currentTimeMillis(); if ((now - mLastForce) > SHAKE_TIMEOUT) { mShakeCount = 0; } if ((now - mLastTime) > TIME_THRESHOLD) { long diff = now - mLastTime; float speed = Math.abs(values[SensorManager.DATA_X] + values[SensorManager.DATA_Y] + values[SensorManager.DATA_Z] - mLastX - mLastY - mLastZ) / diff * 10000; if (speed > FORCE_THRESHOLD) { if ((++mShakeCount >= SHAKE_COUNT) && (now - mLastShake > SHAKE_DURATION)) { mLastShake = now; mShakeCount = 0; if (mShakeListener != null) { mShakeListener.onShake(); } } mLastForce = now; } mLastTime = now; mLastX = values[SensorManager.DATA_X]; mLastY = values[SensorManager.DATA_Y]; mLastZ = values[SensorManager.DATA_Z]; } } }
Java
/** * Implements a GUI for the project following the Model-View-Controller approach. * The main class is {@link kianxali.gui.Controller} */ package kianxali.gui;
Java
package kianxali.gui.views; import java.awt.Shape; import javax.swing.text.Element; import javax.swing.text.LabelView; import kianxali.decoder.Instruction; import kianxali.gui.models.ImageDocument; public class MnemonicView extends LabelView { private Instruction instruction; public MnemonicView(Element elem) { super(elem); Object inst = elem.getAttributes().getAttribute(ImageDocument.InstructionKey); if(inst instanceof Instruction) { instruction = (Instruction) inst; } } @Override public String getToolTipText(float x, float y, Shape allocation) { if(instruction != null) { return instruction.getDescription(); } else { return null; } } }
Java
package kianxali.gui.views; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JViewport; import javax.swing.SwingUtilities; import javax.swing.ToolTipManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultCaret; import javax.swing.text.DefaultStyledDocument; import javax.swing.text.Document; import javax.swing.text.Element; import org.jdesktop.swingx.JXEditorPane; import kianxali.disassembler.DataEntry; import kianxali.disassembler.Function; import kianxali.gui.Controller; import kianxali.gui.models.ImageDocument; import kianxali.gui.models.ImageEditorKit; public class ImageView extends JPanel { private static final long serialVersionUID = 1L; private final Controller controller; private final JXEditorPane editor; private final StatusView statusView; private final JScrollPane scrollPane; public ImageView(final Controller controller) { this.controller = controller; setLayout(new BorderLayout()); statusView = new StatusView(); add(statusView, BorderLayout.NORTH); editor = new JXEditorPane() { private static final long serialVersionUID = -481545877802655847L; @Override public boolean getScrollableTracksViewportWidth() { // disable line wrap, source: http://tips4java.wordpress.com/2009/01/25/no-wrap-text-pane/ return getUI().getPreferredSize(this).width <= getParent().getSize().width; } }; editor.setEditable(false); DefaultCaret caret = (DefaultCaret)editor.getCaret(); caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE); editor.setEditorKit(new ImageEditorKit()); editor.addMouseMotionListener(new MouseMotionListener() { public void mouseDragged(MouseEvent e) { } public void mouseMoved(MouseEvent e) { int index = editor.viewToModel(e.getPoint()); mouseOverIndex(index); } }); editor.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { int index = editor.viewToModel(e.getPoint()); if(SwingUtilities.isLeftMouseButton(e)) { controller.onDisassemblyLeftClick(index); } else if(SwingUtilities.isRightMouseButton(e)) { onRightClick(index, e.getPoint()); } } }); ToolTipManager.sharedInstance().registerComponent(editor); scrollPane = new JScrollPane(editor); scrollPane.getViewport().addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { onScrollChange(); } }); scrollPane.setRowHeaderView(new CrossReferenceHeader(controller, editor)); add(scrollPane, BorderLayout.CENTER); } public void setCaretPos(int offset) { editor.setCaretPosition(offset); } public void scrollTo(long memAddr) throws BadLocationException { Document doc = editor.getDocument(); if(doc instanceof ImageDocument) { JViewport viewport = (JViewport) editor.getParent(); Integer pos = ((ImageDocument) doc).getOffsetForAddress(memAddr); if(pos != null) { Rectangle rect = editor.modelToView(pos); rect.y += viewport.getExtentSize().height - rect.height; // TODO: Hack or supposed to be like this? editor.scrollRectToVisible(new Rectangle(0, 0, 0, 0)); editor.scrollRectToVisible(rect); editor.setCaretPosition(pos); } } } private void onScrollChange() { Document doc = editor.getDocument(); if(doc instanceof ImageDocument) { int scroll = scrollPane.getVerticalScrollBar().getValue(); int pos = editor.viewToModel(new Point(0, scroll)); Long addr = ((ImageDocument) doc).getAddressForOffset(pos); if(addr != null) { controller.onScrollChange(addr); } } scrollPane.getRowHeader().repaint(); } private void mouseOverIndex(int index) { Document doc = editor.getDocument(); if(index < 0 || !(doc instanceof ImageDocument)) { return; } ImageDocument imageDoc = (ImageDocument) doc; Element elem = imageDoc.getCharacterElement(index); if(elem == null) { return; } if(elem.getAttributes().getAttribute(ImageDocument.RefAddressKey) != null) { editor.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); } else { editor.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } public int getCurrentIndex() { return editor.getCaretPosition(); } public DataEntry getData(final int index) { Document doc = editor.getDocument(); if(!(doc instanceof ImageDocument)) { return null; } ImageDocument imageDoc = (ImageDocument) doc; Element elem = imageDoc.getCharacterElement(index); if(elem == null) { return null; } Object memAddrObj = elem.getAttributes().getAttribute(ImageDocument.MemAddressKey); if(!(memAddrObj instanceof Long)) { return null; } long memAddr = (Long) memAddrObj; final DataEntry data = controller.getDisassemblyData().getInfoOnExactAddress(memAddr); return data; } private void onRightClick(final int index, Point p) { boolean hasEntries = false; if(index < 0) { return; } Document doc = editor.getDocument(); if(!(doc instanceof ImageDocument)) { return; } ImageDocument imageDoc = (ImageDocument) doc; Element elem = imageDoc.getCharacterElement(index); if(elem == null) { return; } JPopupMenu menu = new JPopupMenu("Actions"); // Right clicking on mnemonic if(elem.getName() == ImageDocument.MnemonicElementName) { menu.add("Convert to NOP").addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { controller.onConvertToNOP(index); } }); hasEntries = true; } // General right clicking on something that has a memory address Object memAddrObj = elem.getAttributes().getAttribute(ImageDocument.MemAddressKey); if(memAddrObj instanceof Long) { long memAddr = (Long) memAddrObj; final DataEntry data = controller.getDisassemblyData().getInfoOnExactAddress(memAddr); if(data != null) { // Function renaming if(data.getStartFunction() != null) { final Function fun = data.getStartFunction(); menu.add("Rename " + fun.getName()).addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String newName = JOptionPane.showInputDialog("New name for " + fun.getName() + ": "); if(newName != null) { controller.onFunctionRenameReq(fun, newName); } } }); hasEntries = true; } // Commenting menu.add("Change Comment").addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { controller.onCommentChangeReq(data); } }); hasEntries = true; } } if(hasEntries) { menu.show(editor, p.x, p.y); } } public StatusView getStatusView() { return statusView; } public ImageDocument getDocument() { if(editor.getDocument() instanceof ImageDocument) { return (ImageDocument) editor.getDocument(); } else { return null; } } public void setDocument(ImageDocument document) { if(document != null) { editor.setDocument(document); } else { editor.setDocument(new DefaultStyledDocument()); } editor.getCaret().setVisible(true); } }
Java
package kianxali.gui.views; import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.DefaultListCellRenderer; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; import org.jdesktop.swingx.JXList; import kianxali.decoder.Data; import kianxali.gui.Controller; import kianxali.gui.models.StringList; public class StringListView extends JPanel { private static final long serialVersionUID = 1L; private final Controller controller; private final JXList list; public StringListView(Controller controller) { this.controller = controller; this.list = new JXList(); list.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if(e.getClickCount() == 2) { int index = list.locationToIndex(e.getPoint()); onDoubleClick(index); } } }); list.setCellRenderer(new Renderer()); setLayout(new BorderLayout()); add(new JScrollPane(list), BorderLayout.CENTER); } public void setModel(StringList model) { list.setModel(model); } private void onDoubleClick(int index) { Data data = (Data) list.getModel().getElementAt(index); controller.onStringDoubleClicked(data); } private class Renderer implements ListCellRenderer<Data> { private final DefaultListCellRenderer delegate; public Renderer() { this.delegate = new DefaultListCellRenderer(); } @Override public Component getListCellRendererComponent(JList<? extends Data> l, Data value, int index, boolean isSelected, boolean cellHasFocus) { String str = (String) value.getRawContent(); return delegate.getListCellRendererComponent(l, str, index, isSelected, cellHasFocus); } } }
Java
package kianxali.gui.views; import java.awt.BorderLayout; import java.awt.Font; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.SwingUtilities; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.MutableAttributeSet; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import kianxali.gui.Controller; import kianxali.util.LogFormatter; public class LogView extends JPanel { private static final long serialVersionUID = 1L; private final JTextPane logPane; private final MutableAttributeSet logStyle; public LogView(Controller controller) { setLayout(new BorderLayout()); this.logStyle = new SimpleAttributeSet(); StyleConstants.setFontFamily(logStyle, Font.MONOSPACED); this.logPane = new JTextPane(); logPane.setEditable(false); add(new JScrollPane(logPane), BorderLayout.CENTER); } public Handler getLogHandler() { Handler res = new Handler() { @Override public void flush() { } @Override public void close() { } @Override public void publish(LogRecord record) { if(record.getLevel().intValue() < getLevel().intValue()) { return; } final String msg = getFormatter().format(record); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { addLine(msg); } }); } }; res.setFormatter(new LogFormatter()); res.setLevel(Level.INFO); return res; } public void addLine(String line) { try { Document doc = logPane.getDocument(); doc.insertString(doc.getLength(), line, logStyle); } catch(BadLocationException e) { // can't use Logger here because this would call addLine again System.err.println("Can't add text to log: " + e.getMessage()); } } public void clear() { try { Document doc = logPane.getDocument(); doc.remove(0, doc.getLength()); } catch(BadLocationException e) { // don't care } } }
Java
package kianxali.gui.views; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Stroke; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.awt.geom.Line2D; import java.awt.geom.Rectangle2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.TreeSet; import java.util.logging.Logger; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.JTextComponent; import javax.swing.text.Utilities; import kianxali.decoder.DecodedEntity; import kianxali.decoder.Instruction; import kianxali.disassembler.DataEntry; import kianxali.disassembler.DisassemblyData; import kianxali.gui.Controller; import kianxali.gui.models.ImageDocument; public class CrossReferenceHeader extends JPanel implements DocumentListener { private static final long serialVersionUID = 1L; private static final Logger LOG = Logger.getLogger("kianxali.gui.views"); private static final Color[] DISTANT_COLORS = { Color.GREEN, Color.ORANGE, Color.YELLOW, Color.RED, Color.BLUE, Color.BLACK, Color.WHITE, Color.CYAN, Color.MAGENTA, Color.PINK}; private final Map<Line2D, LineEntry> visibleLines; private final Controller controller; private final JTextComponent component; private final Stroke thickStroke = new BasicStroke(3.5f); private final Stroke thinStroke = new BasicStroke(1.5f); private int lastHeight; private ImageDocument imageDoc; private boolean isHighlighting; private class LineEntry implements Comparable<LineEntry> { long fromAddr, toAddr; int fromY, toY, shiftX; public LineEntry(int from, int to) { this.fromY = from; this.toY = to; } @Override public int compareTo(LineEntry o) { if(fromY != o.fromY) { return Integer.compare(fromY, o.fromY); } else { return Integer.compare(toY, o.toY); } } } public CrossReferenceHeader(final Controller controller, final JTextComponent component) { this.visibleLines = new HashMap<>(); this.controller = controller; this.component = component; // not adding the document listener yet because the initial document is never an ImageDocument component.addPropertyChangeListener("document", new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { Document doc = component.getDocument(); if(doc instanceof ImageDocument) { imageDoc = (ImageDocument) doc; imageDoc.addDocumentListener(CrossReferenceHeader.this); } else { imageDoc = null; } documentChanged(); } }); // without this height, weird painting problems will occur :-/ // but due to clipping, it shouldn't be too bad setPreferredSize(new Dimension(50, Integer.MAX_VALUE)); addMouseMotionListener(new MouseMotionListener() { public void mouseDragged(MouseEvent e) { } @Override public void mouseMoved(MouseEvent e) { Point p = e.getPoint(); Line2D line = findLine(p); if(line != null) { isHighlighting = true; repaint(); } else if(isHighlighting) { isHighlighting = false; repaint(); } } }); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { Point p = e.getPoint(); Line2D line = findLine(p); if(line != null) { LineEntry entry = visibleLines.get(line); if(entry != null) { controller.onGotoRequest(entry.fromAddr); } } } }); } private Line2D findLine(Point p) { for(Line2D line : visibleLines.keySet()) { if(line.intersects(new Rectangle2D.Float(p.x - 1, p.y - 1, 2, 2))) { return line; } } return null; } private void documentChanged() { SwingUtilities.invokeLater(new Runnable() { public void run() { try { int endPos = component.getDocument().getLength(); Rectangle rect = component.modelToView(endPos); if(rect != null && rect.y != lastHeight) { repaint(); lastHeight = rect.y; } } catch(BadLocationException e) { // doesn't matter } } }); } @Override protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); super.paintComponent(g2); visibleLines.clear(); if(imageDoc == null) { return; } // get visible addresses Rectangle clip = g.getClipBounds(); int startOffset = component.viewToModel(new Point(0, clip.y)); int endOffset = component.viewToModel(new Point(0, clip.y + clip.height)); g2.setColor(Color.GRAY); g2.fillRect(clip.x, clip.y, clip.width, clip.height); NavigableSet<LineEntry> lineEntries = buildReferences(startOffset, endOffset); shiftReferences(lineEntries); for(LineEntry entry : lineEntries) { int x = clip.width - 8 - entry.shiftX * 4; visibleLines.put(new Line2D.Float(x, entry.fromY, clip.width, entry.fromY), entry); visibleLines.put(new Line2D.Float(x, entry.fromY, x, entry.toY), entry); visibleLines.put(new Line2D.Float(x, entry.toY, clip.width, entry.toY), entry); visibleLines.put(new Line2D.Float(clip.width - 4, entry.toY - 4, clip.width + 4, entry.toY), entry); visibleLines.put(new Line2D.Float(clip.width - 4, entry.toY + 4, clip.width + 4, entry.toY), entry); } // check which lines must be highlighted LineEntry highlight = null; Point mouse = getMousePosition(); if(mouse != null) { Line2D line = findLine(mouse); if(line != null) { highlight = visibleLines.get(line); } } for(Line2D line : visibleLines.keySet()) { LineEntry entry = visibleLines.get(line); if(highlight == entry) { g2.setStroke(thickStroke); } else { g2.setStroke(thinStroke); } g2.setColor(DISTANT_COLORS[entry.shiftX % DISTANT_COLORS.length]); g2.draw(line); } } private void shiftReferences(NavigableSet<LineEntry> references) { for(LineEntry entry : references) { // count the number of lines that must be skipped for(LineEntry other : references) { if(other == entry) { continue; } if(other.fromY <= entry.toY && other.fromY >= entry.fromY) { entry.shiftX++; } } } } // from screen y position to list of other screen y positions private NavigableSet<LineEntry> buildReferences(int startOffset, int endOffset) { NavigableSet<LineEntry> res = new TreeSet<>(); DisassemblyData data = controller.getDisassemblyData(); if(data == null) { return res; } int curOffset = startOffset; while(curOffset <= endOffset) { try { Long memAddr = imageDoc.getAddressForOffset(curOffset); if(memAddr == null) { break; } int thisY = getYPosition(curOffset); // add to-references DecodedEntity srcEntity = data.getEntityOnExactAddress(memAddr); if(srcEntity instanceof Instruction) { Instruction inst = (Instruction) srcEntity; List<Long> branchAddrs = inst.getBranchAddresses(); if(!branchAddrs.isEmpty() && !inst.isFunctionCall()) { for(Long branchAddr : inst.getBranchAddresses()) { if(!controller.getImageFile().isCodeAddress(branchAddr)) { continue; } int toY = getYPosition(imageDoc.getOffsetForAddress(branchAddr)); LineEntry line = new LineEntry(thisY, toY); line.fromAddr = memAddr; line.toAddr = branchAddr; res.add(line); } } } // add from-references DataEntry entry = data.getInfoOnExactAddress(memAddr); if(entry != null && entry.getEntity() instanceof Instruction) { for(DataEntry fromEntry : entry.getReferences().keySet()) { if(fromEntry.getEntity() instanceof Instruction) { Instruction inst = (Instruction) fromEntry.getEntity(); if(!inst.isFunctionCall()) { int fromY = getYPosition(imageDoc.getOffsetForAddress(fromEntry.getAddress())); LineEntry line = new LineEntry(fromY, thisY); line.fromAddr = fromEntry.getAddress(); line.toAddr = memAddr; res.add(line); } } } } // determine next model position int rowEnd = Utilities.getRowEnd(component, curOffset); if(rowEnd == -1) { break; } else { curOffset = rowEnd + 1; } } catch(BadLocationException e) { LOG.warning("Invalid location: " + curOffset); break; } } // filter double entries for(Iterator<LineEntry> it = res.iterator(); it.hasNext();) { LineEntry entry = it.next(); boolean remove = false; for(LineEntry otherEntry : res.tailSet(entry, false)) { if(otherEntry.fromAddr == entry.fromAddr && otherEntry.toAddr == entry.toAddr) { remove = true; break; } } if(remove) { it.remove(); } } return res; } private int getYPosition(int offset) throws BadLocationException { Rectangle rect = component.modelToView(offset); return rect.y + rect.height / 2; } @Override public void insertUpdate(DocumentEvent e) { documentChanged(); } @Override public void removeUpdate(DocumentEvent e) { documentChanged(); } @Override public void changedUpdate(DocumentEvent e) { documentChanged(); } }
Java
package kianxali.gui.views; import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JEditorPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import jsyntaxpane.DefaultSyntaxKit; import kianxali.gui.Controller; public class ScriptView extends JPanel { private static final long serialVersionUID = 1L; private final Controller controller; private final JEditorPane editor; public ScriptView(Controller ctrl) { this.controller = ctrl; DefaultSyntaxKit.initKit(); // text/ruby etc. to editors setLayout(new BorderLayout()); this.editor = new JEditorPane(); JScrollPane editScroll = new JScrollPane(editor); editor.setContentType("text/ruby"); editor.setText("# Enter your Ruby code here\n" + "puts 'Hello, Kianxali'\n"); add(editScroll, BorderLayout.CENTER); JButton runButton = new JButton("Run Script"); runButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { controller.onRunScriptRequest(); } }); add(runButton, BorderLayout.SOUTH); } public String getScript() { return editor.getText(); } }
Java
package kianxali.gui.views; import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.DefaultListCellRenderer; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.ListCellRenderer; import org.jdesktop.swingx.JXList; import kianxali.disassembler.Function; import kianxali.gui.Controller; import kianxali.gui.models.FunctionList; public class FunctionListView extends JPanel { private static final long serialVersionUID = 1L; private final JXList list; private final Controller controller; public FunctionListView(Controller controller) { this.controller = controller; this.list = new JXList(); list.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if(e.getClickCount() == 2) { int index = list.locationToIndex(e.getPoint()); onDoubleClick(index); } } }); list.setCellRenderer(new Renderer()); setLayout(new BorderLayout()); add(new JScrollPane(list), BorderLayout.CENTER); } public void setModel(FunctionList funListModel) { list.setModel(funListModel); } private void onDoubleClick(int index) { Function fun = (Function) list.getModel().getElementAt(index); controller.onFunctionDoubleClick(fun); } private class Renderer implements ListCellRenderer<Function> { private final DefaultListCellRenderer delegate; public Renderer() { this.delegate = new DefaultListCellRenderer(); } @Override public Component getListCellRendererComponent(JList<? extends Function> l, Function value, int index, boolean isSelected, boolean cellHasFocus) { String str = value.getName(); return delegate.getListCellRendererComponent(l, str, index, isSelected, cellHasFocus); } } }
Java
package kianxali.gui.views; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.border.BevelBorder; public class StatusView extends JComponent { private static final long serialVersionUID = 1L; private static final int NUM_STRIPES = 500; private enum DecodeType { UNKNOWN, CODE, DATA }; private final DecodeType[] decodeStatus; private long dataLength; private int cursorIndex; public StatusView() { this.decodeStatus = new DecodeType[NUM_STRIPES + 1]; initNewData(0); setMinimumSize(new Dimension(0, 25)); setPreferredSize(getMinimumSize()); setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED)); } public void initNewData(long fileSize) { this.dataLength = fileSize; for(int i = 0; i < NUM_STRIPES; i++) { decodeStatus[i] = DecodeType.UNKNOWN; } } private void setType(int index, DecodeType type) { DecodeType old = decodeStatus[index]; if(old != type) { decodeStatus[index] = type; repaint(); } } public void onDiscoverCode(long offset, long length) { for(long o = offset; o < offset + length; o++) { int index = (int) (o * NUM_STRIPES / dataLength); setType(index, DecodeType.CODE); } } public void onDiscoverData(long offset, long length) { for(long o = offset; o < offset + length; o++) { int index = (int) (o * NUM_STRIPES / dataLength); setType(index, DecodeType.DATA); } } public void setCursorAddress(long offset) { int index = (int) (offset * NUM_STRIPES / dataLength); cursorIndex = index; repaint(); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); int stripeWidth = (int) Math.max(1, Math.floor((double) getWidth() / NUM_STRIPES)); int stripeHeight = getHeight(); int x = 0; for(int i = 0; i < NUM_STRIPES; i++) { switch(decodeStatus[i]) { case CODE: g.setColor(Color.blue); break; case DATA: g.setColor(Color.yellow); break; default: g.setColor(Color.black); } g.fillRect(x, 0, stripeWidth, stripeHeight); if(i == cursorIndex) { g.setColor(Color.green); g.fillRect(x, 0, 2, stripeHeight); } x += stripeWidth; } } }
Java
package kianxali.gui.views; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Event; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.util.logging.Logger; import javax.swing.JDesktopPane; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JTabbedPane; import javax.swing.KeyStroke; import javax.swing.UIManager; import kianxali.disassembler.DataEntry; import kianxali.gui.Controller; public class KianxaliGUI extends JFrame { private static final Logger LOG = Logger.getLogger("kianxali.gui"); private static final long serialVersionUID = 1L; private final JDesktopPane desktop; private final ImageView imageView; private final FunctionListView functionView; private final StringListView stringView; private final ScriptView scriptView; private final LogView logView; private final Controller controller; public KianxaliGUI(Controller controller) { super("Kianxali"); this.controller = controller; desktop = new JDesktopPane(); add(desktop); setDefaultCloseOperation(EXIT_ON_CLOSE); setPreferredSize(new Dimension(1120, 730)); setupLookAndFeel(); setupMenu(); JTabbedPane tabPane = new JTabbedPane(); functionView = new FunctionListView(controller); tabPane.addTab("Functions", functionView); stringView = new StringListView(controller); tabPane.addTab("Strings", stringView); scriptView = new ScriptView(controller); tabPane.addTab("Script", scriptView); JInternalFrame functionFrame = new JInternalFrame("Entities", true, false, true, true); functionFrame.setLocation(new Point(0, 0)); functionFrame.setSize(new Dimension(300, 680)); functionFrame.add(tabPane); functionFrame.setVisible(true); desktop.add(functionFrame); JInternalFrame imageFrame = new JInternalFrame("Disassembly", true, false, true, true); imageFrame.setLayout(new BorderLayout()); imageFrame.setLocation(new Point(300, 0)); imageFrame.setSize(new Dimension(800, 480)); imageView = new ImageView(controller); imageFrame.add(imageView, BorderLayout.CENTER); imageFrame.setVisible(true); desktop.add(imageFrame); JInternalFrame logFrame = new JInternalFrame("Log", true, false, true, true); logFrame.setLayout(new BorderLayout()); logFrame.setLocation(new Point(300, 480)); logFrame.setSize(new Dimension(800, 200)); logView = new LogView(controller); logFrame.add(logView, BorderLayout.CENTER); logFrame.setVisible(true); desktop.add(logFrame); pack(); } private void setupLookAndFeel() { if(System.getProperty("os.name").equals("Mac OS X")) { System.setProperty("apple.laf.useScreenMenuBar", "true"); } try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch(Exception e) { // doesn't matter, just use default laf LOG.info("Couldn't set system look and feel"); } } private void setupMenu() { JMenuBar menuBar = new JMenuBar(); // File menu JMenu fileMenu = new JMenu("File"); JMenuItem fileOpen = new JMenuItem("Open", 'O'); fileOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, Event.CTRL_MASK)); fileOpen.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { controller.onOpenFileRequest(); } }); fileMenu.add(fileOpen); JMenuItem fileSave = new JMenuItem("Save patched version"); fileSave.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { controller.onSavePatchedRequest(); } }); fileMenu.add(fileSave); JMenuItem exit = new JMenuItem("Exit"); exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { controller.onExitRequest(); } }); fileMenu.add(exit); // Edit menu JMenu editMenu = new JMenu("Edit"); JMenuItem gotoAddr = new JMenuItem("Goto location"); gotoAddr.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String where = JOptionPane.showInputDialog("Goto where (hex mem address)?"); if(where != null) { controller.onGotoRequest(where); } } }); gotoAddr.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, Event.CTRL_MASK)); editMenu.add(gotoAddr); JMenuItem changeComment = new JMenuItem("Change comment"); changeComment.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { final DataEntry data = controller.getCurrentData(); controller.onCommentChangeReq(data); } }); changeComment.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_SEMICOLON, 0)); editMenu.add(changeComment); JMenuItem clearLog = new JMenuItem("Clear log"); clearLog.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { controller.onClearLogRequest(); } }); editMenu.add(clearLog); JMenu helpMenu = new JMenu("Help"); JMenuItem about = new JMenuItem("About"); about.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(KianxaliGUI.this, "<html>Kianxali<br>&copy; 2014 by Folke Will</html>", "About Kianxali", JOptionPane.INFORMATION_MESSAGE); } }); helpMenu.add(about); menuBar.add(fileMenu); menuBar.add(editMenu); menuBar.add(helpMenu); setJMenuBar(menuBar); } public void showError(String caption, String message) { JOptionPane.showMessageDialog(this, message, caption, JOptionPane.ERROR_MESSAGE); } public void showFileOpenDialog() { JFileChooser chooser = new JFileChooser("./"); int res = chooser.showOpenDialog(this); if(res == JFileChooser.APPROVE_OPTION) { controller.onFileOpened(chooser.getSelectedFile().toPath()); } } public void showSavePatchedDialog() { JFileChooser chooser = new JFileChooser("./"); int res = chooser.showSaveDialog(this); if(res == JFileChooser.APPROVE_OPTION) { controller.onPatchedSave(chooser.getSelectedFile().toPath()); } } public ImageView getImageView() { return imageView; } public ScriptView getScriptView() { return scriptView; } public FunctionListView getFunctionListView() { return functionView; } public StringListView getStringListView() { return stringView; } public LogView getLogView() { return logView; } }
Java
package kianxali.gui; import java.io.IOException; import java.io.Writer; import java.nio.file.Path; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import javax.swing.text.BadLocationException; import javax.swing.text.Element; import kianxali.decoder.Data; import kianxali.decoder.DecodedEntity; import kianxali.decoder.Instruction; import kianxali.disassembler.DataEntry; import kianxali.disassembler.DataListener; import kianxali.disassembler.Disassembler; import kianxali.disassembler.DisassemblyData; import kianxali.disassembler.DisassemblyListener; import kianxali.disassembler.Function; import kianxali.gui.models.FunctionList; import kianxali.gui.models.ImageDocument; import kianxali.gui.models.StringList; import kianxali.gui.views.KianxaliGUI; import kianxali.gui.views.StatusView; import kianxali.loader.ByteSequence; import kianxali.loader.ImageFile; import kianxali.loader.elf.ELFFile; import kianxali.loader.mach_o.FatFile; import kianxali.loader.mach_o.MachOFile; import kianxali.loader.pe.PEFile; import kianxali.scripting.ScriptManager; import kianxali.util.OutputFormatter; /** * The controller creates the GUI and receives events from the views to change the models * and vice-versa. * @author fwi * */ public class Controller implements DisassemblyListener, DataListener { private static final Logger LOG = Logger.getLogger("kianxali.gui.controller"); private ImageDocument imageDoc; private Disassembler disassembler; private DisassemblyData disassemblyData; private long beginDisassembleTime; private ImageFile imageFile; private FunctionList functionList; private StringList stringList; private final OutputFormatter formatter; private KianxaliGUI gui; private final ScriptManager scripts; private boolean initialAnalyzeDone; /** * Creates a new controller. */ public Controller() { this.formatter = new OutputFormatter(); this.scripts = new ScriptManager(this); formatter.setIncludeRawBytes(true); } /** * Creates and shows the GUI for this controller */ public void showGUI() { gui = new KianxaliGUI(this); gui.setLocationRelativeTo(null); gui.setVisible(true); Logger.getLogger("kianxali").addHandler(gui.getLogView().getLogHandler()); } public void onOpenFileRequest() { gui.showFileOpenDialog(); } public void onSavePatchedRequest() { if(imageFile != null) { gui.showSavePatchedDialog(); } else { gui.showError("Nothing to patch", "No image loaded"); } } private void loadPEFile(Path path) { LOG.fine("Loading as PE file"); try { imageFile = new PEFile(path); } catch(Exception e) { LOG.log(Level.SEVERE, "Invalid PE file: " + e.getMessage(), e); showError("Invalid PE file: " + e.getMessage()); } } private void loadMachOFile(Path path) { LOG.fine("Loading as Mach-O file"); try { imageFile = new MachOFile(path, 0); } catch(Exception e) { LOG.log(Level.SEVERE, "Invalid Mach-O file: " + e.getMessage(), e); showError("Invalid Mach-O file: " + e.getMessage()); return; } } private void loadFatFile(Path path) { // a fat file contains multiple mach headers for different architectures, let user choose LOG.fine("Loading as fat file"); try { FatFile fatFile = new FatFile(path); Map<String, Long> archTypes = fatFile.getArchitectures(); Object[] arches = new Object[archTypes.size()]; int i = 0; for(String arch : archTypes.keySet()) { arches[i++] = arch; } Object arch = JOptionPane.showInputDialog(gui, "Multiple architectures found in fat file.\nWhich one should be analyzed?", "Fat file detected", JOptionPane.PLAIN_MESSAGE, null, arches, arches[0]); if(arch == null) { return; } long offset = archTypes.get(arch); imageFile = new MachOFile(path, offset); } catch(Exception e) { LOG.log(Level.SEVERE, "Invalid Mach-O file: " + e.getMessage(), e); showError("Invalid Mach-O file: " + e.getMessage()); return; } } private void loadELFFile(Path path) { LOG.fine("Loading as ELF file"); try { imageFile = new ELFFile(path); } catch(Exception e) { LOG.log(Level.SEVERE, "Invalid ELF file: " + e.getMessage(), e); showError("Invalid ELF file: " + e.getMessage()); return; } } public void onFileOpened(Path path) { try { ImageFile old = imageFile; if(PEFile.isPEFile(path)) { loadPEFile(path); } else if(MachOFile.isMachOFile(path)) { loadMachOFile(path); } else if(FatFile.isFatFile(path)) { loadFatFile(path); } else if(ELFFile.isELFFile(path)) { loadELFFile(path); } else { showError("<html>Unknown file type.<br>Supported are: <ul><li>PE (Windows .exe)</li><li>ELF (Unix, Linux)</li><li>MachO (OS X)</li><li>Fat MachO (OS X)</li></ul></html>"); } if(imageFile == old) { return; } initialAnalyzeDone = false; // reset data structures and GUI if another file was previously loaded if(functionList != null) { functionList.clear(); } if(stringList != null) { stringList.clear(); } gui.getImageView().setDocument(null); gui.getImageView().getStatusView().initNewData(imageFile.getFileSize()); imageDoc = new ImageDocument(formatter); functionList = new FunctionList(); stringList = new StringList(); disassemblyData = new DisassemblyData(); disassemblyData.addListener(this); disassemblyData.addListener(functionList); disassemblyData.addListener(stringList); disassembler = new Disassembler(imageFile, disassemblyData); disassembler.addListener(this); formatter.setAddressNameResolve(disassembler); disassembler.startAnalyzer(); } catch(Exception e) { LOG.warning("Couldn't load image: " + e.getMessage()); e.printStackTrace(); gui.showError("Couldn't load file", "Error loading file: " + e.getMessage()); } } public void onScrollChange(long memAddr) { if(imageFile.isValidAddress(memAddr)) { long offset = imageFile.toFileAddress(memAddr); gui.getImageView().getStatusView().setCursorAddress(offset); } } @Override public void onAnalyzeStart() { LOG.info("Please wait while the file is being analyzed..."); beginDisassembleTime = System.currentTimeMillis(); } @Override public void onAnalyzeChange(final long memAddr, final DataEntry entry) { if(gui.getImageView().getDocument() == imageDoc && !SwingUtilities.isEventDispatchThread()) { // if the document is visible already, do it in the EDT // TODO: invokeAndWait deadlocks because this causes the cross references to repaint, // requiring lock to disassemblydata which is held by disassembler -> data.updateEntity SwingUtilities.invokeLater(new Runnable() { @Override public void run() { changeAnalyzeRaw(memAddr, entry); } }); } else { // not visible or already in EDT: edit directly changeAnalyzeRaw(memAddr, entry); } } private void changeAnalyzeRaw(long memAddr, DataEntry entry) { // entry can be null if an entry was deleted try { imageDoc.updateDataEntry(memAddr, entry); } catch(Exception e) { // this can fail if the error happens when generating the string representation after decoding String rawString = "<no opcode>"; if(entry.getEntity() instanceof Instruction) { Instruction inst = (Instruction) entry.getEntity(); short[] rawOpcode = inst.getRawBytes(); rawString = OutputFormatter.formatByteString(rawOpcode); } LOG.log(Level.WARNING, String.format("Couldn't convert instruction to string at %08X: %s (%s)", memAddr, e.getMessage(), rawString)); e.printStackTrace(); } // update status view if(entry != null && entry.getEntity() != null) { StatusView sv = gui.getImageView().getStatusView(); long offset = imageFile.toFileAddress(memAddr); if(entry.getEntity() instanceof Instruction) { sv.onDiscoverCode(offset, entry.getEntity().getSize()); } else if(entry.getEntity() instanceof Data) { sv.onDiscoverData(offset, entry.getEntity().getSize()); } } } @Override public void onAnalyzeError(long memAddr, String reason) { LOG.warning(String.format("Analyze error at location %X: %s", memAddr, reason)); } @Override public void onAnalyzeStop() { double duration = (System.currentTimeMillis() - beginDisassembleTime) / 1000.0; LOG.info(String.format( "Analysis finished after %.2f seconds, got %d entities", duration, disassemblyData.getEntryCount()) ); // only perform the following steps on the first run, i.e. not when a script calls reanalyze etc. if(initialAnalyzeDone) { return; } SwingUtilities.invokeLater(new Runnable() { @Override public void run() { gui.getImageView().setDocument(imageDoc); try { gui.getImageView().scrollTo(imageFile.getCodeEntryPointMem()); } catch(BadLocationException e) { // ignore if scrolling didn't work } gui.getFunctionListView().setModel(functionList); gui.getStringListView().setModel(stringList); } }); initialAnalyzeDone = true; } public void onFunctionDoubleClick(Function fun) { try { gui.getImageView().scrollTo(fun.getStartAddress()); } catch(BadLocationException e) { LOG.warning("Invalid scroll location when double clicking function"); } } public void onStringDoubleClicked(Data data) { try { gui.getImageView().scrollTo(data.getMemAddress()); } catch(BadLocationException e) { LOG.warning("Invalid scroll location when double clicking string"); } } public void onDisassemblyLeftClick(int index) { if(index < 0 || imageDoc == null) { return; } Element elem = imageDoc.getCharacterElement(index); if(elem == null) { return; } // for now, only handle left clicks on references if(elem.getName() != ImageDocument.ReferenceElementName) { return; } Object ref = elem.getAttributes().getAttribute(ImageDocument.RefAddressKey); if(ref instanceof Long) { long refAddr = (Long) ref; try { gui.getImageView().scrollTo(refAddr); } catch(BadLocationException e) { LOG.warning("Invalid scroll location when left clicking reference"); } } } public void onConvertToNOP(int index) { Long addr = imageDoc.getAddressForOffset(index); if(addr == null) { return; } DecodedEntity entity = disassemblyData.getEntityOnExactAddress(addr); if(!(entity instanceof Instruction)) { return; } gui.getImageView().setCaretPos(index); Instruction inst = (Instruction) entity; ByteSequence seq = imageFile.getByteSequence(addr, true); for(int i = 0; i < inst.getSize(); i++) { // TODO: 0x90 is x86 only seq.patchByte(imageFile.toFileAddress(addr + i), (byte) 0x90); } seq.unlock(); disassembler.reanalyze(inst.getMemAddress()); } public void onPatchedSave(Path path) { ByteSequence seq = imageFile.getByteSequence(imageFile.getCodeEntryPointMem(), true); try { seq.savePatched(path); } catch(IOException e) { gui.showError("Couldn't save file", e.getMessage()); } finally { seq.unlock(); } } public void onRunScriptRequest() { String script = gui.getScriptView().getScript(); scripts.runScript(script); } public Writer getLogWindowWriter() { return new Writer() { @Override public void write(char[] cbuf, int off, int len) throws IOException { String msg = new String(cbuf, off, len); gui.getLogView().addLine(msg); } @Override public void flush() throws IOException { } @Override public void close() throws IOException { } }; } public void showError(String msg) { gui.showError("Error", msg); } public DisassemblyData getDisassemblyData() { return disassemblyData; } public ImageFile getImageFile() { return imageFile; } public Disassembler getDisassembler() { return disassembler; } public DataEntry getData(final int index) { return gui.getImageView().getData(index); } public DataEntry getCurrentData() { return getData(gui.getImageView().getCurrentIndex()); } public void onFunctionRenameReq(Function fun, String newName) { if(newName.length() == 0) { showError("Function name cannot be empty"); return; } fun.setName(newName); } public void onCommentChangeReq(DataEntry data, String comment) { disassemblyData.insertComment(data.getAddress(), comment); } public void onCommentChangeReq(DataEntry data) { String comment = JOptionPane.showInputDialog("Comment: ", data.getComment()); if(comment != null) { onCommentChangeReq(data, comment); } } public void onGotoRequest(String where) { if(imageFile == null) { showError("No image file loaded"); return; } try { long addr = Long.parseLong(where, 16); gui.getImageView().scrollTo(addr); } catch(Exception e) { showError("Invalid address: " + e.getMessage()); } } public void onGotoRequest(long addr) { try { gui.getImageView().scrollTo(addr); } catch(Exception e) { showError("Invalid address: " + e.getMessage()); } } public void onExitRequest() { gui.dispose(); } public void onClearLogRequest() { gui.getLogView().clear(); } }
Java
package kianxali.gui.models; import java.util.NavigableSet; import java.util.TreeSet; import javax.swing.AbstractListModel; import javax.swing.SwingUtilities; import kianxali.decoder.Data; import kianxali.decoder.Data.DataType; import kianxali.disassembler.DataEntry; import kianxali.disassembler.DataListener; public class StringList extends AbstractListModel<Data> implements DataListener { private static final long serialVersionUID = 1L; private final NavigableSet<StringEntry> strings; private class StringEntry implements Comparable<StringEntry> { Data data; long address; public StringEntry(long addr) { this.address = addr; } public StringEntry(long addr, Data data) { this.address = addr; this.data = data; } @Override public int compareTo(StringEntry o) { return Long.compare(this.address, o.address); } } public StringList() { this.strings = new TreeSet<>(); } public void clear() { int oldSize = strings.size(); strings.clear(); if(oldSize > 0) { fireContentsChanged(this, 0, oldSize - 1); } } private Integer getIndex(long memAddr) { int i = 0; for(StringEntry entry : strings) { if(entry.address == memAddr) { return i; } } return null; } @Override public void onAnalyzeChange(final long memAddr, final DataEntry entry) { SwingUtilities.invokeLater(new Runnable() { public void run() { Integer oldIndex = getIndex(memAddr); Data data = null; if(entry != null && entry.getEntity() instanceof Data) { data = (Data) entry.getEntity(); } if(oldIndex != null) { // update entry if(data == null || data.getType() != DataType.STRING) { // remove entry strings.remove(new StringEntry(memAddr)); fireIntervalRemoved(this, oldIndex, oldIndex); } else { // changing entry int index = getIndex(memAddr); strings.remove(new StringEntry(memAddr)); strings.add(new StringEntry(memAddr, data)); fireContentsChanged(this, index, index); } } else { // add entry if(data == null || data.getType() != DataType.STRING) { return; } strings.add(new StringEntry(memAddr, data)); int index = getIndex(memAddr); fireIntervalAdded(this, index, index); } } }); } @Override public int getSize() { return strings.size(); } @Override public Data getElementAt(int index) { int i = 0; for(StringEntry entry : strings) { if(i == index) { return entry.data; } i++; } throw new IndexOutOfBoundsException("invalid index: " + index); } }
Java
package kianxali.gui.models; import java.awt.Color; import java.awt.Font; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultStyledDocument; import javax.swing.text.Element; import javax.swing.text.MutableAttributeSet; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.StyleConstants; import kianxali.decoder.Data; import kianxali.decoder.DecodedEntity; import kianxali.decoder.Instruction; import kianxali.decoder.Operand; import kianxali.disassembler.DataEntry; import kianxali.disassembler.Function; import kianxali.loader.ImageFile; import kianxali.loader.Section; import kianxali.util.OutputFormatter; public class ImageDocument extends DefaultStyledDocument { private static final long serialVersionUID = 1L; public static final String LineElementName = "line"; public static final String ReferenceElementName = "reference"; public static final String AddressElementName = "address"; public static final String RawBytesElementName = "rawBytes"; public static final String MnemonicElementName = "mnemonic"; public static final String OperandElementName = "operand"; public static final String InfoElementName = "info"; public static final String CommentElementName = "comment"; public static final String MemAddressKey = "memAddress"; public static final String RefAddressKey = "refAddress"; public static final String InstructionKey = "instruction"; private final MutableAttributeSet addressAttributes, lineAttributes, referenceAttributes; private final MutableAttributeSet rawBytesAttributes, mnemonicAttributes, operandAttributes; private final MutableAttributeSet infoAttributes, commentAttributes; private final OutputFormatter formatter; public ImageDocument(OutputFormatter formatter) { this.formatter = formatter; this.lineAttributes = new SimpleAttributeSet(); this.referenceAttributes = new SimpleAttributeSet(); this.addressAttributes = new SimpleAttributeSet(); this.rawBytesAttributes = new SimpleAttributeSet(); this.mnemonicAttributes = new SimpleAttributeSet(); this.operandAttributes = new SimpleAttributeSet(); this.infoAttributes = new SimpleAttributeSet(); this.commentAttributes = new SimpleAttributeSet(); // root -> {address} -> {line} lineAttributes.addAttribute(ElementNameAttribute, LineElementName); referenceAttributes.addAttribute(ElementNameAttribute, ReferenceElementName); rawBytesAttributes.addAttribute(ElementNameAttribute, RawBytesElementName); addressAttributes.addAttribute(ElementNameAttribute, AddressElementName); mnemonicAttributes.addAttribute(ElementNameAttribute, MnemonicElementName); operandAttributes.addAttribute(ElementNameAttribute, OperandElementName); infoAttributes.addAttribute(ElementNameAttribute, InfoElementName); commentAttributes.addAttribute(ElementNameAttribute, CommentElementName); setupStyles(); } private void setupStyles() { StyleConstants.setFontFamily(addressAttributes, Font.MONOSPACED); StyleConstants.setFontSize(addressAttributes, 12); StyleConstants.setForeground(referenceAttributes, new Color(0x00, 0x64, 0x00)); StyleConstants.setForeground(infoAttributes, new Color(0x00, 0x00, 0xFF)); StyleConstants.setForeground(rawBytesAttributes, new Color(0x40, 0x40, 0x40)); StyleConstants.setForeground(mnemonicAttributes, new Color(0x00, 0x00, 0xCC)); StyleConstants.setForeground(operandAttributes, new Color(0x00, 0x00, 0xCC)); StyleConstants.setForeground(commentAttributes, new Color(0xAA, 0xAA, 0xAA)); } private Element findFloorElement(long memAddr) { Element root = getDefaultRootElement(); Element res = root; int first = 0; Integer idx = null; int last = root.getElementCount() - 2; // do a binary search to find the floor element while(first <= last) { idx = first + (last - first) / 2; res = root.getElement(idx); long curAdr = (long) res.getAttributes().getAttribute(MemAddressKey); if(memAddr < curAdr) { last = idx - 1; } else if(memAddr > curAdr) { first = idx + 1; } else { break; } } if(res != root) { long curAdr = (long) res.getAttributes().getAttribute(MemAddressKey); if(curAdr > memAddr) { if(idx > 0) { return root.getElement(idx - 1); } else { return root; } } } return res; } public Integer getOffsetForAddress(long memAddr) { Element floorElem = findFloorElement(memAddr); if(floorElem != null) { return floorElem.getStartOffset(); } else { return null; } } public Long getAddressForOffset(int offset) { Element root = getDefaultRootElement(); int idx = root.getElementIndex(offset); Element elem = root.getElement(idx); Long addr = (Long) elem.getAttributes().getAttribute(MemAddressKey); return addr; } public synchronized void updateDataEntry(long memAddr, DataEntry data) { Element floorElem = findFloorElement(memAddr); boolean isRoot = (floorElem == getDefaultRootElement()); if(data == null) { // remove element if exists if(!isRoot) { long addr = (long) floorElem.getAttributes().getAttribute(MemAddressKey); if(addr == memAddr) { removeElement(floorElem); } } return; } try { List<ElementSpec> specs = new LinkedList<>(); specs.add(endTag()); MutableAttributeSet adrAttributes = new SimpleAttributeSet(addressAttributes); adrAttributes.addAttribute(MemAddressKey, memAddr); specs.add(startTag(adrAttributes)); int startSize = specs.size(); addImageStart(memAddr, data.getStartImageFile(), specs); addSectionEnd(memAddr, data.getEndSection(), specs); addSectionStart(memAddr, data.getStartSection(), specs); addFunctionStart(memAddr, data.getStartFunction(), specs); // only display references to functions or data if(data.getStartFunction() != null || !(data.getEntity() instanceof Instruction)) { addReferences(memAddr, data.getReferences(), specs); } addEntity(memAddr, data.getEntity(), data.getComment(), data.getAttachedData(), specs); addFunctionEnd(memAddr, data.getEndFunction(), specs); if(specs.size() == startSize) { // nothing was actually added return; } specs.add(endTag()); if(isRoot) { ElementSpec[] specArr = new ElementSpec[specs.size()]; specs.toArray(specArr); insert(0, specArr); } else { long addr = (long) floorElem.getAttributes().getAttribute(MemAddressKey); int offset = floorElem.getEndOffset(); if(addr == memAddr) { offset = floorElem.getStartOffset(); removeElement(floorElem); } if(getLength() > 0) { // end current section if there was content specs.add(0, endTag()); } ElementSpec[] specArr = new ElementSpec[specs.size()]; specs.toArray(specArr); insert(offset, specArr); } } catch(BadLocationException e) { e.printStackTrace(); } } private void startLine(long memAddr, List<ElementSpec> specs) { String address = String.format("%08X\t", memAddr); specs.add(startTag(lineAttributes)); SimpleAttributeSet attr = new SimpleAttributeSet(infoAttributes); StyleConstants.setForeground(attr, new Color(0x00, 0x99, 0x00)); specs.add(contentTag(attr, address)); } private void endLine(List<ElementSpec> specs) { specs.add(contentTag(infoAttributes, "\n")); specs.add(endTag()); } private void addImageStart(long memAddr, ImageFile imageFile, List<ElementSpec> specs) { if(imageFile == null) { return; } startLine(memAddr, specs); specs.add(contentTag(infoAttributes, "; Image file start")); endLine(specs); startLine(memAddr, specs); specs.add(contentTag(infoAttributes, "; Image name: " + imageFile.getFileName())); endLine(specs); startLine(memAddr, specs); specs.add(contentTag(infoAttributes, "; Entry point: " + formatter.formatAddress(imageFile.getCodeEntryPointMem()))); endLine(specs); } private void addSectionStart(long memAddr, Section startSection, List<ElementSpec> specs) { if(startSection == null) { return; } startLine(memAddr, specs); String line = String.format("; Section '%s' starts", startSection.getName()); specs.add(contentTag(infoAttributes, line)); endLine(specs); } private void addSectionEnd(long memAddr, Section endSection, List<ElementSpec> specs) { if(endSection == null) { return; } startLine(memAddr, specs); String line = String.format("; Section '%s' ends", endSection.getName()); specs.add(contentTag(infoAttributes, line)); endLine(specs); } private void addFunctionStart(long memAddr, Function fun, List<ElementSpec> specs) { if(fun == null) { return; } startLine(memAddr, specs); endLine(specs); startLine(memAddr, specs); String line = String.format("%s:", fun.getName()); specs.add(contentTag(infoAttributes, line)); endLine(specs); } private void addReferences(long memAddr, Map<DataEntry, Boolean> references, List<ElementSpec> specs) { if(references.size() == 0) { return; } startLine(memAddr, specs); specs.add(contentTag(referenceAttributes, "; Referenced by: ")); for(DataEntry ref : references.keySet()) { MutableAttributeSet attr = new SimpleAttributeSet(referenceAttributes); attr.addAttribute(RefAddressKey, ref.getAddress()); if(references.get(ref)) { // write access StyleConstants.setForeground(attr, Color.red); } specs.add(contentTag(attr, String.format("%08X ", ref.getAddress()))); } endLine(specs); } private void addFunctionEnd(long memAddr, Function fun, List<ElementSpec> specs) { if(fun == null) { return; } startLine(memAddr, specs); String line = String.format("; Function %s ends", fun.getName()); specs.add(contentTag(infoAttributes, line)); endLine(specs); } private void addEntity(long memAddr, DecodedEntity entity, String comment, Data dataRef, List<ElementSpec> specs) { if(entity == null) { return; } startLine(memAddr, specs); if(entity instanceof Instruction) { Instruction inst = (Instruction) entity; List<Operand> operands = inst.getOperands(); if(formatter.shouldIncludeRawBytes()) { String raw = String.format("%-20s ", OutputFormatter.formatByteString(inst.getRawBytes())); specs.add(contentTag(rawBytesAttributes, raw)); } String mnemo = formatter.formatMnemonic(inst.getMnemonic()) + ((operands.size() > 0) ? " " : ""); SimpleAttributeSet attr = new SimpleAttributeSet(mnemonicAttributes); attr.addAttribute(InstructionKey, inst); specs.add(contentTag(attr, mnemo)); List<Long> branches = inst.getBranchAddresses(); int i = 0; for(Operand op : operands) { Number opAsNum = op.asNumber(); MutableAttributeSet opAttrs = operandAttributes; if(branches.contains(opAsNum)) { opAttrs = new SimpleAttributeSet(referenceAttributes); opAttrs.addAttribute(RefAddressKey, opAsNum); } String opString = op.asString(formatter) + ((i < operands.size() - 1) ? ", " : ""); specs.add(contentTag(opAttrs, opString)); i++; } } else if(entity instanceof Data) { String dataLine = entity.asString(formatter); specs.add(contentTag(operandAttributes, dataLine)); } if(dataRef != null) { specs.add(contentTag(commentAttributes, " -> " + dataRef.asString(formatter))); } if(comment != null) { specs.add(contentTag(commentAttributes, " ; " + comment)); } endLine(specs); } private ElementSpec startTag(MutableAttributeSet attr) { ElementSpec res = new ElementSpec(attr, ElementSpec.StartTagType); res.setDirection(ElementSpec.OriginateDirection); return res; } private ElementSpec contentTag(MutableAttributeSet attr, String str) { char[] line = str.toCharArray(); ElementSpec res = new ElementSpec(attr, ElementSpec.ContentType, line, 0, line.length); res.setDirection(ElementSpec.OriginateDirection); return res; } private ElementSpec endTag() { return new ElementSpec(null, ElementSpec.EndTagType); } }
Java
package kianxali.gui.models; import java.util.NavigableSet; import java.util.TreeSet; import javax.swing.AbstractListModel; import javax.swing.SwingUtilities; import kianxali.disassembler.DataEntry; import kianxali.disassembler.DataListener; import kianxali.disassembler.Function; public class FunctionList extends AbstractListModel<Function> implements DataListener { private static final long serialVersionUID = 1L; private final NavigableSet<FunctionEntry> functions; private class FunctionEntry implements Comparable<FunctionEntry> { Function function; long address; public FunctionEntry(long memAddr) { this.address = memAddr; } public FunctionEntry(long memAddr, Function fun) { this.address = memAddr; this.function = fun; } @Override public int compareTo(FunctionEntry o) { return Long.compare(this.address, o.address); } } public FunctionList() { functions = new TreeSet<>(); } public void clear() { int oldSize = functions.size(); functions.clear(); if(oldSize > 0) { fireContentsChanged(this, 0, oldSize - 1); } } private Integer getIndex(long memAddr) { int i = 0; for(FunctionEntry entry : functions) { if(entry.address == memAddr) { return i; } } return null; } @Override public synchronized void onAnalyzeChange(final long memAddr, final DataEntry entry) { SwingUtilities.invokeLater(new Runnable() { public void run() { Integer oldIndex = getIndex(memAddr); if(oldIndex != null) { // update entry if((entry == null || entry.getStartFunction() == null)) { // remove function functions.remove(new FunctionEntry(memAddr)); fireIntervalRemoved(this, oldIndex, oldIndex); } else { // changing entry int index = getIndex(memAddr); functions.remove(new FunctionEntry(memAddr)); functions.add(new FunctionEntry(memAddr, entry.getStartFunction())); fireContentsChanged(this, index, index); } } else { // add entry if(entry == null || entry.getStartFunction() == null) { return; } functions.add(new FunctionEntry(memAddr, entry.getStartFunction())); int index = getIndex(memAddr); fireIntervalAdded(this, index, index); } } }); } @Override public synchronized int getSize() { return functions.size(); } @Override public synchronized Function getElementAt(int index) { int i = 0; for(FunctionEntry entry : functions) { if(i == index) { return entry.function; } i++; } throw new IndexOutOfBoundsException("invalid index: " + index); } }
Java
package kianxali.gui.models; import javax.swing.text.StyledEditorKit; import javax.swing.text.ViewFactory; public class ImageEditorKit extends StyledEditorKit { private static final long serialVersionUID = 1L; @Override public String getContentType() { return "application/octet-stream"; } @Override public ViewFactory getViewFactory() { return new ImageViewFactory(); } }
Java
package kianxali.gui.models; import javax.swing.text.BoxView; import javax.swing.text.Element; import javax.swing.text.ParagraphView; import javax.swing.text.StyledEditorKit; import javax.swing.text.View; import javax.swing.text.ViewFactory; import kianxali.gui.views.MnemonicView; public class ImageViewFactory implements ViewFactory { private final ViewFactory delegate; public ImageViewFactory() { delegate = new StyledEditorKit().getViewFactory(); } @Override public View create(Element e) { String kind = e.getName(); switch(kind) { case ImageDocument.AddressElementName: return new BoxView(e, BoxView.Y_AXIS); case ImageDocument.LineElementName: return new ParagraphView(e); case ImageDocument.MnemonicElementName: return new MnemonicView(e); default: return delegate.create(e); } } }
Java
/** * This package contains a JRuby interface to the application. * The Ruby interface is described in the {@link kianxali.scripting.ScriptAPI} * interface. */ package kianxali.scripting;
Java
package kianxali.scripting; import kianxali.decoder.DecodedEntity; import org.jruby.RubyProc; /** * This interfaces describes the methods that are available to * Ruby scripts through the $api object. * @author fwi * */ public interface ScriptAPI { /** * Traverses all instructions in the disassembly * @param block a ruby block that gets passed each instruction, e.g. * $api.traverseCode {|instruction| ...} * @see kianxali.decoder.Instruction */ void traverseCode(RubyProc block); /** * Checks whether a given address is a code address * @param addr the address to examine, null is allowed and will always be false * @return true iff the given address is in a code section of the image file */ boolean isCodeAddress(Long addr); /** * Retrieves the code or data entity for a given address * @param addr the address to examine * @return an instance of an instruction, a data object or null * @see kianxali.decoder.Instruction * @see kianxali.decoder.Data */ DecodedEntity getEntityAt(Long addr); /** * Read raw bits (8, 16, 32, or 64) contained at a virtual memory address * @param addr the address to examine * @param size number of bits (8, 16, 32 or 64) * @return the raw value contained at the given memory address or null if invalid address */ Long readBits(Long addr, Short size); /** * Applies a patch to a virtual memory address * @param addr the address to patch * @param data the data to write at the given address * @param size number of bits (8, 16, 32 or 64) at destination */ void patchBits(Long addr, Long data, Short size); /** * Causes the disassembler to reanalyze the trace at the given address * @param addr the memory address to reanalyze, subsequent address will also be reanalyzed */ void reanalyze(Long addr); /** * Convert from physical file offset to virtual address space * * @param fileOffset * @return */ long toMemAddress(Long fileOffset); }
Java
package kianxali.scripting; import java.util.logging.Level; import java.util.logging.Logger; import kianxali.decoder.DecodedEntity; import kianxali.decoder.Instruction; import kianxali.disassembler.Disassembler; import kianxali.disassembler.DisassemblyData; import kianxali.disassembler.InstructionVisitor; import kianxali.gui.Controller; import kianxali.loader.ByteSequence; import kianxali.loader.ImageFile; import org.jruby.Ruby; import org.jruby.RubyProc; import org.jruby.embed.ScriptingContainer; import org.jruby.javasupport.JavaEmbedUtils; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.builtin.IRubyObject; /** * This class is the interface between scripts entered by the user and the controller * associated with the GUI * @author fwi * */ public class ScriptManager implements ScriptAPI { private static final Logger LOG = Logger.getLogger("kianxali.scripting"); private final Controller controller; private final ScriptingContainer ruby; private final ThreadContext rubyContext; /** * Create a new script manager for a given controller. * The method blocks for a few seconds because loading JRuby takes quite a while * @param controller the controller that contains the disassembly data etc. */ public ScriptManager(Controller controller) { this.controller = controller; this.ruby = new ScriptingContainer(); this.rubyContext = ruby.getProvider().getRuntime().getCurrentContext(); Ruby.setThreadLocalRuntime(ruby.getProvider().getRuntime()); ruby.setWriter(controller.getLogWindowWriter()); ruby.put("$api", this); LOG.config("Using Ruby version: " + ruby.getCompatVersion()); } /** * Runs a ruby script * @param script the script to run */ public void runScript(String script) { try { ruby.runScriptlet(script); } catch(Exception e) { String msg = "Couldn't run script: " + e.getMessage(); LOG.log(Level.WARNING, msg, e); controller.showError(msg); } } private IRubyObject toRubyObject(Object object) { return JavaEmbedUtils.javaToRuby(rubyContext.getRuntime(), object); } @Override public void traverseCode(final RubyProc block) { DisassemblyData data = controller.getDisassemblyData(); if(data == null) { return; } data.visitInstructions(new InstructionVisitor() { @Override public void onVisit(Instruction inst) { IRubyObject[] args = {toRubyObject(inst)}; block.call(rubyContext, args); } }); } @Override public DecodedEntity getEntityAt(Long addr) { DisassemblyData data = controller.getDisassemblyData(); if(data == null || addr == null) { return null; } return data.getEntityOnExactAddress(addr); } @Override public boolean isCodeAddress(Long addr) { ImageFile image = controller.getImageFile(); if(image == null || addr == null) { return false; } return image.isCodeAddress(addr); } @Override public void patchBits(Long addr, Long data, Short size) { if(addr == null || data == null || size == null) { throw new IllegalArgumentException("null-address or data or size"); } ImageFile image = controller.getImageFile(); if(image == null) { throw new IllegalStateException("no image loaded"); } ByteSequence seq = image.getByteSequence(addr, true); switch(size) { case 8: seq.patchByte(((byte) (data & 0xFF))); break; case 16: seq.patchWord(((short) (data & 0xFFFF))); break; case 32: seq.patchDWord(((int) (data & 0xFFFFFFFF))); break; case 64: seq.patchQWord(data); break; default: seq.unlock(); throw new UnsupportedOperationException("Invalid size: " + size); } seq.unlock(); } @Override public void reanalyze(Long addr) { if(addr == null) { throw new IllegalArgumentException("null-address passed"); } Disassembler dasm = controller.getDisassembler(); if(dasm == null) { throw new IllegalStateException("no disassembler loaded"); } dasm.reanalyze(addr); } @Override public Long readBits(Long addr, Short size) { if(addr == null) { throw new IllegalArgumentException("null-address"); } if(size == null) { throw new IllegalArgumentException("null-size"); } ImageFile image = controller.getImageFile(); if(image == null) { throw new IllegalStateException("no image loaded"); } ByteSequence seq = image.getByteSequence(addr, true); long res; switch(size) { case 8: res = seq.readUByte(); break; case 16: res = seq.readUWord(); break; case 32: res = seq.readUDword(); break; case 64: res = seq.readSQword(); break; default: seq.unlock(); throw new UnsupportedOperationException("Invalid size: " + size); } seq.unlock(); return res; } @Override public long toMemAddress(Long fileOffset) { return controller.getImageFile().toMemAddress(fileOffset); } }
Java
package kianxali.util; import java.io.PrintWriter; import java.io.StringWriter; import java.util.logging.Formatter; import java.util.logging.LogRecord; /** * This class implements a log formatter that simply prefixes log entries with * their severity. * * Based on <a href='http://stackoverflow.com/questions/2950704/java-util-logging-how-to-suppress-date-line'> * http://stackoverflow.com/questions/2950704/java-util-logging-how-to-suppress-date-line</a> * * @author fwi * */ public class LogFormatter extends Formatter { @Override public String format(final LogRecord r) { StringBuilder sb = new StringBuilder(); sb.append(String.format("%7s: ", r.getLevel())); sb.append(formatMessage(r)).append(System.getProperty("line.separator")); if(null != r.getThrown()) { sb.append("Throwable occurred: "); Throwable t = r.getThrown(); PrintWriter pw = null; try { StringWriter sw = new StringWriter(); pw = new PrintWriter(sw); t.printStackTrace(pw); sb.append(sw.toString()); } finally { if(pw != null) { try { pw.close(); } catch(Exception e) { e.printStackTrace(); } } } } return sb.toString(); } }
Java
/** * This package contains some independent utility classes that are * used throughout the project. */ package kianxali.util;
Java
package kianxali.util; /** * This interface is implemented by classes that can resolve memory addresses * to symbol names. * @author fwi * */ public interface AddressNameResolver { /** * Resolve the symbol name of a memory address. * @param memAddr the memory address to resolve * @return the name of the symbol associated with the memory address or null if no symbol */ String resolveAddress(long memAddr); }
Java
package kianxali.util; /** * This class stores information about how the output of instructions * and data should be formatted, e.g. the format of hex strings, addresses, * mnemonics and so on. * @author fwi * */ public class OutputFormatter { private boolean includeRawBytes; private AddressNameResolver addrResolver; /** * Construct a new formatter with default settings. */ public OutputFormatter() { } /** * Sets a resolver that provides symbol names for memory addresses. * It will be used to display symbol names instead of addresses if present. * @param resolver the resolver to ask about memory addresses */ public void setAddressNameResolve(AddressNameResolver resolver) { this.addrResolver = resolver; } /** * Formats a byte string as a hex string * @param bytes the byte array * @return a hex string describing the byte array */ public static String formatByteString(short[] bytes) { StringBuilder res = new StringBuilder(); for(short b : bytes) { res.append(String.format("%02X", b)); } return res.toString(); } /** * Configure whether the raw instruction bytes should be included when displaying * an instruction * @param includeRawBytes true if the instruction bytes should be included */ public void setIncludeRawBytes(boolean includeRawBytes) { this.includeRawBytes = includeRawBytes; } /** * Returns whether raw instruction bytes should be included when displaying * an instruction * @return true if the instruction bytes should be included */ public boolean shouldIncludeRawBytes() { return includeRawBytes; } /** * Formats a register name * @param name the name of the register * @return the formatted name of the register */ public String formatRegister(String name) { return name.toLowerCase(); } /** * Formats a given number. * @param num the number to format * @param includeMinus whether the sign should be output * @return a string containing the formatted number */ public String formatNumber(long num, boolean includeMinus) { StringBuilder res = new StringBuilder(); if(num < 0) { res.append(Long.toHexString(-num).toUpperCase()); } else { res.append(Long.toHexString(num).toUpperCase()); } // Denote that the string is hexadecimal if needed if(Math.abs(num) > 9) { res.append("h"); } // add a leading zero if the representation starts with a letter if(Character.isAlphabetic(res.charAt(0))) { res.insert(0, "0"); } // add minus if number is negative and user wants to include the sign if(num < 0 && includeMinus) { res.insert(0, "-"); } return res.toString(); } /** * Formats a given immediate * @param immediate the immediate to format * @return a string describing the immediate */ public String formatImmediate(long immediate) { if(addrResolver != null && addrResolver.resolveAddress(immediate) != null) { return addrResolver.resolveAddress(immediate); } return formatNumber(immediate, true); } /** * Formats a given virtual memory address * @param offset the address to format * @return the formatted addresses */ public String formatAddress(long offset) { if(addrResolver != null && addrResolver.resolveAddress(offset) != null) { return addrResolver.resolveAddress(offset); } return formatNumber(offset, false); } /** * Formats a given mnemonic * @param string the mnemonic to format * @return the formatted mnemonic */ public String formatMnemonic(String string) { return string.toLowerCase(); } }
Java
package kianxali; import java.util.logging.ConsoleHandler; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.Logger; import kianxali.gui.Controller; import kianxali.util.LogFormatter; /** * Kianxali is an interactive, scriptable disassembler supporting multiple architectures * and file types. * @author fwi * */ public final class Kianxali { private static final Logger LOG = Logger.getLogger("kianxali"); private final Controller controller; /** * Create a new instance of the disassembler * @param logLevel the log level to display on the console */ public Kianxali(Level logLevel) { // setup logging Handler consoleHandler = new ConsoleHandler(); consoleHandler.setLevel(logLevel); consoleHandler.setFormatter(new LogFormatter()); LOG.setUseParentHandlers(false); LOG.addHandler(consoleHandler); LOG.setLevel(logLevel); LOG.info("Kianxali starting"); controller = new Controller(); } /** * Starts the actual disassembler by showing the GUI */ public void start() { controller.showGUI(); } /** * Main entry point of the program: Starts the disassembler and shows the GUI * @param args unused */ public static void main(String[] args) { Kianxali kianxali = new Kianxali(Level.FINEST); kianxali.start(); } }
Java
package kianxali.loader.mach_o; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import kianxali.loader.ByteSequence; // Source of information: http://code.google.com/p/networkpx/source/browse/etc/idc/dyldinfo.idc public class SymbolTable { private static final Logger LOG = Logger.getLogger("kianxali.loader.mach_o"); private static final short OPCODE_DONE = 0x00; private static final short OPCODE_SET_DYLIB_ORDINAL_IMM = 0x10; private static final short OPCODE_SET_DYLIB_ORDINAL_ULEB = 0x20; private static final short OPCODE_SET_DYLIB_SPECIAL_IMM = 0x30; private static final short OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM = 0x40; private static final short OPCODE_SET_TYPE_IMM = 0x50; private static final short OPCODE_SET_ADDEND_SLEB = 0x60; private static final short OPCODE_SET_SEGMENT_AND_OFFSET_ULEB = 0x70; private static final short OPCODE_ADD_ADDR_ULEB = 0x80; private static final short OPCODE_DO_BIND = 0x90; private static final short OPCODE_DO_BIND_ADD_ADDR_ULEB = 0xA0; private static final short OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED = 0xB0; private static final short OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB = 0xC0; private final long offset, size; private final Map<Long, String> symbols; public SymbolTable(ByteSequence seq, long startOffset, boolean mach64) { symbols = new HashMap<>(); seq.skip(8); // rebase info seq.skip(8); // binding info seq.skip(8); // weak binding info offset = startOffset + seq.readUDword(); size = seq.readUDword(); seq.skip(8); // export info } private long readULEB(ByteSequence seq) { long res = 0, bit = 0; short c; do { c = seq.readUByte(); res |= ((c & 0x7F) << bit); bit += 7; } while((c & 0x80) != 0); return res; } public void load(List<MachSegment> segments, ByteSequence seq, boolean mach64) { seq.seek(offset); String symbolName = null; long addr = 0; while(seq.getPosition() - offset < size) { short data = seq.readUByte(); short imm = (short) (data & 0x0F); short opcode = (short) (data & 0xF0); switch(opcode) { case OPCODE_SET_DYLIB_ORDINAL_ULEB: case OPCODE_SET_ADDEND_SLEB: // we don't need this but have to read the ULEB to stay in sync with the opcode stream readULEB(seq); break; case OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: symbolName = seq.readString(); break; case OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: addr = segments.get(imm).getVirtualAddress() + readULEB(seq); break; case OPCODE_ADD_ADDR_ULEB: addr += readULEB(seq); break; case OPCODE_DO_BIND: symbols.put(addr, symbolName); addr += 4; break; case OPCODE_DO_BIND_ADD_ADDR_ULEB: symbols.put(addr, symbolName); addr += 4 + readULEB(seq); break; case OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: symbols.put(addr, symbolName); addr += 4 * (imm + 1); break; case OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: long count = readULEB(seq); long skip = readULEB(seq); symbols.put(addr, symbolName); addr += count * (4 + skip); break; case OPCODE_SET_DYLIB_ORDINAL_IMM: case OPCODE_SET_DYLIB_SPECIAL_IMM: case OPCODE_SET_TYPE_IMM: case OPCODE_DONE: // we don't need these at all break; default: LOG.warning("Invalid bind opcode: " + opcode); return; } } } public Map<Long, String> getSymbols() { return symbols; } }
Java
package kianxali.loader.mach_o; import java.nio.ByteOrder; import java.util.HashMap; import java.util.Map; import kianxali.loader.ByteSequence; public class FatHeader { public static final long FAT_MAGIC = 0xBEBAFECAL; private final Map<Long, Long> entries; public FatHeader(ByteSequence seq) { long magic = seq.readUDword(); seq.setByteOrder(ByteOrder.BIG_ENDIAN); long nArch = seq.readUDword(); if(magic != FAT_MAGIC || nArch >= 20) { System.out.println(String.format("%X %X", magic, nArch)); throw new UnsupportedOperationException("Invalid fat_header"); } entries = new HashMap<>(); for(long i = 0; i < nArch; i++) { long type = seq.readUDword(); seq.readUDword(); // subtype long offset = seq.readUDword(); seq.readUDword(); // size seq.readUDword(); // align entries.put(type, offset); } seq.setByteOrder(ByteOrder.LITTLE_ENDIAN); } public Map<Long, Long> getArchitectures() { return entries; } }
Java
/** * This package implements a loader for the Mach-O and fat format according to * <a href ='https://developer.apple.com/library/mac/documentation/DeveloperTools/Conceptual/MachORuntime/Reference/reference.html'> * https://developer.apple.com/library/mac/documentation/DeveloperTools/Conceptual/MachORuntime/Reference/reference.html</a> * and the OS X loader header files. */ package kianxali.loader.mach_o;
Java
package kianxali.loader.mach_o; import kianxali.loader.ByteSequence; public class MachSegment { private final String name; private long virtualAddress, virtualSize, fileOffset, fileSize; private final MachSection[] sections; public MachSegment(ByteSequence seq, long startOffset, boolean mach64) { name = seq.readString(16); if(mach64) { virtualAddress = seq.readSQword(); virtualSize = seq.readSQword(); fileOffset = startOffset + seq.readSQword(); fileSize = seq.readSQword(); } else { virtualAddress = seq.readUDword(); virtualSize = seq.readUDword(); fileOffset = startOffset + seq.readUDword(); fileSize = seq.readUDword(); } // memory protection seq.skip(2 * 4); long numSections = seq.readUDword(); // flags seq.skip(4); sections = new MachSection[(int) numSections]; for(int i = 0; i < numSections; i++) { sections[i] = new MachSection(seq, startOffset, mach64); } } public String getName() { return name; } public MachSection[] getSections() { return sections; } public long getVirtualAddress() { return virtualAddress; } public long getVirtualSize() { return virtualSize; } public long getFileOffset() { return fileOffset; } public long getFileSize() { return fileSize; } }
Java
package kianxali.loader.mach_o; import java.util.ArrayList; import java.util.List; import kianxali.loader.ByteSequence; public class MachHeader { public static final long MH_MAGIC = 0xFEEDFACEL; public static final long MH_MAGIC_64 = 0xFEEDFACFL; public static final long CPU_TYPE_X86 = 7L; public static final long CPU_TYPE_X86_64 = 0x01000007L; public static final long THREAD_STATE_32 = 0x1L; public static final long THREAD_STATE_64 = 0x4L; public static final long LC_SEGMENT = 0x1L; public static final long LC_UNIXTHREAD = 0x5L; public static final long LC_DYLD_INFO_ONLY = 0x80000022L; public static final long LC_SEGMENT_64 = 0x19L; public static final long LC_MAIN = 0x80000028L; private boolean mach64; private final long startOffset; private boolean entryPointIsMem; private long entryPoint; private final List<MachSegment> segments; private final List<MachSection> sections; private SymbolTable symbolTable; public MachHeader(ByteSequence seq, long offset) { startOffset = offset; segments = new ArrayList<>(); sections = new ArrayList<>(); seq.seek(offset); long magic = seq.readUDword(); if(magic == MH_MAGIC) { mach64 = false; } else if(magic == MH_MAGIC_64) { mach64 = true; } else { throw new UnsupportedOperationException(String.format("Invalid Mach-O magic: %8X", magic)); } long cpuType = seq.readSDword(); if(cpuType != CPU_TYPE_X86 && cpuType != CPU_TYPE_X86_64) { throw new UnsupportedOperationException("Invalid Mach-O CPU type: " + cpuType); } // subtype seq.readSDword(); // filetype seq.readUDword(); long numLoadCommands = seq.readUDword(); // number of bytes seq.readUDword(); // flags seq.readUDword(); if(mach64) { // reserved seq.readUDword(); } // process load commands for(int i = 0; i < numLoadCommands; i++) { long cmd = seq.readUDword(); long size = seq.readUDword(); if(cmd == LC_SEGMENT_64 || cmd == LC_SEGMENT) { MachSegment segment = new MachSegment(seq, startOffset, mach64); for(MachSection section : segment.getSections()) { sections.add(section); } segments.add(segment); } else if(cmd == LC_DYLD_INFO_ONLY) { symbolTable = new SymbolTable(seq, startOffset, mach64); } else if(cmd == LC_UNIXTHREAD) { entryPointIsMem = true; long flavor = seq.readUDword(); seq.readUDword(); if(flavor == THREAD_STATE_32) { seq.skip(10 * 4); entryPoint = seq.readUDword(); seq.skip(5 * 4); } else if(flavor == THREAD_STATE_64) { seq.skip(16 * 8); entryPoint = seq.readSQword(); seq.skip(4 * 8); } else { throw new UnsupportedOperationException("Invalid Mach-O thread flavor: " + flavor); } } else if(cmd == LC_MAIN) { entryPointIsMem = false; if(mach64) { entryPoint = startOffset + seq.readSQword(); seq.readSQword(); } else { entryPoint = startOffset + seq.readUDword(); seq.readUDword(); } } else { seq.skip(size - 8); } } if(symbolTable != null) { symbolTable.load(segments, seq, mach64); } } public long getStartOffset() { return startOffset; } public SymbolTable getSymbolTable() { return symbolTable; } public boolean isMach64() { return mach64; } public boolean isEntryPointMem() { return entryPointIsMem; } public long getEntryPoint() { return entryPoint; } public List<MachSection> getSections() { return sections; } }
Java
package kianxali.loader.mach_o; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Path; import java.util.HashMap; import java.util.List; import java.util.Map; import kianxali.decoder.Context; import kianxali.loader.ImageFile; import kianxali.loader.Section; /** * Implements a parser for the fat file format that can include Mach-O files * for difference architectures. * @author fwi * */ public class FatFile extends ImageFile { private final FatHeader fatHeader; public FatFile(Path path) throws IOException { super(path); imageFile.seek(0); fatHeader = new FatHeader(imageFile); } public static boolean isFatFile(Path path) throws IOException { FileInputStream fileIn = new FileInputStream(path.toFile()); DataInputStream dataIn = new DataInputStream(fileIn); // Java classes and OS X Fat binaries use the same magic // Hack: The 2nd field of Java specifies the file format version (starting at 43) // while the 2nd field of a fat header specifies the number of architectures (at most 19) // Source of information: http://www.puredarwin.org/developers/universal-binaries long magic1 = Integer.reverseBytes(dataIn.readInt()) & 0xFFFFFFFFL; long magic2 = dataIn.readInt() & 0xFFFFFFFFL; dataIn.close(); fileIn.close(); return magic1 == FatHeader.FAT_MAGIC && magic2 < 20; } public Map<String, Long> getArchitectures() { Map<Long, Long> archMap = fatHeader.getArchitectures(); Map<String, Long> res = new HashMap<>(); for(Long type : archMap.keySet()) { long offset = archMap.get(type); if(type == MachHeader.CPU_TYPE_X86) { res.put("x86", offset); } else if(type == MachHeader.CPU_TYPE_X86_64) { res.put("x86_64", archMap.get(type)); } else { res.put(String.format("Unknown CPU type %d", type), offset); } } return res; } @Override public List<Section> getSections() { throw new UnsupportedOperationException("not a mach file"); } @Override public Context createContext() { throw new UnsupportedOperationException("not a mach file"); } @Override public long getCodeEntryPointMem() { throw new UnsupportedOperationException("not a mach file"); } @Override public long toFileAddress(long memAddress) { throw new UnsupportedOperationException("not a mach file"); } @Override public long toMemAddress(long fileOffset) { throw new UnsupportedOperationException("not a mach file"); } @Override public Map<Long, String> getImports() { throw new UnsupportedOperationException("not a mach file"); } }
Java
package kianxali.loader.mach_o; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteOrder; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import kianxali.decoder.Context; import kianxali.decoder.arch.x86.X86Context; import kianxali.decoder.arch.x86.X86CPU.ExecutionMode; import kianxali.decoder.arch.x86.X86CPU.Model; import kianxali.loader.ImageFile; import kianxali.loader.Section; /** * Implements a loader for the Mach-O format. See package info for * the used references. * @author fwi * */ public class MachOFile extends ImageFile { private MachHeader machHeader; public MachOFile(Path path, long offset) throws IOException { super(path); loadHeaders(offset); } public static boolean isMachOFile(Path path) throws IOException { FileInputStream fileIn = new FileInputStream(path.toFile()); DataInputStream dataIn = new DataInputStream(fileIn); long magic = Integer.reverseBytes(dataIn.readInt()) & 0xFFFFFFFFL; dataIn.close(); fileIn.close(); return magic == MachHeader.MH_MAGIC || magic == MachHeader.MH_MAGIC_64; } private void loadHeaders(long offset) { imageFile.lock(); imageFile.setByteOrder(ByteOrder.LITTLE_ENDIAN); machHeader = new MachHeader(imageFile, offset); imageFile.unlock(); } @Override public List<Section> getSections() { List<MachSection> sections = machHeader.getSections(); List<Section> res = new ArrayList<Section>(sections.size()); for(Section sec : sections) { res.add(sec); } return res; } @Override public Context createContext() { if(machHeader.isMach64()) { return new X86Context(Model.ANY, ExecutionMode.LONG); } else { return new X86Context(Model.ANY, ExecutionMode.PROTECTED); } } @Override public long getCodeEntryPointMem() { if(machHeader.isEntryPointMem()) { return machHeader.getEntryPoint(); } else { return toMemAddress(machHeader.getEntryPoint()); } } @Override public long toFileAddress(long memAddress) { MachSection section = (MachSection) getSectionForMemAddress(memAddress); long diff = memAddress - section.getStartAddress(); return section.getFileOffset() + diff; } @Override public long toMemAddress(long fileOffset) { for(MachSection section : machHeader.getSections()) { if(fileOffset >= section.getFileOffset() && fileOffset <= section.getFileOffset() + section.getVirtualSize()) { long diff = fileOffset - section.getFileOffset(); return section.getStartAddress() + diff; } } throw new UnsupportedOperationException("invalid file offset: " + fileOffset); } @Override public Map<Long, String> getImports() { if(machHeader.getSymbolTable() != null) { Map<Long, String> res = machHeader.getSymbolTable().getSymbols(); if(res != null) { return res; } } return new HashMap<Long, String>(); } }
Java
package kianxali.loader.mach_o; import kianxali.loader.ByteSequence; import kianxali.loader.Section; public class MachSection implements Section { private final String name, segmentName; private final long virtualAddress, virtualSize, fileOffset, flags; public MachSection(ByteSequence seq, long startOffset, boolean mach64) { name = seq.readString(16); segmentName = seq.readString(16); if(mach64) { virtualAddress = seq.readSQword(); virtualSize = seq.readSQword(); } else { virtualAddress = seq.readUDword(); virtualSize = seq.readUDword(); } fileOffset = startOffset + seq.readUDword(); seq.skip(3 * 4); flags = seq.readUDword(); seq.skip(2 * 4); if(mach64) { seq.skip(4); } } public String getSegmentName() { return segmentName; } public String getName() { return name; } public long getVirtualSize() { return virtualSize; } public long getFileOffset() { return fileOffset; } @Override public long getStartAddress() { return virtualAddress; } @Override public long getEndAddress() { return getStartAddress() + getVirtualSize(); } @Override public boolean isExecutable() { return ((flags & (1 << 31)) != 0); } }
Java
package kianxali.loader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.util.concurrent.locks.ReentrantLock; /** * This class represents a stream of bytes and allows to read the standard x86 * data types from the stream. The file is completely loaded into an array instead * of using memory mapped I/O because it should be possible to store data files * of the disassembler that can be loaded without having the actual image file. * @author fwi * */ public final class ByteSequence { private final byte[] data; private final ByteBuffer bytes; private final ReentrantLock lock; private ByteSequence(byte[] input, boolean doCopy) { if(doCopy) { this.data = new byte[input.length]; System.arraycopy(input, 0, data, 0, input.length); } else { this.data = input; } this.bytes = ByteBuffer.wrap(data); this.bytes.order(ByteOrder.LITTLE_ENDIAN); this.lock = new ReentrantLock(); } /** * Construct a new byte sequence from a given path. * @param path the path describing the file to be opened * @return the byte sequence for the file * @throws IOException if the file couldn't be read */ public static ByteSequence fromFile(Path path) throws IOException { File file = path.toFile(); FileInputStream fileStream = new FileInputStream(file); byte[] input = new byte[(int) file.length()]; fileStream.read(input); fileStream.close(); return new ByteSequence(input, false); } /** * Construct a new byte sequence from a given byte array. The byte array * will be copied, i.e. the changes will not be reflected in either direction * @param bytes the byte array to use * @return the byte sequence containing the array */ public static ByteSequence fromBytes(byte[] bytes) { return new ByteSequence(bytes, true); } /** * Applies a patch to the byte sequence. This only happens in memory. * @param offset the file offset to patch * @param b the byte to write at the given offset */ public void patchByte(long offset, byte b) { bytes.position((int) offset); patchByte(b); } /** * Applies a patch to the current location. * @param b the byte to write at the current location */ public void patchByte(byte b) { bytes.put(b); } /** * Applies a patch to the current location. * @param w the word to write at the current location */ public void patchWord(short w) { bytes.putShort(w); } /** * Applies a patch to the current location. * @param d the dword to write at the current location */ public void patchDWord(int d) { bytes.putInt(d); } /** * Applies a patch to the current location. * @param q the qword to write at the current location */ public void patchQWord(long q) { bytes.putLong(q); } /** * Attempts to lock the byte sequence. Note that the lock only * applies to other threads that also use lock, i.e. it's still possible * to access the byte sequence without a lock. */ public void lock() { lock.lock(); } /** * Unlocks the byte sequence. Must always be called after lock. */ public void unlock() { lock.unlock(); } /** * Sets the byte order of the sequence. Affects the read and write operations. * @param endian the byte order to use */ public void setByteOrder(ByteOrder endian) { bytes.order(endian); } /** * Seek to a given offset in the file * @param offset the offset to position the cursor to */ public void seek(long offset) { bytes.position((int) offset); } /** * Lets the cursor skip the given amount of bytes * @param amount the number of bytes to skip the cursor */ public void skip(long amount) { bytes.position((int) (bytes.position() + amount)); } /** * Returns the current position of the cursor * @return the cursor's offset in the byte array */ public long getPosition() { return bytes.position(); } /** * Returns whether there are more bytes after the cursor * @return true iff at least one byte can be read after the cursor */ public boolean hasMore() { return bytes.hasRemaining(); } /** * Returns the number of bytes that can be read after the cursor * @return the number of bytes that can be read after the cursor */ public int getRemaining() { return bytes.remaining(); } /** * Reads a unsigned byte from the current cursor position * @return the byte read */ public short readUByte() { return (short) (bytes.get() & 0xFF); } /** * Reads a signed byte from the current cursor position * @return the byte read */ public byte readSByte() { return bytes.get(); } /** * Reads a unsigned word (16 bit) from the current cursor position * @return the word read */ public int readUWord() { return bytes.getShort() & 0xFFFF; } /** * Reads a signed word (16 bit) from the current cursor position * @return the word read */ public short readSWord() { return bytes.getShort(); } /** * Reads a unsigned dword (32 bit) from the current cursor position * @return the dword read */ public long readUDword() { return bytes.getInt() & 0xFFFFFFFFL; } /** * Reads a signed dword (32 bit) from the current cursor position * @return the dword read */ public int readSDword() { return bytes.getInt(); } /** * Reads a signed qword (64 bit) from the current cursor position * @return the qword read */ public long readSQword() { return bytes.getLong(); } /** * Reads a float from the current cursor position * @return the float read */ public float readFloat() { return bytes.getFloat(); } /** * Reads a double from the current cursor position * @return the double read */ public double readDouble() { return bytes.getDouble(); } /** * Reads a null-terminated ASCII string from the current cursor position * @return the string read */ public String readString() { StringBuilder res = new StringBuilder(); do { byte b = bytes.get(); if(b != 0) { res.append((char) b); } else { break; } } while(true); return res.toString(); } /** * Reads an ASCII string with a given length from the current cursor position. * If there is a 0 character in the string, it will be skipped * @return the string read */ public String readString(int maxLen) { StringBuilder res = new StringBuilder(); for(int i = 0; i < maxLen; i++) { byte b = bytes.get(); if(b != 0) { res.append((char) b); } } return res.toString(); } /** * Saves a version of the byte array that contains all the patches * @param path the path to save the array to * @throws IOException if the file couldn't be written */ public void savePatched(Path path) throws IOException { RandomAccessFile file = new RandomAccessFile(path.toFile(), "rws"); FileChannel channel = file.getChannel(); bytes.rewind(); channel.write(bytes); channel.close(); file.close(); } }
Java
/** * This package implements a loader for the ELF format according to * <a href='http://www.linux-kernel.de/appendix/ap05.pdf'>http://www.linux-kernel.de/appendix/ap05.pdf</a> * and <elf.h> */ package kianxali.loader.elf;
Java
package kianxali.loader.elf; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Logger; import kianxali.decoder.Context; import kianxali.decoder.arch.x86.X86Context; import kianxali.decoder.arch.x86.X86CPU.ExecutionMode; import kianxali.decoder.arch.x86.X86CPU.Model; import kianxali.loader.ImageFile; import kianxali.loader.Section; /** * Implements a loader for ELF files, see package info for used references. * @author fwi * */ public class ELFFile extends ImageFile { private static final Logger LOG = Logger.getLogger("kianxali.loader.elf"); private final ELFHeader header; private final Map<Long, String> imports; private final Map<Long, String> stringTable; private List<Section> loadedSections; public ELFFile(Path path) throws IOException { super(path); this.imports = new HashMap<>(); header = new ELFHeader(imageFile); stringTable = loadStringTable(header.getStringSection()); loadSections(); loadSymbols(); loadRelocations(); } public static boolean isELFFile(Path path) throws IOException { FileInputStream fileIn = new FileInputStream(path.toFile()); DataInputStream dataIn = new DataInputStream(fileIn); long magic = dataIn.readInt() & 0xFFFFFFFFL; dataIn.close(); fileIn.close(); return magic == ELFHeader.ELF_MAGIC; } private Map<Long, String> loadStringTable(SectionHeader stringHeader) { Map<Long, String> res = new HashMap<>(); if(stringHeader == null) { return res; } long startPos = stringHeader.getOffset(); long endPos = stringHeader.getOffset() + stringHeader.getSize(); imageFile.seek(startPos); while(imageFile.getPosition() < endPos) { long entryPos = imageFile.getPosition() - startPos; String entry = imageFile.readString(); res.put(entryPos, entry); } return res; } private void loadSections() { loadedSections = new ArrayList<>(header.getSectionHeaders().size()); for(SectionHeader section : header.getSectionHeaders()) { if(section.getAddress() == 0) { // only analyze sections that are actually loaded continue; } long nameIndex = section.getNameIndex(); String name = stringTable.get(nameIndex); long start = section.getAddress(); long end = start + section.getSize(); long offset = section.getOffset(); boolean executable = section.isExecutable(); loadedSections.add(new ELFSection(name, offset, start, end, executable)); } } private List<ELFSymbol> readSymbols(SectionHeader symSection) { List<ELFSymbol> res = new ArrayList<>(); Map<Long, String> symStrTab = loadStringTable(header.getSectionHeaders().get((int) symSection.getLink())); imageFile.seek(symSection.getOffset()); for(int i = 0; i < symSection.getSize() / symSection.getEntrySize(); i++) { ELFSymbol sym = new ELFSymbol(imageFile, header.has64BitHeader()); String name = symStrTab.get(sym.getNameIndex()); sym.attachName(name); res.add(sym); } return res; } private void loadSymbols() { for(SectionHeader section : header.getSectionHeaders()) { if(section.getType() != SectionHeader.Type.SHT_SYMTAB) { // we only want the symbol table here continue; } for(ELFSymbol sym : readSymbols(section)) { if(sym.getValue() != 0 && sym.getAttachedName() != null && sym.getType() == ELFSymbol.Type.STT_FUNC) { imports.put(sym.getValue(), sym.getAttachedName()); } } } } private void loadRelocations() { for(SectionHeader section : header.getSectionHeaders()) { if(section.getType() != SectionHeader.Type.SHT_REL && section.getType() != SectionHeader.Type.SHT_RELA) { // only analyze relocation tables continue; } SectionHeader linkedSection = header.getSectionHeaders().get(((int) section.getLink())); if(linkedSection.getType() != SectionHeader.Type.SHT_DYNSYM) { // not sure if that can happen, hopefully not LOG.warning("ELF SHT_REL/A with link not being SHT_DYNSYM"); continue; } // parse linked DynSym table List<ELFSymbol> symbols = readSymbols(linkedSection); imageFile.seek(section.getOffset()); for(int i = 0; i < section.getSize() / section.getEntrySize(); i++) { boolean addend = false; if(section.getType() == SectionHeader.Type.SHT_RELA) { addend = true; } ELFRelocation rel = new ELFRelocation(imageFile, addend, header.has64BitHeader()); if(rel.getType() != ELFRelocation.Type.JUMP_SLOT) { // only analyze jump slots for now continue; } String name = symbols.get((int) rel.getInfoIndex()).getAttachedName(); imports.put(rel.getAddress(), name); } } } @Override public long getCodeEntryPointMem() { return header.getEntryPoint(); } @Override public List<Section> getSections() { return Collections.unmodifiableList(loadedSections); } @Override public Context createContext() { if(header.has64BitCode()) { return new X86Context(Model.ANY, ExecutionMode.LONG); } else { return new X86Context(Model.ANY, ExecutionMode.PROTECTED); } } @Override public long toFileAddress(long memAddress) { ELFSection section = (ELFSection) getSectionForMemAddress(memAddress); long diff = memAddress - section.getStartAddress(); return section.getOffset() + diff; } @Override public long toMemAddress(long fileOffset) { for(Section sec : loadedSections) { ELFSection section = (ELFSection) sec; long size = section.getEndAddress() - section.getStartAddress(); if(fileOffset >= section.getOffset() && fileOffset <= section.getOffset() + size) { long diff = fileOffset - section.getOffset(); return section.getStartAddress() + diff; } } throw new UnsupportedOperationException("invalid file offset: " + fileOffset); } @Override public Map<Long, String> getImports() { return Collections.unmodifiableMap(imports); } }
Java
package kianxali.loader.elf; import kianxali.loader.Section; public class ELFSection implements Section { private final String name; private final long offset, start, end; private final boolean executable; public ELFSection(String name, long offset, long start, long end, boolean executable) { this.name = name; this.offset = offset; this.start = start; this.end = end; this.executable = executable; } @Override public String getName() { return name; } @Override public boolean isExecutable() { return executable; } public long getOffset() { return offset; } @Override public long getStartAddress() { return start; } @Override public long getEndAddress() { return end; } }
Java
package kianxali.loader.elf; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.List; import kianxali.loader.ByteSequence; public class ELFHeader { public static final long ELF_MAGIC = 0x7F454C46; private enum Machine { X86, X86_64 }; private boolean elf64; // header format, not machine private Machine machine; private long entryPoint; private long programOffset, sectionOffset; private final int progHeaderCount; private final int sectHeaderCount, sectHeaderStringIndex; private List<ProgramHeader> programHeaders; private List<SectionHeader> sectionHeaders; public ELFHeader(ByteSequence seq) { seq.setByteOrder(ByteOrder.BIG_ENDIAN); long magic = seq.readUDword(); if(magic != ELF_MAGIC) { throw new UnsupportedOperationException("invalid magic"); } short eiClass = seq.readUByte(); if(eiClass == 1) { elf64 = false; } else if(eiClass == 2) { elf64 = true; } else { throw new UnsupportedOperationException("invalid EI_CLASS: " + eiClass); } short eiData = seq.readUByte(); if(eiData == 1) { seq.setByteOrder(ByteOrder.LITTLE_ENDIAN); } else if(eiData == 2) { seq.setByteOrder(ByteOrder.BIG_ENDIAN); } else { throw new UnsupportedOperationException("invalid EI_DATA: " + eiData); } short eiVersion = seq.readUByte(); if(eiVersion != 1) { throw new UnsupportedOperationException("invalid EI_VERSION: " + eiVersion); } // skip uninteresting parts seq.skip(9); int eType = seq.readUWord(); if(eType != 2 && eType != 3) { throw new UnsupportedOperationException("invalid e_type: " + eType); } int eMachine = seq.readUWord(); if(eMachine == 3 || eMachine == 6) { machine = Machine.X86; } else if(eMachine == 62) { machine = Machine.X86_64; } long eVersion = seq.readUDword(); if(eVersion != 1) { throw new UnsupportedOperationException("invalid e_version: " + eVersion); } if(elf64) { entryPoint = seq.readSQword(); // TODO: UQ programOffset = seq.readSQword(); sectionOffset = seq.readSQword(); } else { entryPoint = seq.readUDword(); programOffset = seq.readUDword(); sectionOffset = seq.readUDword(); } seq.readUDword(); // unused machine flags seq.readUWord(); // unused ELF header size /* progHeaderSize = */ seq.readUWord(); progHeaderCount = seq.readUWord(); /* sectHeaderSize = */ seq.readUWord(); sectHeaderCount = seq.readUWord(); sectHeaderStringIndex = seq.readUWord(); loadProgramHeaders(seq); loadSectionHeaders(seq); } private void loadProgramHeaders(ByteSequence seq) { if(progHeaderCount <= 0) { return; } programHeaders = new ArrayList<>(progHeaderCount); seq.seek(programOffset); for(int i = 0; i < progHeaderCount; i++) { programHeaders.add(new ProgramHeader(seq, elf64)); } } private void loadSectionHeaders(ByteSequence seq) { if(sectHeaderCount <= 0) { return; } sectionHeaders = new ArrayList<>(sectHeaderCount); seq.seek(sectionOffset); for(int i = 0; i < sectHeaderCount; i++) { sectionHeaders.add(new SectionHeader(seq, elf64)); } } public SectionHeader getStringSection() { return sectionHeaders.get(sectHeaderStringIndex); } public long getEntryPoint() { return entryPoint; } public boolean has64BitHeader() { return elf64; } public boolean has64BitCode() { return machine == Machine.X86_64; } public List<ProgramHeader> getProgramHeaders() { return programHeaders; } public List<SectionHeader> getSectionHeaders() { return sectionHeaders; } }
Java
package kianxali.loader.elf; import kianxali.loader.ByteSequence; public class ELFSymbol { public enum Type { STT_NOTYPE, // unspecified STT_OBJECT, // data object STT_FUNC, // code object STT_SECTION, // symbol associated with a section STT_FILE, // symbol name is a file name UNKNOWN } private Type type; private final long nameIndex, value, size; private int sectionIndex; private String attachedName; public ELFSymbol(ByteSequence seq, boolean elf64) { short symType; nameIndex = seq.readUDword(); if(elf64) { symType = seq.readUByte(); seq.readUByte(); // skip "other" sectionIndex = seq.readUWord(); value = seq.readSQword(); size = seq.readSQword(); } else { value = seq.readUDword(); size = seq.readUDword(); symType = seq.readUByte(); seq.readUByte(); // skip "other" sectionIndex = seq.readUWord(); } switch(symType & 0xF) { case 0: type = Type.STT_NOTYPE; break; case 1: type = Type.STT_OBJECT; break; case 2: type = Type.STT_FUNC; break; case 3: type = Type.STT_SECTION; break; case 4: type = Type.STT_FILE; break; default: type = Type.UNKNOWN; } } public Type getType() { return type; } public long getNameIndex() { return nameIndex; } public long getValue() { return value; } public long getSize() { return size; } public int getSectionIndex() { return sectionIndex; } public void attachName(String name) { this.attachedName = name; } public String getAttachedName() { return attachedName; } }
Java
package kianxali.loader.elf; import kianxali.loader.ByteSequence; public class ELFRelocation { public enum Type { JUMP_SLOT, UNKNOWN }; private long address; private long entryIndex; private long addend; private Type type; public ELFRelocation(ByteSequence seq, boolean hasAddend, boolean elf64) { long typ; if(elf64) { address = seq.readSQword(); long info = seq.readSQword(); if(hasAddend) { addend = seq.readSQword(); } typ = (info & 0xFFFFFFFFL); entryIndex = info >> 32; } else { address = seq.readUDword(); long info = seq.readUDword(); if(hasAddend) { addend = seq.readSDword(); } typ = (info & 0xFF); entryIndex = info >> 8; } if(typ == 7) { type = Type.JUMP_SLOT; } else { type = Type.UNKNOWN; } } public long getAddress() { return address; } public long getAddend() { return addend; } public long getInfoIndex() { return entryIndex; } public Type getType() { return type; } }
Java
package kianxali.loader.elf; import kianxali.loader.ByteSequence; public class ProgramHeader { public enum Type { PT_NULL, // Unused program header PT_LOAD, // Loadable program segment PT_DYNAMIC, // Dynamic linking information PT_INTERP, // Program interpreter, e.g. ld-linux PT_NOTE, // Auxiliary information UNKNOWN }; private Type type; private long flags, fileOffset, virtAddr, physAddr; private long segmentSize, memSize, align; public ProgramHeader(ByteSequence seq, boolean elf64) { int pType = (int) seq.readUDword(); switch(pType) { case 0: type = Type.PT_NULL; break; case 1: type = Type.PT_LOAD; break; case 2: type = Type.PT_DYNAMIC; break; case 3: type = Type.PT_INTERP; break; case 4: type = Type.PT_NOTE; break; default: type = Type.UNKNOWN; break; } if(elf64) { flags = seq.readUDword(); fileOffset = seq.readSQword(); virtAddr = seq.readSQword(); physAddr = seq.readSQword(); segmentSize = seq.readSQword(); memSize = seq.readSQword(); align = seq.readSQword(); } else { fileOffset = seq.readUDword(); virtAddr = seq.readUDword(); physAddr = seq.readUDword(); segmentSize = seq.readUDword(); memSize = seq.readUDword(); flags = seq.readUDword(); align = seq.readUDword(); } } public Type getType() { return type; } public boolean isReadable() { return (flags & 1) != 0; } public boolean isWritable() { return (flags & 2) != 0; } public boolean isExecutable() { return (flags & 4) != 0; } // from start of file public long getFileOffset() { return fileOffset; } // for loaded segments: virtual address public long getVirtAddr() { return virtAddr; } // for not loaded segments public long getPhysAddr() { return physAddr; } // size of segment in file public long getSegmentSize() { return segmentSize; } // size in virtual memory public long getMemSize() { return memSize; } public long getAlign() { return align; } }
Java
package kianxali.loader.elf; import kianxali.loader.ByteSequence; public class SectionHeader { public enum Type { SHT_NULL, // ignored SHT_PROGBITS, // program data SHT_SYMTAB, // symbol table SHT_STRTAB, // string table SHT_RELA, // relocation entries SHT_HASH, // symbol hash table SHT_DYNA, // dynamic linking information SHT_NOTE, // notes SHT_NOBITS, // null-initialized data (BSS) SHT_REL, // relocation entries without addends SHT_DYNSYM, // dynamic linker symbol table UNKNOWN }; private final long nameIndex; private Type type; private long flags; private long address, offset, size, info; private long link; // link to other section private long align, entrySize; public SectionHeader(ByteSequence seq, boolean elf64) { nameIndex = seq.readUDword(); int eType = (int) seq.readUDword(); switch(eType) { case 0: type = Type.SHT_NULL; break; case 1: type = Type.SHT_PROGBITS; break; case 2: type = Type.SHT_SYMTAB; break; case 3: type = Type.SHT_STRTAB; break; case 4: type = Type.SHT_RELA; break; case 5: type = Type.SHT_HASH; break; case 6: type = Type.SHT_DYNA; break; case 7: type = Type.SHT_NOTE; break; case 8: type = Type.SHT_NOBITS; break; case 9: type = Type.SHT_REL; break; case 11: type = Type.SHT_DYNSYM; break; default: type = Type.UNKNOWN; } if(elf64) { flags = seq.readSQword(); address = seq.readSQword(); offset = seq.readSQword(); size = seq.readSQword(); link = seq.readUDword(); info = seq.readUDword(); align = seq.readSQword(); entrySize = seq.readSQword(); } else { flags = seq.readUDword(); address = seq.readUDword(); offset = seq.readUDword(); size = seq.readUDword(); link = seq.readUDword(); info = seq.readUDword(); align = seq.readUDword(); entrySize = seq.readUDword(); } } public long getNameIndex() { return nameIndex; } public Type getType() { return type; } public boolean isWritable() { return (flags & 1) != 0; } public boolean isExecutable() { return (flags & 4) != 0; } // virtual address for this section public long getAddress() { return address; } // file offset for this section public long getOffset() { return offset; } public long getSize() { return size; } public long getInfo() { return info; } public long getLink() { return link; } public long getAlign() { return align; } public long getEntrySize() { return entrySize; } }
Java
/** * This package contains loaders for binary image file formats, i.e. files that contain * the memory layout, data and instructions of an application. All loaders implement * the {@link kianxali.loader.ImageFile} interface. */ package kianxali.loader;
Java
package kianxali.loader; import java.io.IOException; import java.nio.file.Path; import java.util.List; import java.util.Map; import kianxali.decoder.Context; /** * An image file represents the main data structure that describes the * memory layout of an executable file. * @author fwi * */ public abstract class ImageFile { protected final ByteSequence imageFile; protected final long fileSize; protected final String fileName; protected ImageFile(Path path) throws IOException { this.imageFile = ByteSequence.fromFile(path); this.fileSize = imageFile.getRemaining(); this.fileName = path.getFileName().toString(); } /** * Returns the file size of the image file * @return the file size of the image file */ public long getFileSize() { return fileSize; } /** * Returns all sections inside the file * @return a list of memory sections in the file */ public abstract List<Section> getSections(); /** * Creates a CPU context for the target CPU described in the file * @return the context matching the expectations of the image file */ public abstract Context createContext(); /** * Returns the virtual memory address of the code entry point * @return the memory address of the code entry point */ public abstract long getCodeEntryPointMem(); /** * Converts a virtual memory address into a file offset * @param memAddress the memory address to convert * @return the offset for that address in the file */ public abstract long toFileAddress(long memAddress); /** * Converts a file offset to a virtual memory address * @param fileOffset the offset inside the file * @return the virtual memory address for the offset */ public abstract long toMemAddress(long fileOffset); /** * Retrieve a map of imported functions * @return a map from memory address to imported function name */ public abstract Map<Long, String> getImports(); /** * Returns the file name of the image file * @return the file name of the image file */ public String getFileName() { return fileName; } /** * Returns a byte sequence for a given virtual memory location * @param memAddress the memory address where the byte sequence should point at * @param locked whether the sequence should be locked for exclusive access * @return a byte sequence pointing at the given memory address */ public ByteSequence getByteSequence(long memAddress, boolean locked) { if(locked) { imageFile.lock(); } try { imageFile.seek(toFileAddress(memAddress)); } catch(Exception e) { imageFile.unlock(); throw e; } return imageFile; } /** * Returns the section that covers a given memory address * @param memAddress the memory address to examine * @return the section that covers the memory address or null */ public Section getSectionForMemAddress(long memAddress) { for(Section sec : getSections()) { if(memAddress >= sec.getStartAddress() && memAddress <= sec.getEndAddress()) { return sec; } } return null; } /** * Checks whether a given virtual memory address is valid in the application's memory layout * @param memAddress the memory address to examine * @return true iff there is a virtual memory section that covers the address */ public boolean isValidAddress(long memAddress) { return getSectionForMemAddress(memAddress) != null; } /** * Checks whether a given virtual memory address could contain executable code * @param memAddress the memory address to examine * @return true iff the address is valid and its associated section is marked as executable */ public boolean isCodeAddress(long memAddress) { Section sect = getSectionForMemAddress(memAddress); return sect != null && sect.isExecutable(); } }
Java
package kianxali.loader; /** * This interface describes a virtual memory section in an image file's memory layout. * @author fwi * */ public interface Section { /** * Returns the name of the memory section * @return the name of the memory section, can also be empty or null depending on the image file type */ String getName(); /** * Returns whether the section is marked as executable in the memory layout * @return true iff the section is marked as executable */ boolean isExecutable(); /** * Returns the virtual memory start address for this section * @return the start address of this section */ long getStartAddress(); /** * Returns the virtual memory end address for this section * @return the end address of this section (inclusive) */ long getEndAddress(); }
Java
/** * This package implements a loader for the PE file format (i.e. Windows EXE and DLL files). * It was implemented according to the "Microsoft Portable Executable and Common Object File Format Specification." */ package kianxali.loader.pe;
Java
package kianxali.loader.pe; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; import java.nio.ByteOrder; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.logging.Logger; import kianxali.decoder.arch.x86.X86Context; import kianxali.decoder.arch.x86.X86CPU.ExecutionMode; import kianxali.decoder.arch.x86.X86CPU.Model; import kianxali.loader.ImageFile; import kianxali.loader.Section; /** * Implements a loader for the PE file format. See the package info for the used * references. * @author fwi * */ public class PEFile extends ImageFile implements AddressConverter { private static final Logger LOG = Logger.getLogger("kianxali.loader.pe"); private DOSStub dosStub; private PEHeader peHeader; private OptionalHeader optionalHeader; private List<PESection> sections; private Imports imports; public PEFile(Path path) throws IOException { super(path); loadHeaders(); loadImports(); } public static boolean isPEFile(Path path) throws IOException { FileInputStream fileIn = new FileInputStream(path.toFile()); DataInputStream dataIn = new DataInputStream(fileIn); int magic = Short.reverseBytes(dataIn.readShort()); dataIn.close(); fileIn.close(); return magic == DOSStub.DOS_MAGIC; } @Override public X86Context createContext() { if(peHeader.is64BitCode()) { return new X86Context(Model.ANY, ExecutionMode.LONG); } else { return new X86Context(Model.ANY, ExecutionMode.PROTECTED); } } @Override public long rvaToMemory(long rva) { return rva + optionalHeader.getImageBase(); } @Override public long rvaToFile(long rva) { for(PESection header : sections) { long memOffset = header.getVirtualAddressRVA(); if(rva >= memOffset && rva <= memOffset + header.getRawSize()) { return rva - memOffset + header.getFilePosition(); } } throw new IllegalArgumentException("invalid rva: " + rva); } @Override public long fileToRVA(long offset) { for(PESection header : sections) { long fileOffset = header.getFilePosition(); if(offset >= fileOffset && offset < fileOffset + header.getRawSize()) { return offset - header.getFilePosition() + header.getVirtualAddressRVA(); } } throw new IllegalArgumentException("invalid offset: " + offset); } @Override public long fileToMemory(long offset) { return rvaToMemory(fileToRVA(offset)); } @Override public long memoryToRVA(long mem) { return mem - optionalHeader.getImageBase(); } @Override public long memoryToFile(long mem) { return rvaToFile(memoryToRVA(mem)); } private void loadHeaders() { imageFile.lock(); imageFile.setByteOrder(ByteOrder.LITTLE_ENDIAN); imageFile.seek(0); dosStub = new DOSStub(imageFile); imageFile.seek(dosStub.getPEPointer()); peHeader = new PEHeader(imageFile); optionalHeader = new OptionalHeader(imageFile); sections = new ArrayList<>(peHeader.getNumSections()); for(int i = 0; i < peHeader.getNumSections(); i++) { sections.add(i, new PESection(imageFile, this)); } imageFile.unlock(); } private void loadImports() { long importsRVA = optionalHeader.getDataDirectoryOffsetRVA(OptionalHeader.DATA_DIRECTORY_IMPORT); if(importsRVA != 0) { imageFile.lock(); try { imageFile.seek(rvaToFile(importsRVA)); imports = new Imports(imageFile, this, peHeader.is64BitCode()); } catch(Exception e) { LOG.warning("Couldn't read imports: " + e.getMessage()); e.printStackTrace(); // continue without imports imports = new Imports(); } finally { imageFile.unlock(); } } else { // no imports imports = new Imports(); } } @Override public List<Section> getSections() { List<Section> res = new ArrayList<>(sections.size()); for(Section section : sections) { res.add(section); } return Collections.unmodifiableList(res); } @Override public long toFileAddress(long memAddress) { return memoryToFile(memAddress); } @Override public long toMemAddress(long fileOffset) { return fileToMemory(fileOffset); } @Override public long getCodeEntryPointMem() { return rvaToMemory(optionalHeader.getEntryPointRVA()); } @Override public Map<Long, String> getImports() { return imports.getAllImports(); } }
Java
package kianxali.loader.pe; public interface AddressConverter { long rvaToMemory(long rva); long rvaToFile(long rva); long fileToRVA(long offset); long fileToMemory(long offset); long memoryToRVA(long mem); long memoryToFile(long mem); }
Java
package kianxali.loader.pe; import kianxali.loader.ByteSequence; import kianxali.loader.Section; public class PESection implements Section { private final String name; private final AddressConverter addrConv; private final long virtualAddressRVA, rawSize, filePosition, characteristics; public PESection(ByteSequence image, AddressConverter conv) { this.addrConv = conv; name = image.readString(8); // ignore unreliable size image.readUDword(); virtualAddressRVA = image.readUDword(); rawSize = image.readUDword(); filePosition = image.readUDword(); // ignore object reloactions image.readUDword(); image.readUDword(); image.readUWord(); image.readUWord(); characteristics = image.readUDword(); } @Override public String getName() { return name; } public long getVirtualAddressRVA() { return virtualAddressRVA; } public long getRawSize() { return rawSize; } public long getFilePosition() { return filePosition; } public boolean isCode() { return (characteristics & 0x20) != 0; } public boolean isInitializedData() { return (characteristics & 0x40) != 0; } public boolean isUninitializedData() { return (characteristics & 0x80) != 0; } @Override public long getStartAddress() { return addrConv.rvaToMemory(virtualAddressRVA); } @Override public long getEndAddress() { return addrConv.rvaToMemory(virtualAddressRVA + rawSize); } @Override public boolean isExecutable() { return isCode(); } }
Java
package kianxali.loader.pe; import java.sql.Date; import kianxali.loader.ByteSequence; public class PEHeader { public static final long PE_SIGNATURE = 0x4550; public enum Machine { X86_32, X86_64 }; private Machine machine; private final int numSections; private final Date timeStamp; public PEHeader(ByteSequence image) { long signature = image.readUDword(); if(signature != PE_SIGNATURE) { throw new RuntimeException("Invalid PE signature"); } int machineCode = image.readUWord(); switch(machineCode) { case 0x14C: machine = Machine.X86_32; break; case 0x8664: machine = Machine.X86_64; break; default: throw new RuntimeException("unknown machine in PE header: " + machineCode); } numSections = image.readUWord(); long timeStampEpoch = image.readUDword(); timeStamp = new Date(timeStampEpoch * 1000); // skip unused information image.skip(12); } public boolean is64BitCode() { return machine == Machine.X86_64; } public int getNumSections() { return numSections; } public Date getTimeStamp() { return timeStamp; } }
Java
package kianxali.loader.pe; import kianxali.loader.ByteSequence; public class DOSStub { public static final int DOS_MAGIC = 0x5A4D; private final long pePointer; public DOSStub(ByteSequence image) { int magic = image.readUWord(); if(magic != DOS_MAGIC) { throw new RuntimeException("Invalid magic"); } image.skip(58); pePointer = image.readUDword(); } public long getPEPointer() { return pePointer; } }
Java